diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/2170-pydantic-dataclasses.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/2170-pydantic-dataclasses.md new file mode 100644 index 0000000000000000000000000000000000000000..a30f94d8279c88b5c7f11dfc1b997ae08f79c623 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/2170-pydantic-dataclasses.md @@ -0,0 +1,80 @@ + +- Start Date: 2021-10-14 +- Proposal PR: n/a +- Github Issue: https://github.com/deepset-ai/haystack/pull/1598 +- Deciders: @tholor + + +## Context and Problem Statement + +Originally we implemented Haystack's primitive based on Python's vanilla `dataclasses`. However, shortly after we realized this causes issues with FastAPI, which uses Pydantic's implementation. We need to decide which version (vanilla Python's or Pydantic's) to use in our codebase. + +## Decision Drivers + +* The Swagger autogenerated documentation for REST API in FastAPI was broken where the dataclasses include non-standard fields (`pd.dataframe` + `np.ndarray`) + +## Considered Options + +* Switch to Pydantic `dataclasses` in our codebase as well. +* Staying with vanilla `dataclasses` and find a workaround for FastAPI to accept them in place of Pydantic's implementation. + +## Decision Outcome + +Chosen option: **1**, because our initial concerns about speed proved negligible and Pydantic's implementation provided some additional functionality for free (see below). + +### Positive Consequences + +* We can now inherit directly from the primitives in the REST API dataclasses, and overwrite the problematic fields with standard types. +* We now get runtime type checks "for free", as this is a core feature of Pydantic's implementation. + +### Negative Consequences + +* Pydantic dataclasses are slower. See https://github.com/deepset-ai/haystack/pull/1598 for a rough performance assessment. +* Pydantic dataclasses do not play nice with mypy and autocomplete tools unaided. In many cases a complex import statement, such as the following, is needed: + +```python +if typing.TYPE_CHECKING: + from dataclasses import dataclass +else: + from pydantic.dataclasses import dataclass +``` + +## Pros and Cons of the Options + +### Switch to Pydantic `dataclasses` + +* Good, because it solves the issue without having to find workarounds for FastAPI. +* Good, because it adds type checks at runtime. +* Bad, because mypy and autocomplete tools need assistance to parse its dataclasses properly. Example: + +```python +if typing.TYPE_CHECKING: + from dataclasses import dataclass +else: + from pydantic.dataclasses import dataclass +``` + +* Bad, because it introduces an additional dependency to Haystack (negligible) +* Bad, because it adds some overhead on the creation of primitives (negligible) + +### Staying with vanilla `dataclasses` + +* Good, because it's Python's standard way to generate data classes +* Good, because mypy can deal with them without plugins or other tricks. +* Good, because it's faster than Pydantic's implementation. +* Bad, because does not play well with FastAPI and Swagger (critical). +* Bad, because it has no validation at runtime (negligible) + +## Links + +* https://pydantic-docs.helpmanual.io/usage/dataclasses/ +* https://github.com/deepset-ai/haystack/pull/1598 +* https://github.com/deepset-ai/haystack/issues/1593 +* https://github.com/deepset-ai/haystack/issues/1582 +* https://github.com/deepset-ai/haystack/pull/1398 +* https://github.com/deepset-ai/haystack/issues/1232 + + diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3550-csv-converter.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3550-csv-converter.md new file mode 100644 index 0000000000000000000000000000000000000000..aa905dd2162ff974c9a394b3dbcc2bd78ae9c53a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3550-csv-converter.md @@ -0,0 +1,86 @@ +- Start Date: 2022-11-28 +- Proposal PR: [#3638](https://github.com/deepset-ai/haystack/issues/3638) +- Github Issue: [#3550](https://github.com/deepset-ai/haystack/issues/3550) + +# Summary + +Using Haystack for questions answering pipelines is prettier easy, but most of the time users have CSV files containing +their knowledge base with questions and there associated answers. +Unfortunately there is no easy way to dynamically update the knowledge base or import new data from CSV though rest API +using YAML, as there are no CSV parser. + +Having a basic way to dynamically index a CSV file always requires development of a new nodes. + +# Basic example + +To define an FAQ query and **indexing** pipeline we would then simply do : +```yaml +# To allow your IDE to autocomplete and validate your YAML pipelines, name them as .haystack-pipeline.yml + +version: ignore + +components: # define all the building-blocks for Pipeline + - name: DocumentStore + type: ElasticsearchDocumentStore + params: + host: localhost + embedding_field: question_emb + embedding_dim: 384 + excluded_meta_data: + - question_emb + similarity: cosine + - name: Retriever + type: EmbeddingRetriever + params: + document_store: DocumentStore # params can reference other components defined in the YAML + embedding_model: sentence-transformers/all-MiniLM-L6-v2 + scale_score: False + - name: CSVConverter + type: CsvTextConverter + +pipelines: + - name: indexing + nodes: + - name: CSVConverter + inputs: [File] + - name: Retriever + inputs: [ CSVConverter ] + - name: DocumentStore + inputs: [ Retriever ] +``` + +# Motivation + +Using YAML pipeline description it's not possible to describe a CSV FAQ indexing pipeline that takes CSV files as input +containing questions and answers and index them. It's a basic usage that still requires coding. + +As we are presenting a tutorial `Utilizing Existing FAQs for Question Answering` it would be great to have this basic +node so that anyone can quickly run an FAQ Question Answering pipeline using only a YAML description and import their +CSV though REST API. + +# Detailed design + +I've added a new node: **`CsvTextConverter`** . It takes a file input, parse it as FAQ CSV file having `question` and `answer` column +and outputs `Document`s. + +For now the node is very simple: can only handle a fixed CSV format and no other tabular data. It also +can't produce documents that are not of type `text`. These shortcomings can be addressed in later enhancements. + +# Drawbacks + +We could consider that developing this custom node is easy and a good way to learn Haystack, +but casual users shouldn't need to know this much before being able to index CSV files. + +# Alternatives + +Didn't consider any other design. + +# Adoption strategy + +It doesn't introduce any breaking change, any users having FAQs pipeline would be able to use the official nodes instead +of their existing ones. + +# How we teach this + +This may require updating this tutorial [Utilizing Existing FAQs for Question Answering](https://haystack.deepset.ai/tutorials/04_faq_style_qa) +and to document those 2 nodes. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3558-embedding_retriever.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3558-embedding_retriever.md new file mode 100644 index 0000000000000000000000000000000000000000..5c76f771793151d3175b9d032c281a3bff0a556f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3558-embedding_retriever.md @@ -0,0 +1,131 @@ +- Start Date: 2022-11-11 +- Proposal PR: https://github.com/deepset-ai/haystack/pull/3558 +- Github Issue: + +> ⚠️ Superseded by https://github.com/deepset-ai/haystack/blob/main/proposals/text/5390-embedders.md + + # Summary + +- Current EmbeddingRetriever doesn't allow Haystack users to provide new embedding methods and is + currently constricted to farm, transformers, sentence transformers, OpenAI and Cohere based + embedding approaches. Any new encoding methods need to be explicitly added to Haystack + and registered with the EmbeddingRetriever. + + +- We should allow users to easily plug-in new embedding methods to EmbeddingRetriever. For example, a Haystack user should be able to + add custom embeddings without having to commit additional code to Haystack repository. + + # Basic example + EmbeddingRetriever is instantiated with: + + ``` python + retriever = EmbeddingRetriever( + document_store=document_store, + embedding_model="sentence-transformers/multi-qa-mpnet-base-dot-v1", + model_format="sentence_transformers", + ) + ``` +- The current approach doesn't provide a pluggable abstraction point of composition but + rather attempts to satisfy various embedding methodologies by having a lot of + parameters which keep ever expanding. + + +- The new approach allows creation of the underlying embedding mechanism (EmbeddingEncoder) + which is then in turn plugged into EmbeddingRetriever. For example: + + ``` python + encoder = SomeNewFancyEmbeddingEncoder(api_key="asdfklklja", + query_model="text-search-query", + doc_model="text-search-doc") + ``` + +- EmbeddingEncoder is then used for the creation of EmbeddingRetriever. EmbeddingRetriever + init method doesn't get polluted with additional parameters as all of the peculiarities + of a particular encoder methodology are contained on in its abstraction layer. + + ``` python + retriever = EmbeddingRetriever( + document_store=document_store, + encoder=encoder + ) + ``` + + # Motivation + +- Why are we doing this? What use cases does it support? What is the expected outcome? + + We could certainly keep the current solution as is; it does implement a decent level + of composition/decoration to lower coupling between EmbeddingRetriever and the underlying + mechanism of embedding (sentence transformers, OpenAI, etc). However, the current mechanism + in place basically hard-codes available embedding implementations and prevents our users from + adding new embedding mechanism by themselves outside of Haystack repository. We also might + want to have a non-public dC embedding mechanism in the future. In the current design a non-public + dC embedding mechanism would be impractical. In addition, the more underlying implementations we + add we'll continue to "pollute" EmbeddingRetriever init method with more and more parameters. + This is certainly less than ideal long term. + + +- EmbeddingEncoder classes should be subclasses of BaseComponent! As subclasses of BaseComponent, + we can use them outside the EmbeddingRetriever context in indexing pipelines, generating the + embeddings. We are currently employing a kludge of using Retrievers which is quite counter-intuitive + and confusing for our users. + + +- EmbeddingEncoder classes might sound overly complicated, especially with a distinguishing mechanism + name pre-appended (i.e CohereEmbeddingEncoder). Therefore, we'll adopt Embedder + naming scheme, i.e. CohereEmbedder, SentenceTransformerEmbedder and so on. + + # Detailed design + +- Our new EmbeddingRetriever would still wrap the underlying encoding mechanism in the form of + _BaseEmbedder. _BaseEmbedder still needs to implement methods: + - embed_queries + - embed_documents + + +- The new design approach differs is in the creation of EmbeddingRetriever - rather than hiding the underlying encoding + mechanism one could simply create the EmbeddingRetriever with a specific encoder directly. For example: + + ``` + retriever = EmbeddingRetriever( + document_store=document_store, + encoder=OpenAIEmbedder(api_key="asdfklklja", model="ada"), + #additional EmbeddingRetriever-abstraction-level parameters + ) + ``` + +- If the "two-step approach" of EmbeddingRetriever initialization is no longer the ideal solution (issues with current + schema generation and loading/saving via YAML pipelines) we might simply add the EmbeddingRetriever + class for every supported encoding approach. For example, we could have OpenAIEmbeddingRetriever, CohereEmbeddingRetriever, + SentenceTransformerEmbeddingRetriever and so on. Each of these retrievers will delegate the bulk of the work to an + existing EmbeddingRetriever with a per-class-specific Embedder set in the class constructor (for that custom + encoding part). We'll get the best of both worlds. Each EmeddingRetriever will have only the relevant primitives + parameters for the **init()** constructor; the underlying EmbeddingRetriever attribute in EmeddingRetriever + will handle most of the business logic of retrieving, yet each retriever will use an appropriate per-class-specific + Embedder for the custom encoding part. + + + + # Drawbacks +- The main shortcoming are: + - The "two-step approach" in EmbeddingRetriever initialization + - Likely be an issue for the current schema generation and loading/saving via YAML pipelines (see solution above) + - It is a API breaking change so it'll require code update for all EmbeddingRetriever usage both in our codebase and for Haystack users + - Can only be done in major release along with other breaking changes + + # Alternatives + + We could certainly keep everything as is :-) + + # Adoption strategy +- As it is a breaking change, we should implement it for the next major release. + + # How do we teach this? +- This change would require only a minor change in documentation. +- The concept of embedding retriever remains, just the mechanics are slightly changed +- All docs and tutorials need to be updated +- Haystack users are informed about a possibility to create and use their own embedders for embedding retriever. +- # Unresolved questions + + Optional, but suggested for first drafts. What parts of the design are still + TBD? diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3665-prompt-node.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3665-prompt-node.md new file mode 100644 index 0000000000000000000000000000000000000000..fccf7527c93315f5084fa125fde6ce3f2a5f4fbf --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3665-prompt-node.md @@ -0,0 +1,445 @@ +- Start Date: 2022-12-04 +- Proposal PR: https://github.com/deepset-ai/haystack/pull/3665 +- Github Issue: https://github.com/deepset-ai/haystack/issues/3306 +- Example Colab notebook: https://colab.research.google.com/drive/1bOIxb8cnpTrpMtTSBArY9FJlL59Ar4K_?usp=sharing + + # Summary + +- The PromptNode class is the central abstraction in Haystack's large language model (LLM) support. + Such a component supports multiple NLP tasks out-of-the-box. PromptNode allows users to + perform multiple tasks, such as summarization, question answering, question generation etc. using a single, + unified model within the Haystack framework. + + +- One of the benefits of PromptNode is that it allows users to define and add additional tasks + that are supported by the model. This can enable users to extend the capabilities of the model and + to use it for a wider range of NLP tasks within the Haystack ecosystem. + + + # Basic example + + PromptNode is instantiated with the underlying LLM model and prompted by using natural language: + + ``` python + from haystack.nodes.llm import PromptNode + pn = PromptNode(model_name_or_path="google/flan-t5-base") + pn("What is the capital of Germany?") + + ---------------------------------------------------------------------------- + ['berlin'] + ``` + + # Motivation + + +- The use of large language models (LLMs) has become increasingly popular in natural language + processing (NLP) due to their ability to capture complex and nuanced patterns in language. + PromptNode allows users to leverage the power of LLMs in the Haystack ecosystem, and + to perform multiple NLP tasks using a single, unified model. This provides a flexible and efficient + tool for NLP in Haystack, and can enable users to improve the performance and reliability of their applications. + + +- Modern LLM support hundreds if not thousands of tasks. Aside from PromptNode we'll define prompt templates for + dozen or so most popular NLP tasks and allow users to register prompt templates for additional tasks. The + extensible and modular approach would allow users to extend the capabilities of the model and to use + it for a wider range of NLP tasks within the Haystack ecosystem. Prompt engineers would define templates + for each NLP task and register them with the PromptNode. The burden of defining the best templates for each task + would be on the prompt engineers and not on the users. + + +- The use of templates to define NLP tasks can make it easier for users to use PromptNode, as + they do not need to know the details of how the model works or how to define tasks for it. This can + reduce the learning curve and make it easier for users to get started with PromptNode and + to leverage the power of LLMs in Haystack. + + +- The extensible and modular approach of PromptNode allows users to easily add support for + additional templates, even on-the-fly, which can enable them to extend the capabilities of the model and to use it for + a wider range of NLP tasks. This can provide users with more flexibility and control over the model, + and can enable them to tailor it to their specific needs and applications. + + # Detailed design + +- The PromptNode class is the most important abstraction in Haystack's large language model (LLM) support. + In addition to PromptNode class, we'll also define a set of prompt templates for the most popular NLP tasks. + + +- NLP prompt templates will be represented by `PromptTemplate` class. + + ``` python + class PromptTemplate(BaseTemplate): + + name: str + prompt_text: str + input_variables: List[str] + + ```` + + PromptNode would, out-of-the-box, support 10-20 default NLP tasks defined by PromptTemplate instances. However, it would + allow registering additional templates with PromptNode. + + +- The prompt templates for default tasks (question-answering,question-generation, summarization etc.) could be examined by the user + using `get_prompt_templates_names` class method of the PromptNode. For example: + + ``` python + from haystack.nodes.llm import PromptNode + PromptNode.get_prompt_templates_names() + + ---------------------------------------------------------------------------- + ['question-answering', + 'question-generation', + 'conditioned-question-generation', + 'summarization', + 'question-answering-check'] + ``` + + +- PromptNode supports natural language prompting (using `prompt` method) by specifying prompt template method parameter. For example: + + ``` python + from haystack.nodes.llm import PromptNode + pn = PromptNode(model_name_or_path="google/flan-t5-base") + pn.prompt("question-generation", documents=["Berlin is the capital of Germany."]) + + ---------------------------------------------------------------------------- + ['What is the capital of Germany?'] + ``` + +- PromptNode supports selecting a particular default template for a certain task (e.g. question-generation) and then subsequently + using the selected template until user changes the current template. For example: + + ``` python + qa = pn.use_prompt_template("deepset/question-generation-v2") + qa(documents=["Berlin is the capital of Germany."]) + + ---------------------------------------------------------------------------- + ['What is the capital of Germany?'] + ``` + +- The addition of new prompt templates is supported by the `add_prompt_template` method. For example: + + ``` python + from haystack.nodes.llm import PromptNode + PromptNode.add_prompt_template(PromptTemplate(name="sentiment-analysis", + prompt_text="Please give a sentiment for this context. Answer with positive, " + "negative or neutral. Context: $documents; Answer:", + input_variables=["documents"])) + PromptNode.get_prompt_templates_names() + + ---------------------------------------------------------------------------- + ['question-answering', + 'question-generation', + 'conditioned-question-generation', + 'summarization', + 'question-answering-check', + 'sentiment-analysis'] + ``` + +- Users can inspect registered prompt templates with two class methods: `get_prompt_templates_names` and `get_prompt_templates`. The first + method, as we have seen, simply lists the names of the supported templates while the second method returns the list of `PromptTemplate` + instances, in readable format, allowing users to inspect the actual prompt template used and the templates input parameters. + + ``` python + from haystack.nodes.llm import PromptNode + PromptNode.get_prompt_templates() + + ---------------------------------------------------------------------------- + [PromptTemplate(name="sentiment-analysis", + prompt_text="Please give a sentiment for this context. Answer with positive, " + "negative or neutral. Context: $documents; Answer:", + input_variables=["documents"], ...] + ``` + + + +- However, aside from existing templates, users should also be able to use "on-the-fly" templates without registering them first. For example: + + ``` python + from haystack.nodes.llm import PromptNode + pn = PromptNode(model_name_or_path="google/flan-t5-base") + prompt_template = PromptTemplate(name="sentiment-analysis", + prompt_text="Please give a sentiment for this context. " + "Answer with positive, negative or neutral. Context: $documents; Answer:", + input_variables=["documents"]) + pn.prompt(prompt_template, documents=["I really enjoyed the recent movie."]) + + ---------------------------------------------------------------------------- + ['positive'] + ``` + This, "on-the-fly" approach might be handy if users want to simply try stuff out + + +- Therefore, the most central API method of the PromptNode class would be the `prompt` method with the following signature: + ``` python + def prompt(self, prompt_template: Union[str, PromptTemplate] = None, *args, **kwargs) -> List[str]: + ``` + + +- PromptNode class `__init__` constructor, aside from the `model_name_or_path` parameter would also have a + `prompt_template` parameter which would serve as the current and default template of the PromptNode. + +- ``` python + def __init__(self, model_name_or_path: str = "google/flan-t5-base", prompt_template: Union[str, PromptTemplate] = None): + ``` + + If the `prompt_template` is not specified in the `PromptNode` init method then user is required to specify the + template in the prompt method: + + ``` python + from haystack.nodes.llm import PromptNode + pn = PromptNode(model_name_or_path="google/flan-t5-base") + pn.prompt("question-generation", documents=["Berlin is the capital of Germany."]) + + ---------------------------------------------------------------------------- + ['What is the capital of Germany?'] + ``` + + Otherwise, when the `PromptNode` is initialized with a prompt template user can invoke the `PromptNode` directly + + ``` python + from haystack.nodes.llm import PromptNode + pn = PromptNode(model_name_or_path="google/flan-t5-base", prompt_template="question-generation") + pn(documents=["Berlin is the capital of Germany."]) + + ---------------------------------------------------------------------------- + ['What is the capital of Germany?'] + ``` + +- Template parameters verification + + All template input parameters will be verified to match the template definition and the corresponding runtime + parameters for the input variables will be checked for type and value. For example: + + ``` python + from haystack.nodes.llm import PromptNode + on = PromptNode(model_name_or_path="google/flan-t5-base") + on.prompt("question-generation", some_unknown_param=["Berlin is the capital of Germany."]) + + ---------------------------------------------------------------------------- + ValueError Traceback (most recent call last) + in + 1 # tasks parameters are checked + ----> 2 sa(some_param=[Document("Berlin is the capital of Germany.")]) + + 2 frames + /usr/local/lib/python3.8/dist-packages/haystack/nodes/llm/multi_task.py in __call__(self, *args, **kwargs) + 34 if set(template_dict.keys()) != set(self.input_variables): + 35 available_params = set(list(template_dict.keys()) + list(set(kwargs.keys()))) + ---> 36 raise ValueError(f"Expected prompt params {self.input_variables} but got {list(available_params)}") + 37 + 38 template_dict["prompt_template"] = self.prompt_text + + ValueError: Expected prompt params ['documents'] but got ['some_unknown_param'] + ``` + +- Pipelines + + Even though we can use PromptNode directly its real power lies in using pipelines and Haystack. For example, we + can retrieve documents from the document store using the query and then inject the retrieved documents into documents + as a parameter to the selected PromptNode template. For example: + + ``` python + from haystack.pipelines import PromptNode + top_k = 3 + query = "Who are the parents of Arya Stark?" + retriever = EmbeddingRetriever(...) + pn = PromptNode(model_name_or_path="google/flan-t5-base", prompt_template="question-answering") + + pipe = Pipeline() + pipe.add_node(component=retriever, name="Retriever", inputs=["Query"]) + pipe.add_node(component=pn, name="prompt_node", inputs=["Retriever"]) + + output = pipe.run(query=query, + params={"Retriever": {"top_k": top_k}}, + questions=[query for n in range(0, top_k)], + #documents parameter we need for this task will be automatically populated by the retriever + ) + + output["results"] + ``` + + - However, we are still not utilizing the full power of Haystack pipelines. What if we could use more than + one PromptNode in the pipeline? Perhaps we could first retrieve documents from the retriever, pass it + to first PromptNode that will generate questions from these documents, and then add a + second PromptNode component that will answer those generated questions given the documents as the + context. Here is how we can do exactly that: + + ``` python + top_k = 3 + query = "Who are the parents of Arya Stark?" + retriever = EmbeddingRetriever(...) + model = PromptModel(model_name_or_path="google/flan-t5-small") + + qg = PromptNode(prompt_template="question-generation", prompt_model=model, output_variable="questions") + qa = PromptNode(prompt_template="question-answering", prompt_model=model) + + pipe = Pipeline() + pipe.add_node(component=retriever, name="Retriever", inputs=["Query"]) + pipe.add_node(component=qg, name="qg", inputs=["Retriever"]) + pipe.add_node(component=qa, name="qa", inputs=["qg"]) + + result = pipe.run(query=query) + + print(result["results"]) + + ``` + + The above example shows how we can use PromptNode in a pipeline and how we can bind the results of one + PromptNode to the input of another PromptNode. The `output_variable` parameter used in the constructor of the + question answering node, and assigned value `questions` indicates that variable `questions` could be resolved by any + downstream pipeline node. In this particular case, the output of the question generation node will be passed to downstream + nodes, and answering node will use that `questions` variable to inject its stored value into the `questions` parameter of + the question answering template. + + A careful reader of this proposal will also notice that we are using the same PromptModel instance for both PromptNodes. + This is done mainly for reuse as the PromptModel instance could be a locally run LLM and we don't want to load it + multiple times. + + As LLMs are very resource intensive we can also envision a scenario where we would like to use a remote LLM service. + In such cases we can use multiple instances of a PromptNode in a pipeline directly thus bypassing PromptModel altogether. + + + - Pipeline YAML config file + + Let's recreate the above pipeline using a YAML config file and a declarative way of defining a pipeline. + + ```yaml + + components: + + # can go in pipeline + - name: prompt_node + params: + prompt_template: template + model_name_or_path: model + output_variable: "questions" + type: PromptNode + + # can go in pipeline + - name: prompt_node_2 + params: + prompt_template: "question-answering" + model_name_or_path: deepset/model-name + type: PromptNode + + # not in pipeline - only needed if you're reusing the model across multiple PromptNode in a pipeline + # and hidden from users in the Python beginner world + - name: model + params: + model_name_or_path: google/flan-t5-xl + type: PromptModel + + # not in pipeline + - name: template + params: + name: "question-generation-v2" + prompt_text: "Given the following $documents, please generate a question. Question:" + input_variables: documents + type: PromptTemplate + + pipelines: + - name: question-generation-answering-pipeline + nodes: + - name: EmbeddingRetriever + inputs: [Query] + - name: prompt_node + inputs: [EmbeddingRetriever] + - name: prompt_node_2 + inputs: [prompt_node] + ``` + First of all, notice how we reuse the resource heavy PromptModel instance across multiple PromptNode instances. And + although we could have used already registered `question-generation` prompt template, we decided to define a new one + called `question-generation-v2` and as such set it as the default template for the first PromptNode. We also defined + the output of the first PromptNode as `questions` and used that variable in the second PromptNode. + + In conclusion, we can see that the YAML config file is a mirror image of the previous code centric pipeline + example and also a very powerful way of defining a pipeline. + + + + - Default tasks/prompts to be added to PromptNode + + [Muffin]: + - Summarization + - Natural Language Inference + - Multiple-Choice QA + - Translation + - Sentiment Analysis + - Extractive QA + - Structured Data to Text + - Coreference Resolution + - Code Repair + - Code Error Generation + - Dialogue Context Generation + - Closed-Book QA + - Next Sentence Prediction + - Paraphrasing Identification + - Conversational Question Answering + - Topic Classification + - Mathematical QA + - Dialog Next Turn Prediction + - Grammatical Acceptability + - Punctuation fixing + + [T0-SF]: + - Adversarial QA + - Question Generation + - Commonsense Reasoning + - Title Generation + - Dialogue Turn Prediction + - Predict Span Indices + - Context Generation + + [NIV2]: + - Program Execution + - Text Matching + - Toxic Language Detection + - Cause Effect Classification + - Information Extraction + - Textual Entailment + - Wrong Candidate Generation + - Named Entity Recognition + - Commonsense Classification + - Fill-in-the-blank + - Text Completion + - Sentence Composition + - Question Understanding + + [CoT Reasoning]: + - Explanation Generation + - Generate Question And Answer + - Grade School Math Word Problems + - Algebraic Question Answering + - Common Sense Reasoning Over Entities + - Common Sense Reasoning For QA + - Passage Based Question Answering + - Sense-Making And Explanation + + # Drawbacks +- One potential drawback of PromptNode is that it may require a significant amount of computational resources + to use. This may limit its use in applications or environments where there are constraints on the available hardware + or software resources. + + +- Due to current pipeline design limitations PromptTemplate has to be a subclass of BaseComponent. This might slightly + confuse some users who are already familiar with Haystack components. We will mitigate this issue in subsequent releases + as we refactor the pipeline design. All in all, PromptTemplate will be a thin class with minimal inheritance signature from some base class. + + + + # Alternatives + +- One alternative to PromptNode is to continue to use separate models for each NLP task in Haystack. This + can enable users to tailor the model to the specific requirements of each task, and to potentially improve the + performance of the model for that task by additional fine-tuning or model adaptation via GPL. However, using separate + models may require these complex and computationally intensive training and deployment processes, and may not be as + efficient or flexible as using a single, unified model. + + # Adoption strategy +- This is not a breaking change proposal and we should implement it immediately. + + # How do we teach this? +- This change would require change in documentation. +- We can provide examples of how to use PromptNode in Haystack pipelines via tutorials. +- Docs and tutorials need to be updated diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3695-demo-repository.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3695-demo-repository.md new file mode 100644 index 0000000000000000000000000000000000000000..bbfeed38b379490707fad25d1222e6f986390615 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3695-demo-repository.md @@ -0,0 +1,77 @@ +- Start Date: 2022-12-12 +- Proposal PR: https://github.com/deepset-ai/haystack/pull/3695 +- Github Issue: (if available, link the issue containing the original request for this change) + +# Summary + +A new git repository is created to host NLP applications showcasing Haystack's features. + +# Basic example + +A git repository was already created on Github as an example: + +https://github.com/deepset-ai/haystack-demos + +# Motivation + +NLP applications showcasing Haystack's capabilities can be an invaluable learning resource +for its users, but at this moment we don't fully take advantage of the only one demo we have +as a documentation source. + +This proposal aims at overcoming that limitation in two ways: +- Define better requirements for a demo application so that users can learn from it. +- Make it easier to add more demo applications showcasing Haystack. + +# Detailed design + +Every demo has a descriptive name that will be used as its identifier. + +Every demo lives in a dedicated folder named after its identifier at the root of the repo, and +provides all the resources needed to understand the code, run the application locally or deploy it +remotely on a server. + +Every demo provides a README.md file containing the following information: +- A brief description of the application and what's its goal. +- Explicit mention of which NLP use case is implemented: for example "QA", or "Document Retrieval". +- Detailed instructions about how to run the application locally. +- Any hardware requirement and the limitations when not provided (for example, a GPU device). +- How to modify and test the code, and how to contribute changes. + +The code of a demo application should be tested whenever possible, and at least some of the +tests should be able to run in the repo CI system. Every demo has a dedicated Workflow defined +in a file named after its identifier. The workflow runs only when files in the demo folder are +modified. + +In case the CI is needed for continuous deployment, or for building artifacts, a demo can have +more than one workflow file defined, named after its identifier plus a descriptive suffix, for +example: `my_demo_identifier.yml` for tests, `my_demo_identifier_docker.yml` for building a +Docker image, `my_demo_identifier_deploy.yml` for continuous delivery. + +# Drawbacks + +- The code of the existing demo would be removed from Haystack and potentially become harder to + find for existing contributors. +- The proposed design dictates a list of new requirements for a demo that will take time to + implement. + +# Alternatives + +- Leave things as they are +- Implement the design proposal to a subfolder of Haystack's git repository + +# Adoption strategy + +Adoption will be mostly driven by communicating the changes to the community and monitoring the +traffic in the new Github repository: interacting with the existing demo will not be affected +but accessing the code would. + +# How we teach this + +- A link to the demo repository will be added to the web page of the [demo itself](https://haystack-demo.deepset.ai/). +- Haystack's README and documentation will mention where to find the code for the demos. +- [Haystack Home](https://haystack.deepset.ai) will host a whole section dedicated to Haystack demos + (detailing the aforementioned section is out of scope for this proposal). + +# Unresolved questions + +N/A. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3784-shaper.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3784-shaper.md new file mode 100644 index 0000000000000000000000000000000000000000..52a057dcd6f18353ed988a611ba9f5b6149f9a9a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3784-shaper.md @@ -0,0 +1,272 @@ +- Title: Shaper +- Decision driver: Vladimir +- Start Date: 2022-12-29 +- Proposal PR: https://github.com/deepset-ai/haystack/pull/3784/ + +# Summary + +Input/Output Shaper (Shaper) is a new pipeline component that can invoke arbitrary, registered functions, on the +invocation context (query, documents etc.) of a pipeline and pass the new/modified variables further down the pipeline. + +# Basic example + +In the following example, we'll use Shaper to add a new variable `questions` to the invocation context. +`questions` is a copy of query variable. This functionality of Shaper is useful when we simply want to +rename a variable in the invocation context e.g. in cases where the PromptNode template is expecting a variable +'questions' rather than 'query'. + + +```python + + from haystack import Pipeline, Document + + with open("tmp_config.yml", "w") as tmp_file: + tmp_file.write( + f""" + version: ignore + components: + - name: shaper + params: + inputs: + query: + output: questions + type: Shaper + pipelines: + - name: query + nodes: + - name: shaper + inputs: + - Query + """ + ) + pipeline = Pipeline.load_from_yaml(path="tmp_config.yml") + result = pipeline.run( + query="What can you tell me about Berlin?", + documents=[Document("Berlin is an amazing city."), Document("I love Berlin.")], + ) + assert result + # query has been renamed to questions + assert isinstance(result["meta"]["invocation_context"]["questions"], str) + + +``` + +# Motivation + +We need Shaper to support the use cases where we want to easily add new variables to the pipeline invocation context. +These new variables hold values which are a result of some arbitrary function invocation on the existing variables +in the invocation context. + +Shaper is especially useful when combined with PromptNode(s). Aside from simply renaming variables to match +the templates of PromptNodes, we can also use Shaper to add new variables to the invocation context. Often +these new variables are the result of some arbitrary function invocation on the existing variables in the +invocation context. + +The original idea for Shaper is related to question answering use case using PromptNode. In QA, query string variable +passed to a pipeline run method needs to be expanded to a list of strings with the list size matching the size of the +documents list. Therefore, we can use the query as the question to pose to all the documents in the documents list. + +The expected outcome of using Shaper is that we can easily add new variables to the invocation context so they can +match the prompt templates of PromptNodes. Multiple Shaper components can be used in a pipeline to modify the +invocation context as needed. + + +# Detailed design + +The Shaper component is most often defined in pipelines YAML file. The YAML component definition consists of the +params block: + +```yaml + components: + - name: shaper + params: + inputs: + query: + func: expand + output: questions + params: + expand_target: query + size: + func: len + params: + - documents + documents: + func: concat + params: + docs: documents + delimiter: " " + type: Shaper + pipelines: + - name: query + nodes: + - name: shaper + inputs: + - Query +``` + +The params block consists of the inputs list. Each item in the inputs list is a dictionary with the key being the +invocation context variable that we want to modify. + +In the example above, we have two items in the inputs list. The first item is a dictionary with the key `query` and the +second item is a dictionary with the key `documents`. + +For the query variable, we want to invoke the function `expand` and store the result in the variable `questions`. +The `expand` function takes two keyword parameters: `expand_target` and `size`. The `expand_target` parameter is the +name of the variable in the invocation context that we want to expand. The `size`parameter is a result of the `len` +function invocation on the variable `documents`. + +For the documents variable, we want to invoke the function `concat` and store the result in the same variable. +Therefore, after the invocation, the documents variable will hold a result of `concat` function invocation while +we'll also have a new variable `questions` in the invocation context. The questions variable will hold a result of +`expand` function invocation. + +The important thing to note here is that we can invoke functions with both keyword and positional parameters. Function +`len` is an example of a function that takes non-keyword positional parameters. The `concat` and `expand` function +take keyword parameters. These functions can also be invoked with positional parameters but that is not recommended. + + +### Default parameters + +The Shaper component can also be configured with default parameters. Default parameters are used when we +don't specify the parameters for a function invocation. The default parameters are specified in the function definition. + +For example, in the YAML snippet definition below, we have a function `expand` that takes two keyword parameters: +`expand_target` and `size`. However, we haven't specified either of these parameters in the YAML config. This is +possible because we assume that the first parameter is always the variable we want to invoke the function on. In this +case, the variable `query`. The second parameter is the `size` of the list we want to expand the variable to. Here we +have also defined a helper function in Shaper called `expand:size` that calculates the default value of +this parameter - `len(documents)`. + +Therefore, the `expand` function, described below, will be invoked with the following parameters: `query` +and `len(documents)` + +```yaml + components: + - name: shaper + params: + inputs: + query: + func: expand + output: questions + type: Shaper + pipelines: + - name: query + nodes: + - name: shaper + inputs: + - Query + +``` + +We need the "default parameter" functionality to support YAML files definitions that are more concise and less +error-prone. + + +### Omitting output parameter + +The output parameter is optional. If it is omitted, the result of the function invocation will be stored in +the corresponding input variable. In the example below, the output of expand function will be stored in the +query variable. + +```yaml + components: + - name: shaper + params: + inputs: + query: + func: expand + type: Shaper + pipelines: + - name: query + nodes: + - name: shaper + inputs: + - Query + +``` + +### Order of function invocation + +The order of function invocation is important. The functions are invoked in the order they are defined in the YAML. +In the example below, we have two input variables: `query` and `documents`. The `query` variable is expanded to a +list of strings and stored in the variable `questions`. The `documents` variable is then contracted and the +variable `questions` is immediately used as the `num_tokens` keyword parameter to the `concat` function. + +```yaml + components: + - name: shaper + params: + inputs: + query: + func: expand + output: questions + params: + expand_target: query + size: + func: len + params: + - documents + documents: + func: concat + output: documents + params: + docs: documents + delimiter: " " + num_tokens: + func: len + params: + - questions + type: Shaper + pipelines: + - name: query + nodes: + - name: shaper + inputs: + - Query +``` + +### Security + +The Shaper component prevents arbitrary code execution. There should be no dangerous `exec` or `eval` Python calls. Only +the functions we have specified in the Shaper component are allowed to be invoked. The functions are specified in the +constructor using immutable data structures. + +This security measure might be relaxed in the future to allow users to specify their own functions. However, this +change will require a more thorough security review. + +# Drawbacks and other considerations + +Although a "normal use" of PromptNodes would not trigger a need for Shaper there are cases where its +use is necessary. In cases where we can only use pipeline definitions to configure the pipeline (via YAML), +we need to use it. + + +- Implementation and maintenance cost should not be high. +- Shaper is not really useful outside of Haystack pipeline. +- Shaper could turn out to be useful in other use cases as well - i.e. declarative pre/post processing. +- Shaper integrates well with PromptNodes and other components. +- No braking changes to existing components. + + +# Alternatives + +A better solution would likely be a more general run method for components. This would allow us to arbitrarily +define the pipeline invocation context. However even in those cases we'll need to use Shaper to modify +existing variables in invocation context as needed. + +# Adoption strategy + +Haystack users can start using Shaper in their pipelines immediately. There are no breaking changes to +existing components or pipelines. + + +# How we teach this + +We will need docs update to teach users how to use Shaper. The docs will need to explain the +motivation using Shaper and PromptNode examples. We also need to show the usage via tutorials. + + +# Unresolved questions + +Optional, but suggested for first drafts. What parts of the design are still +TBD? diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3875-table-cell.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3875-table-cell.md new file mode 100644 index 0000000000000000000000000000000000000000..a014ded77eb1fef9da7c2aef429f937c065ab107 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3875-table-cell.md @@ -0,0 +1,238 @@ +- Title: TableCell Dataclass +- Decision driver: Sebastian Lee +- Start Date: 2023-01-17 +- Proposal PR: https://github.com/deepset-ai/haystack/pull/3875 +- Github Issue: https://github.com/deepset-ai/haystack/issues/3616 + +# Summary + +When returning answers for a TableQA pipeline we would like to return the column and row index as the answer location +within the table since the table is either returned as a list of lists in Haystack. +This would allow users to easily look up the answer in the returned table to fetch the text directly from the table, +identify the row or column labels for that answer, or generally perform operations on the table near or around the +answer cell. + +# Basic Example + +When applicable, write a snippet of code showing how the new feature would be used. +```python +import pandas as pd +from haystack.nodes import TableReader +from haystack import Document + +data = { + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["58", "47", "60"], + "number of movies": ["87", "53", "69"], + "date of birth": ["18 december 1963", "11 november 1974", "6 may 1961"], +} +table_doc = Document(content=pd.DataFrame(data), content_type="table") +reader = TableReader(model_name_or_path="google/tapas-base-finetuned-wtq", max_seq_len=128) +prediction = reader.predict(query="Who was in the most number of movies?", documents=[table_doc]) +answer = prediction["answers"][0] + +# New feature +# answer.context -> [["actor", "age", "number of movies"], ["Brad Pitt",...], [...]] +# answer.offsets_in_context[0] -> (row=1, col=1) +print(answer.context[answer.offsets_in_context[0].row][answer.offsets_in_context[0].col]) +``` + +# Motivation + +## Why do we need this feature? +To allow users to easily look up the answer cell in the returned table to fetch the answer text +directly from the table, identify the row or column labels for that answer, or generally perform operations on the table +near or around the answer cell. + +Currently, we return the location of the answer in the **linearized** version of the table, so we can use the +`Span` dataclass. The `Span` dataclass is reproduced below: +```python +@dataclass +class Span: + start: int + end: int + """ + Defining a sequence of characters (Text span) or cells (Table span) via start and end index. + For extractive QA: Character where answer starts/ends + For TableQA: Cell where the answer starts/ends (counted from top left to bottom right of table) + + :param start: Position where the span starts + :param end: Position where the span ends + """ +``` +This is inconvenient for users because they would need to know how the table is linearized (column major or row major) +so they could reconstruct the column and row indices of the answer before they could locate the answer cell in the table. + +## What use cases does it support? +Some examples are already stated above but to recap, to easily perform operations on the table near or around the answer cell. + +## What's the expected outcome? +The addition of a new dataclass called `TableCell` that would look like +```python +@dataclass +class TableCell: + row: int + col: int + """ + Defining a table cell via the row and column index. + + :param row: Row index of the cell + :param col: Column index of the cell + """ +``` + +# Detailed design + +**New terminology:** `TableCell`, the new name for the dataclass to +store the column and row index of the answer cell. + +**Basic Example:** [Above Basic Example](#basic-example) + +## Code changes +- Addition of `TableCell` dataclass to https://github.com/deepset-ai/haystack/blob/main/haystack/schema.py +```python +@dataclass +class TableCell: + row: int + col: int + """ + Defining a table cell via the row and column index. + + :param row: Row index of the cell + :param col: Column index of the cell + """ +``` + +- Updating code (e.g. schema objects, classes, functions) that use `Span` to also support `TableCell` where appropriate. +This includes: +- Updating the `Answer` dataclass to support `TableCell` as a valid type for `offsets_in_document` and `offsets_in_context` +```python +@dataclass + class Answer: + answer: str + type: Literal["generative", "extractive", "other"] = "extractive" + score: Optional[float] = None + context: Optional[Union[str, List[List]]] = None + offsets_in_document: Optional[List[Span], List[TableCell]] = None + offsets_in_context: Optional[List[Span], List[TableCell]] = None + document_id: Optional[str] = None + meta: Optional[Dict[str, Any]] = None +``` +- Similar to how we can return a list of `Span`s, we would allow a list of `TableCell`s to be returned to handle the case + when multiple `TableCell`s are returned to form a final answer. +- Updating any functions that accept table answers as input to use the new `col` and `row` variables instead of `start` and `end` variables. +This type of check for table answers is most likely already done by checking if the `context` is of type `pd.DataFrame`. +- `TableReader` and `RCIReader` to return `TableCell` objects instead of `Span`. + +Changes related to the Edge Case/Bug below +- Update `Document.content` and `Answer.context` to use `List[List]` instead of `pd.DataFrame`. +- Update `TableReader` nodes to convert table from `List[List]` into `pd.DataFrame` before inputting to the model. + +## Edge Case/Bug +Internally, Haystack stores a table as a pandas DataFrame in the `Answer` dataclass, which does not treat the column +labels as the first row in the table. +However, in Haystack's rest-api the table is converted into a list of lists format where the column labels are +stored as the first row, which can be seen [here](https://github.com/deepset-ai/haystack/pull/3872), which is consistent +with the `Document.to_dict()` method seen [here](https://github.com/deepset-ai/haystack/blob/6af4f14fe0d375a1ae0ced18930a9239401231c7/haystack/schema.py#L164-L165). + +This means that the current `Span` and (new) `TableCell` dataclass point to the wrong location when the table is +converted to a list of lists. + +For example, the following code +```python +import pandas as pd +from haystack import Document + +data = { + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["58", "47", "60"], + "number of movies": ["87", "53", "69"], + "date of birth": ["18 december 1963", "11 november 1974", "6 may 1961"], +} +table_doc = Document(content=pd.DataFrame(data), content_type="table") +span = (0, 0) +print(table_doc.content.iloc[span]) # prints "brad pitt" + +dict_table_doc = table_doc.to_dict() +print(dict_table_doc["content"][span[0]][span[1]]) # prints "actors" +``` + +We have decided to store the table internally as a list of lists to avoid this issue. See discussion starting [here](https://github.com/deepset-ai/haystack/pull/3875#discussion_r1088766318). + +# Drawbacks + +Look at the feature from the other side: what are the reasons why we should _not_ work on it? Consider the following: + +- What's the implementation cost, both in terms of code size and complexity? + +I don't believe this will require too much code change since we already check for Table like answers by checking if the +returned context is of type string or pandas Dataframe. + +- Can the solution you're proposing be implemented as a separate package, outside of Haystack? + +Technically yes, but since it affects core classes like `TableReader`, and `RCIReader` it makes sense to implement in +Haystack. + +- Does it teach people more about Haystack? + +It would update already existing documentation and tutorials of Haystack. + +- How does this feature integrate with other existing and planned features? + +This feature directly integrates and impacts the TableQA feature of Haystack. + +- What's the cost of migrating existing Haystack pipelines (is it a breaking change?)? + +Yes there are breaking changes that would affect end users. +1. The way to access the offsets in returned Answers would be different. +Following the deprecation policy we will support both `Span` and `TableCell` (can be toggled between using a boolean flag) +for 2 additional versions of Haystack. +2. Tables in Haystack Documents and Answers will change from type pandas Dataframe to a list of lists. + +# Alternatives + +## What's the impact of not adding this feature? +Requiring users to figure out how to interpret the linearized answer cell coordinates to reconstruct the row and column indices +to be able to access the answer cell in the returned table. + +## Other designs +1. Expand `Span` dataclass to have optional `col` and `row` fields. This would require a similar check as `TableCell`, but instead +require checking for which of the elements are populated, which seems unnecessarily complex. +```python +@dataclass +class Span: + start: int = None + end: int = None + col: int = None + row: int = None +``` +2. Use the existing `Span` dataclass and put the row index and column index as the `start` and `end` respectively. +This may be confusing to users since it is not obvious that `start` should refer to `row` and `end` should refer to `column`. +```python +answer_cell_offset = Span(start=row_idx, end=col_idx) +``` +3. Provide a convenience function shown [here](https://github.com/deepset-ai/haystack/issues/3616#issuecomment-1361300067) +to help users convert the linearized `Span` back to row and column indices. I believe this solution is non-ideal since it would +require a user of the rest_api to access a python function to convert the linearized indices back into row and column indices. + +# Adoption strategy + +## How will the existing Haystack users adopt it? +Haystack users would immediately experience this change once they update their installation of Haystack if they were using +the TableQA reader. This would be a breaking change since it would change the `offsets_in_document` and +`offsets_in_context` in the returned `Answer`. I'm not sure if there would be a straightforward way to write a migration +script for this change. + +# How we teach this + +Would implementing this feature mean the documentation must be re-organized +or updated? Does it change how Haystack is taught to new developers at any level? + +- The API docs for `TableCell` would need to be added. +- The documentation page for [Table Question Answering](https://docs.haystack.deepset.ai/docs/table_qa) would need to be updated. +- Update the (TableQa tutorial)[https://github.com/deepset-ai/haystack-tutorials/blob/main/tutorials/15_TableQA.ipynb] +to reflect the `Span` is no longer linearzied. + +# Unresolved questions + +No more unresolved questions. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3925-mrkl-agent.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3925-mrkl-agent.md new file mode 100644 index 0000000000000000000000000000000000000000..05d18a6a57a0b73a212b968367e8ed5e7ce7a36f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3925-mrkl-agent.md @@ -0,0 +1,380 @@ +- Title: MRKLAgent +- Decision driver: @julian-risch (in close collaboration with @vblagoje ) +- Start Date: 2023-01-27 +- Proposal PR: https://github.com/deepset-ai/haystack/pull/3925 +- Github Issue or Discussion: https://github.com/deepset-ai/haystack/issues/3753 + +# Summary +The Agent class answers queries by choosing between different tools, which are implemented as pipelines or nodes. +It uses a large language model (LLM) to generate a thought based on the query, choose a tool, and generate the input for the tool. +Based on the result returned by an action/tool (used interchangeably), the Agent has two options. +It can either stop if it knows the answer now or repeat the process of 1) thought, 2) action choice, 3) action input. + +The Agent can be used for questions containing multiple subquestions that can be answered step-by-step (Multihop QA). +Combined with tools like the PythonRuntime or SerpAPIComponent we imagine for Haystack, the Agent can query the web and do calculations. + +We have a [notebook](https://colab.research.google.com/drive/1oJf4gxkokIazLN26NNt6XsewMvCmVrz8?usp=sharing) that demonstrates how to use an Agent with two tools: PythonRuntime and SerpAPIComponent. It requires API keys for OpenAI and SerpAPI. +The notebook is based on the branch https://github.com/deepset-ai/haystack/compare/main...mrkl-pipeline (no pull request) + +# Basic example + +An example of an Agent could use two tools: a web search engine and a calculator. + +The query "Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?" can be broken down into three steps: +1) Searching the web for the name of Olivia Wilde's boyfriend +2) Searching the web for the age of that boyfriend +3) Calculating that age raised to the 0.23 power + +And the Agent would respond in the end with "Jason Sudeikis, Olivia Wilde's boyfriend, is 47 years old and his age raised to the 0.23 power is 2.4242784855673896." A detailed walk-through follows below. + + +# Motivation + +With an Agent, users can combine multiple LLMs and tools, so that they can build a truly powerful app. They can use an LLM in a loop to answer more complex questions than with ExtractiveQA or GenerativeQA. With an Agent and a tool for web search, Haystack is not limited to extracting answers from a document store or generating answers based on model weights anymore but it can use the knowledge it retrieves on-the-fly from the web. Thereby, the model's knowledge does not get outdated. + +In future, we envision that an Agent could use tools not only for retrieving knowledge but also for interacting with the world. For example, it could periodically skim through newly opened issues in Haystack's GitHub repository. If there is a question that can be answered based on documentation then the Agent could retrieve relevant pages from the documentation, generate an answer and post it as a first response to the issue. + +# Detailed design + +**Glossary** +- Thought: First part of a prompt generated by Agent that serves to breakdown the query into a plan, for example, what part of the question needs to be answered first. +- Action (or tool): Actions/tools are Haystack pipelines or nodes that the Agent can use to answer a question. We use tool and action interchangeably in this proposal until we decided on the best naming. Choosing a tool in each iteration is the center part of a prompt generated by Agent. +- Action input: Last part of a prompt generated by an Agent. It serves as the input to a tool that the Agent uses to answer a question. +- Observation: The output generated by a tool and sent back to the Agent. + +The Agent consists of a PromptNode that generates thoughts, chooses actions, and generates action inputs. +Just like Haystack pipelines, an Agent can be loaded from a YAML file. That YAML file must also contain the tools of the Agent defined as pipelines or nodes. +Tools need to be added to an Agent so that it can use them, just like nodes need to be added to pipelines. +When a tool is added to an Agent, a description of the tools needs to be added so that the LLM knows when it is useful. + +A key functionality of the Agent is that it can act iteratively and use any of the pre-defined tools as many times as it wants based on the input query and the results returned from the tools used earlier. In every iteration, it chooses one of the tools and generates the input for that tool dynamically. +An example application of this is MultiHopQA, where multiple subquestions need to be answered step-by-step. +For the example query "Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?", the MRKLPipeline needs to answer several subquestions. Here is an example of a full transcript of the prompt input and generated output: + +``` +Answer the following questions as best as you can. You have access to the following tools: + +Search: useful for when you need to answer questions about current events. You should ask targeted questions +Calculator: useful for when you need to answer questions about math + +Use the following format: + +Question: the input question you must answer +Thought: you should always think about what to do +Action: the action to take, should be one of [Search, Calculator] +Action Input: the input to the action +Observation: the result of the action +... (this Thought/Action/Action Input/Observation can repeat N times) +Thought: I now know the final answer +Final Answer: the final answer to the original input question + +Begin! +Question: Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power? +Thought: I need to do some research to answer this question. +Action: Search +Action Input: Olivia Wilde's boyfriend +Observation: First linked in November 2011, Wilde and Sudeikis got engaged in January 2013. They later became parents, welcoming son Otis in 2014 and daughter Daisy in 2016. +Thought: I need to find out his age +Action: Search +Action Input: Jason Sudeikis age +Observation: 47 years +Thought: I need to raise it to the 0.23 power +Action: Calculator +Action Input: 47^0.23 +Observation: 2.4242784855673896 +Thought: I now know the final answer +Final Answer: Jason Sudeikis, Olivia Wilde's boyfriend, is 47 years old and his age raised to the 0.23 power is 2.4242784855673896. +``` + +## Agent steps breakdown +The above steps represent the entire action trace for the Agent. However, let's break it down into individual agent steps so we can understand how it makes decisions, chooses actions and action inputs. + +### Step 1: + +We start with a prompt where we instruct LLM on what we want. The first prompt we send to LLM is the following: +``` +Answer the following questions as best as you can. You have access to the following tools: + +Search: useful for when you need to answer questions about current events. You should ask targeted questions +Calculator: useful for when you need to answer questions about math + +Use the following format: + +Question: the input question you must answer +Thought: you should always think about what to do +Action: the action to take, should be one of [Search, Calculator] +Action Input: the input to the action +Observation: the result of the action +... (this Thought/Action/Action Input/Observation can repeat N times) +Thought: I now know the final Answer +Final Answer: the final Answer to the original input question + +Begin! +Question: Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power? +Thought: +``` + +Notice how we finish the prompt with the `Thought:` token, priming the model to start its generation of an actual plan of what needs to be done in the first step. +LLM would also generate `Action:` and `Action Input:` rows of this step which help us select an Action to execute and the input for that action. +As we also instruct the model to stop generating a response with stop words being `Observation:` the model response for this step is: + +``` +I need to do some research to answer this question. +Action: Search +Action Input: Olivia Wilde's boyfriend +``` + +At this point, we invoke Search (along with the input) and receive the response from the Search tool: "First linked in November 2011, Wilde and Sudeikis got engaged in January 2013. They later became parents, welcoming son Otis in 2014 and daughter Daisy in 2016." + +We append the tool response under the `Observation:` + +LLM generation above and the response from the Search action (added under Observation) are appended to the initial prompt. + +### Step 2: + +We start this step with the following prompt: + +``` +Answer the following questions as best as you can. You have access to the following tools: + +Search: useful for when you need to answer questions about current events. You should ask targeted questions +Calculator: useful for when you need to answer questions about math + +Use the following format: + +Question: the input question you must answer +Thought: you should always think about what to do +Action: the action to take, should be one of [Search, Calculator] +Action Input: the input to the action +Observation: the result of the action +... (this Thought/Action/Action Input/Observation can repeat N times) +Thought: I now know the final Answer +Final Answer: the final Answer to the original input question + +Begin! +Question: Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power? +Thought: I need to do some research to answer this question. +Action: Search +Action Input: Olivia Wilde's boyfriend +Observation: First linked in November 2011, Wilde and Sudeikis got engaged in January 2013. They later became parents, welcoming son Otis in 2014 and daughter Daisy in 2016. +Thought: +``` + +Again, notice how we've added the response from LLM and the `Observation` from the tool to the prompt, and we finish the prompt with `Thought:` token, priming the model to start the response with the plan for this step. As in the previous step, the model generates an action plan and selects an action and its input. The LLM response is: + +``` +I need to find out his age +Action: Search +Action Input: Jason Sudeikis age +``` + +This LLM response above gives us enough information to invoke a Search tool again along with the appropriate input, and we receive the response from the Search: 47 years. We add this response to the prompt history as the `Observation:` keyword. + +### Step 3: + +For the sake of brevity, let's not list the entire prompt again. The critical part to remember is that we append the output of step 2 to the prompt history we are creating as we step through each agent step. These so-called reasoning traces help agents "understand" what needs to be done in each successive step. +The last part of the prompt is the following: +``` +Thought: I need to find out his age +Action: Search +Action Input: Jason Sudeikis age +Observation: 47 years +Thought: +``` + +The LLM-generated response is: + +``` +I need to raise it to the 0.23 power +Action: Calculator +Action Input: 47^0.23 +``` + +In this step, we invoke a new tool - The calculator with specified input. The calculator response is 2.4242784855673896 +We added the calculator response to the prompt history under the Observation keyword. + + +### Step 4: + +Again, we append a calculator response and prompt to the prompt history once again. Let's not list the entire prompt, but the last few lines: +``` +I need to raise it to the 0.23 power +Action: Calculator +Action Input: 47^0.23 +Observation: 2.4242784855673896 +Thought: +``` + +The LLM-generated response is: +``` +I now know the final answer +Final Answer: Jason Sudeikis, Olivia Wilde's boyfriend, is 47 years old and his age raised to the 0.23 power is 2.4242784855673896. +``` + +Using simple string parsing, we can detect that the mode in this step responded with the "Final Answer:" keyword just as we instructed, thus breaking out of the loop and completing the agent's task with a response returned to the agent's client. +In the rare case that "Final Answer:" is not generated even after many iterations, we can break out of the loop based on a maximum number of iterations allowed. Thereby, we can prevent an infinite loop. + +## Agent Creation + +The Agent can be either created programmatically or loaded from a YAML file. +In the following example, one tool is a node for searching the web. The other tool is a pipeline for doing calculations in python. + +**Example programmatic creation:** +```python +search = SerpAPIComponent(api_key=os.environ.get("SERPAPI_API_KEY"), name="Serp", inputs=["Query"]) + +prompt_model=PromptModel(model_name_or_path="text-davinci-003", api_key=os.environ.get("OPENAI_API_KEY")) + +calculator = Pipeline() +calculator.add_node(PromptNode( + model_name_or_path=prompt_model, + default_prompt_template=PromptTemplate(prompt_text="Write a simple python function that calculates..."), + output_variable="python_runtime_input") # input +calculator.add_node(PythonRuntime()) # actual calculator + +prompt_node = PromptNode( + model_name_or_path=prompt_model, + stop_words=["Observation:"] +) + +agent = Agent(prompt_node=prompt_node) +# Nodes and pipelines can be added as tools to the agent. Just as nodes can be added to pipelines with add_node() +agent.add_tool("Search", search, "useful for when you need to answer questions about current events. You should ask targeted questions") +agent.add_tool("Calculator", calculator, "useful for when you need to answer questions about math") + +result = agent.run("What is 2 to the power of 3?") +``` + +**Example YAML file:** +```yaml +version: ignore + +components: + - name: AgentPromptNode + type: PromptNode + params: + model_name_or_path: DavinciModel + stop_words: ['Observation:'] + - name: DavinciModel + type: PromptModel + params: + model_name_or_path: 'text-davinci-003' + api_key: 'XYZ' + - name: Serp + type: SerpAPIComponent + params: + api_key: 'XYZ' + - name: CalculatorInput + type: PromptNode + params: + model_name_or_path: DavinciModel + default_prompt_template: CalculatorTemplate + output_variable: python_runtime_input + - name: Calculator + type: PythonRuntime + - name: CalculatorTemplate + type: PromptTemplate + params: + name: calculator + prompt_text: | + # Write a simple python function that calculates + # $query + # Do not print the result; invoke the function and assign the result to final_result variable + # Start with import statement + +pipelines: + - name: calculator_pipeline + nodes: + - name: CalculatorInput + inputs: [Query] + - name: Calculator + inputs: [CalculatorInput] + +agents: + - name: agent + params: + prompt_node: AgentPromptNode + tools: + - name: Search + pipeline_or_node: Serp + description: > + useful for when you need to answer questions about current events. + You should ask targeted questions + - name: Calculator + pipeline_or_node: calculator_pipeline + description: > + useful for when you need to answer questions about math +``` + +and loading from the YAML file into an Agent: + +```python +agent = Agent.load_from_yaml( + "test.mrkl.haystack-pipeline.yml", agent_name="agent" +) +``` + +Pipelines, agents, nodes, and tools all implement `run` and `run_batch` methods, which is the minimal contract. +At the moment, tools are either pipelines or nodes but we can imagine more types of tools as long as they implement that minimal contract. + +# Drawbacks + +Although the scope of the initial Agent is limited, it can grow into a full-fledged framework consisting of +various types of agents (conversation, Robotic Process Automation etc.). The field of agents is rapidly growing, and we should be aware that it can even outgrow Haystack in the future. Perhaps we can start with the Agent being part of Haystack and potentially create a new project in the future. + +One of the central building blocks of an Agent are the PromptNode and set "neural attachments" extending the agent's capabilities. +Many tools like Search, Calculator, Notion and API connectors are somewhat different conceptually from the existing Haystack components. +On the other hand, some of the existing Haystack components fit naturally into the framework of tools, for example, DocumentStore, Retriever, and Reader. + +There is a non-negligible potential for a growing implementation cost of such an agent framework that might +stretch the resource away from the existing Haystack core. However, as LLM-based agents are an exciting and +rapidly growing field, they may raise Haystack awareness significantly. + +# Alternatives + +We have considered an alternative design where the Agent is just another node or a pipeline. +However, we decided to introduce it as a separate concept because of user-friendliness / clear code. +While a Pipeline is a collection of Nodes, an Agent is a collection of Pipelines. +Nodes in a pipeline have a pre-defined execution order, whereas the execution order of Pipelines in an Agent are chosen at runtime by a LLM. + +Regarding the name *Agent*, we considered several alternatives and prefer *Agent* for its simplicity. +Alternative names: +- MRKLAgent +- LLMOrchestrator +- LLMChain +- Toolchain (fits nicely with tools and [toolchains](https://en.wikipedia.org/wiki/Toolchain) in software) +- PipelineComposer / LLMComposer +- PipelineComposition / LLMComposition +- Interesting naming tidbits: + - MRKL [paper](https://arxiv.org/pdf/2205.00445.pdf) never uses word agent, only system + - ReAct [paper](https://arxiv.org/pdf/2210.03629.pdf) uses agent almost exclusively + + +# Adoption strategy + +Introducing the Agent concept is a rather big change that would require a careful adoption strategy. We would need a lot more documentation explaining these new concepts, and each attaching tool would need additional documentation. + +However, the existing Haystack users, especially advanced users have already requested an agent framework to be added as part of the Haystack. We anticipate that advanced users will be the first to adopt the Agent. + +Using an Agent requires an OpenAI api key and some tools require additional api keys, for example SerpAPI but there are free trials. + +The debugging output of the Agent will help users to better understand how it works. In a debugger, the agent works as any other Haystack pipeline containing a prompt node. + +# How we teach this + +Yes, adding agents to Haystack would require a lot of documentation changes. Perhaps even a separate documentation for MRKL and other future agents somewhat detached from Haystack. + +We can teach existing Haystack users about agents and agent tools in a new section of the documentation. We can also organize Discord office hours, tutorials, and webinars to teach the new concepts. + +# Unresolved questions + +**Name of the parameter pipeline_or_node** +* When we add a tool to the agent, we need to specify the name of the pipeline or node (component) to add. +This parameter could be called `pipeline_or_node` or `pipeline_or_component_name` etc. + +**Umbrella Term for Pipeline and Agent** +* We need a term that captures pipelines and agents for communication with users (NLP application, flow, system, service, engine ...). +Let's have that conversation separately from this proposal. + +**Tools we imagine in the near future** +* Tools will be discussed in a separate proposal. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3959-json-converter.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3959-json-converter.md new file mode 100644 index 0000000000000000000000000000000000000000..1643929ad232c46780564b4afc49614803e3883e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3959-json-converter.md @@ -0,0 +1,142 @@ +- Title: Addition of a `JsonConverter` node +- Decision driver: @bglearning +- Start Date: 2023-01-26 +- Proposal PR: #3959 + +# Summary + +Right now we don't have a node that can take json files as input to be fed into a pipeline. + +Proposal: Add a `JsonConverter` node that takes in a json file, parses it, and generates `Document`s. +It would also support the `jsonl` format with one line corresponding to one document. + +# Basic example + +```python +from haystack.nodes import JsonConverter + +converter = JsonConverter() + +# Receive back List[Document] +docs = converter.convert("data_file.json") +``` + +With the `data_file.json` as a list of json representation of documents: + +```json +[ + { + "content": "...", + "content_type": "text", "meta": {...} + }, + { + "content": [["h1", "h2"], ["val1", "val2"]], + "content_type": "table", "meta": {...} + } +] +``` + +Alternatively, the data can also be `jsonl`. +By default, the converter will try to auto-detect between `json` and `jsonl`. + +The main use case would be to be able to include this directly in the YAML specification + +```yaml +... + +pipelines: + - name: indexing + nodes: + - name: JsonConverter + inputs: [File] + - name: Retriever + inputs: [JsonConverter] + - name: DocumentStore + inputs: [Retriever] +``` + +# Motivation + +Users may want to do some processing of the data themselves, persist it somehow, and only then pass it onto a haystack pipeline (for instance, by uploading into the REST API endpoint). Ideally this would happen without the need to create a custom endpoint. + +For many such processing, json is a convenient intermediate format as it allows for things like specifying the metadata. + +Specifically, one use-case that has come up for a team using haystack: they want to use a PDF parser (for tables) currently not in haystack. As such, they want to handle the parsing themselves outside of haystack, put the parsed result into a json file, and then pass it onto a haystack API endpoint. + +Having a `JsonConverter` node would allow users to setup a haystack pipeline to ingest such data without the user having to create a custom node for it. + +# Detailed design + +The converter would primarily be a wrapper around `Document.from_dict`. + +The schema accepted would be the a list of json dictionary of Documents. +So, the following, with `content` being the only compulsory field. + +``` +[ + { + "content": str or list[list], + "content_type": str, + "meta": dict, + "id_hash_keys": list, + "score": float, + "embedding": array + }, + ... +] +``` + +```python +class JsonConverter(BaseConverter): + def __init__(self, ...): + ... + + def convert( + self, + file_path: Path, + meta: Optional[Dict[str, str]] = None, + encoding: Optional[str] = "UTF-8", + id_hash_keys: Optional[List[str]] = None, + ... + ) -> List[Document]: + if id_hash_keys is None: + id_hash_keys = self.id_hash_keys + + documents = [] + with open(file_path, encoding=encoding, errors="ignore") as f: + data = json.load(f) + for doc_dict in data: + doc_dict = dict(doc_dict) + doc_dict['id_hash_keys'] = id_hash_keys + doc_dict['meta'] = doc_dict.get('meta', dict()) + + if meta: + doc_dict['meta'].update(meta) + + documents.append(Document.from_dict(doc_dict)) + + return documents +``` + +# Drawbacks + +- It would add another node that needs to be maintained and documented. + +# Alternatives + +- This node could be created as a custom node for the particular application where it is required. But could be better to have it out-of-the-box. +- Design Alternative: Also, provide options to map custom fields to `Document` fields (E.g. {"review": "content"}) which could make this node a bit more flexible and might mean the user doesn't have to do some pre-formatting beforehand. But this can be a future development. + +# Adoption strategy + +It doesn't introduce a breaking change and wouldn't require changes in existing pipelines. + +# How we teach this + +It would be good to have this be part of the Guide (perhaps under File Converters). + +Could also be mentioned in one of the tutorials. For instance, in the preprocessing tutorial where we say "Haystack expects data to be provided as a list documents in the following dictionary format". + +# Unresolved questions + +- Should the `content_type` allowed be restricted (e.g. only "text" and "table"). And relatedly, should the name be more specific? E.g. `JsonTableTextConverter` rather than `JsonConverter`. Currently leaning towards no restriction and the `JsonConverter` name. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4084-agent-demo.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4084-agent-demo.md new file mode 100644 index 0000000000000000000000000000000000000000..a6d8f8be592f8ad488bad055f9c5ffb03e7fb825 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4084-agent-demo.md @@ -0,0 +1,262 @@ +- Title: Agent tools +- Decision driver: Vladimir Blagojevic (with Julian Risch) +- Start Date: 2023-02-06 +- Proposal PR: https://github.com/deepset-ai/haystack/pull/4084 + + +# Summary + +Agent system consists of an extendable set of modules (aka experts/tools) and a "router" dispatching natural +language input to a module that can best respond to the given input. These modules can be: + +• Neural, including the general-purpose LLMs as well as other smaller, specialized LMs. + +• Symbolic, for example a math calculator, a currency converter, or an API call to a search engine. + + +Current Haystack pipeline design approach fits nicely with these extension modules/tools. They can be tested in +isolation and subsequently integrated into the agent. The agent can register these tools, understand their objectives +and route the user input to the appropriate tool. The tools can be either Haystack pipelines or components. + + +A demo idea for the new Agent is to demonstrate Question Answering on Technical Documentation (using the example of +Haystack). It should be useful and impressive, and it determines what tools we will implement first. + +**Example Questions:** +- "Why am I seeing duplicate answers being returned?" based on indexed FAQ documentation +- "Which organizations use Haystack?" based on web search and Wikipedia returning answers via SearchEngine +- "How can I choose the model for PromptNode?" based on retrieving documents via WebRetriever +- "How can I make overwrite_with_env_variables work in RayPipeline" based on an open issue found with GitHub API or web search + +If an answer cannot be found in indexed files, the Agent will use self reflection to rephrase the question and/or search the +web. It will give updates while searching, for example print thoughts: “Found nothing in indexed documentation. Will continue +with web search.” If still nothing can be found, the Agent will generate a link to a pre-filled and pre-tagged issue template +like this that the user can choose to create. Tools required for the demo: SearchEngine, GitHubAPI, Self Reflection Module, WebRetriever. + +We also need to demonstrate how the Agent uses a combination of multiple tools to answer a question instead of just trying +them sequentially. + +**Example Question:** +- "Is there an open issue about any of the nodes in a standard QA pipeline not working?" + +Here the LLM might first use documentation to find out more about what nodes are part of standard QA pipelines and then +searches on GitHub for open issues that mention retriever or reader. + +We propose the following tools to be developed for the MVP version of our agent (#3925): + +- SearchEngine +- Self reflection module (query rephrasing) +- WebRetriever +- Top-p (nucleus) sampling +- Agent memory +- deepset Cloud API + +# Basic example + +No code examples are provided, but a high-level overview of how the feature would be used. + +There is also a [colab notebook](https://colab.research.google.com/drive/1oJf4gxkokIazLN26NNt6XsewMvCmVrz8?usp=sharing) +demonstrating how to use an agent with tools and a [branch](https://github.com/deepset-ai/haystack/compare/main...mrkl-pipeline) +for demo purposes (no pull request). + +# Motivation + +Agent tools are the main and essential building block of the agent system. They are the modules extending the +agent's capabilities. Agent, when it relies only on itself, is not as powerful as when it can leverage the +external modules (tools) that are highly specialized in their respective domains. Agent can't do, for example, lookup of +restaurants in our neighbourhood, but it can use SearchEngine to do that. When it comes to complex math calculations, LLM +would be a poor choice, but a math calculator would be a good fit, and so on. + +Combining the power of LLMs with the power of external tools is the key ingredient to the success of the agent framework. + + +# Detailed design + +In the following sections, we list essential agent tools required for agent MVP. We start with the general design +principles and then describe each tool in detail. + +Each tool is defined as a Python class that inherits from the BaseComponent class. The base class acts as a wrapper +around the actual tool implementation. + +The main Agent modules/tools are: + +## SearchEngine + +SearchEngine is a symbolic API module allowing programmatic interaction with Google and other search engines. We'll have +multiple providers of SearchEngine including https://serper.dev, https://www.searchapi.io/ and https://serpapi.com as initial providers. + +SearchEngine will return a list of results (e.g. List[Document]), the content of each document being a "snippet" of the +single search result, while all other attributes of the search results (e.g. title, url link, etc.) will +be metadata of the document. + +### SearchEngine scoping + +A great feature of SearchEngine is that it can be scoped to a particular domain. Therefore, in our demo, if so desired, +we can search through Haystack documentation on docs.haystack.com, github.com/deepset-ai/haystack and so on. + +## Self reflection module + +SRM is a neural module that aims to improve the agent's overall robustness. Agents can sometimes be very fragile +in their execution steps. As a core component, the motivation for the self-reflection module (SRM) is to improve the +robustness of the agent's execution. Agents can be fragile in their execution steps due to the non-deterministic nature +of LLM inferencing and their sensitivity to the chosen prompts. + +SRM relies on instruction following LLM and operates in two lock-step sequences. Given any other agent module/tool, +its description, and its input and output - SRM does the following: + +1. It checks if the module description (objective), the input, and the output are aligned/congruent. +2. If they are not aligned, it rephrases the input (while retaining semantic meaning) and attempts to elicit an aligned +output. + +SRM can improve the robustness of any module. For example, SearchEngine can sometimes be very sensitive to query wording. +If we are searching for "Olivia Wilde's boyfriend", the results might not be as precise as if we search for "Who is +Olivia Wilde's current boyfriend?". SRM can rephrase the query to the latter form if the former form doesn't return +an aligned answer. + +It is still an open question of how to implement SRM. We can make it an internal component or another pipeline. The +former approach is more efficient and has tight coupling, and the latter is more flexible. We'll carefully weigh +the pros and cons of each approach and decide on the best approach. + +One idea how to integrate SRM into an existing Agent and its tools is that every tool can set a parameter indicating +how often SRM should run for this tool (default value 0). If it is 0, SRM will not be used at all for that tool, +otherwise it will check at least once for alignment/congruency and optionally rephrase. This will repeat but not +more often than the parameter allows. + +One possible implementation of SRM could be https://arxiv.org/abs/2203.11171 + +The main motivation for addition of SRM (and self-consistency ideas in general) is the finding from +https://arxiv.org/abs/2210.03629 Google Brain researchers discovered that "Wrong reasoning trace (including failing +to recover from repetitive steps)" accounts for 47% of agent errors. + +## WebRetriever + +WebRetriever is a symbolic module that allows users to query the web for relevant documents. It is a wrapper around +SearchEngine that produces a list of Haystack Documents. + +WebRetriever will operate in two modes: + +- snippet mode: WebRetriever will return a list of Documents, each Document being a snippet of the search result +- document mode: WebRetriever will return a list of Documents, each Document being a full HTML stripped document of the search result + +In document mode, given a user query passed via the run method, SearchEngine first fetches the top_k relevant URL hits, which are +downloaded and processed. The processing involves stripping irrelevant HTML tags and producing clean raw text. WebRetriever +then splits raw text into paragraph-long Documents of the desired size. + +In the future, we'll develop WebRetriever variants with DocumentStore that caches documents with some expiration +setting. The enhanced WebRetreiever versions will allow us to avoid downloading the same documents from the web +multiple times. + +However, for the first version of the agent, we'll strive to keep WebRetriever as simple as possible. + +## Top-p (nucleus) sampling + +Although very useful, top-k ranking is sometimes inferior to top-p ranking. Instead of filtering only from the most +likely k hits, in top-p sampling we choose the smallest possible set of documents whose cumulative probability of +relevance exceeds the probability p (usually close to 1). The relevance could be calculated via sbert.net CrossEncoder using +query and the document content. + +In web search, this is a very useful feature as it allows us to avoid query irrelevant documents and be super precise +in our search results. We'll implement top-p sampling as a separate module that WebRetriever can use. Other components +in Haystack can use it as well. + +The main motivation for addition of top-p sampling is the finding from https://arxiv.org/abs/2210.03629 Google Brain +researchers found that "Search result error" is the main cause in 23% of the cases of agent failure. Top-p sampling +can help us minimize this point of failure. + +Note that one can still use top-k filtering via Ranker and top-p filtering via TopPSampler in combination. + +## Agent memory + +Although we currently support only so-called ReAct agents, it is not hard to envision a future where we'll have +additional agent types including conversational agents. + +Due to LLMs one-shot-forget nature of inferencing, conversational agents might need to remember the context of the +conversation. To support conversational agents, we'll need Agent memory component. The memory component will initially contain +two submodules: entity extraction and summarization + +Entity extraction is a neural module extracting entities from the provided conversation transcript (raw text). +The entities are best thought of as an outcome of Named-entity recognition task; for example, people, places, organizations etc. + +Entity summarization is a neural module that summarizes the entities extracted by the entity extraction module. + +Entity extraction and summarization are run in the background as the conversation progresses. The +frequency of extraction and summarization updates will be configurable. + +The extracted entities along with relevant summaries will be stored in the Agent memory. Agent memory implementation +details are out of scope of this proposal; they could be various short or long term memory storage options. + +For the first version of the agent, we'll strive to keep the memory component as simple as possible; we'll +only implement entity extraction and summarization while we'll use runtime memory for storing entities. + +### Future improvements: + +As we have limited token payload for model inferencing, we'll need to implement a mechanism for decaying memory. + +If we have many entities in the memory, we'll also need to implement a mechanism for entities selection. +We'll likely need no summaries for well-known entities like "Elon Musk" or "New York". + +Information related to the entities could become stale over time (e.g."I'm currently in New York") and we'll +need to implement a mechanism for updating the entities. + +The mechanism for decaying memory, prioritizing and updating entities is out of scope of this proposal. + + +## deepset Cloud API +The Agent should be able to use pipelines deployed on deepset Cloud as a tool. +To this end, the text question needs to be send via REST API to +the [search endpoint](https://docs.cloud.deepset.ai/reference/search_api_v1_workspaces__workspace_name__pipelines__pipeline_name__search_post) of a given pipeline deployed on deepset Cloud. + +In the demo, the Agent will use this tool for question answering on indexed documents of the Haystack documentation, +such as documentation web pages or tutorials. + + +# Drawbacks + +One of the main reasons why we should not work on implementing this proposal is that it is a rather large +undertaking requiring substantial resources. This naturally carries significant risks. We should carefully weigh +the pros and cons of tools we want to implement and prioritize them. The current priority criteria is that the tool +should be useful for the agents MVP, the majority of early adopters and that it should be relatively easy to +implement. We can always add more tools in the future. + +Another priority guidance is the demo we intend to build. We want to build a demo that showcases the agent's +capabilities in a use case that is relevant to the majority of early adopters (current Haystack users). + + +# Alternatives + +We also considered the following demo alternatives: + +- Medical QA: We can build a demo that answers medical questions. This is a very interesting use case but also +fraught with risks. A question one might ask in such a demo is “Which antibiotic should I use for urinary tract infections?”. +A factoid-based QA system might (reasonably) return the answer “trimethoprim 200mg”. However, a “correct” answer is not +sufficient to translate into clinical use. There were other recent demos but they were not very successful. +See https://twitter.com/GlassHealthHQ/status/1620092094034620421 for more details. + +- Public Healthcare QA: a bit less risky proposal than the medical QA. We can build a demo that answers questions about +healthy diet, cooking recipes, vitamines etc. This demo would use almost exactly the same tools as the main demo proposal +and we can potentially switch to this demo if needed. + +- Financial Domain (earnings transcript): we can build a demo that answers questions about earnings transcripts. However, +we were not sure if this is a good use case for the agent as it is not very relevant to the majority of early adopters. + + +# Adoption strategy + +An adoption strategy for this proposal is not needed as much and the objective is to demo the capabilities of the agent +and inspire early adopters to use the agent and the main tools we are going to implement. + + +# Demo + +See the Summary section for the demo description. + +# How we teach this + +We intend to use the demo to teach users about the agent's capabilities. We'll subsequently add more documentation about +core components used in the demo and the agent in general. This demo would be mainly used to promote Haystack Agents and +to generate interest in the agent. + +# Unresolved questions + +Optional, but suggested for first drafts. What parts of the design are still +TBD? diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4172-shaper-in-prompt-template.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4172-shaper-in-prompt-template.md new file mode 100644 index 0000000000000000000000000000000000000000..3dd8180d1e8b956cab26edaaffcd4870bdf34d90 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4172-shaper-in-prompt-template.md @@ -0,0 +1,185 @@ +- Title: Shapers in Prompt Templates +- Decision driver: tstadel +- Start Date: 2023-02-15 +- Proposal PR: (fill in after opening the PR) +- Github Issues or Discussion: + - spike: https://github.com/deepset-ai/haystack/pull/4061 + - solved issues: + - https://github.com/deepset-ai/haystack/issues/3877 + - https://github.com/deepset-ai/haystack/issues/4053 + - https://github.com/deepset-ai/haystack/issues/4047 + +# Summary + +In order to make prompt templates more flexible and powerful while at the same time making PromptNode as easy to use as any other node in Haystack, we want to introduce two modifications to PromptTemplate: +- output: support Shapers in PromptTemplates to enable the user to define how the output to the prompt template should be shaped +- input: extend the prompt syntax to support the usage of functions that can be applied to input variables + +With these modifications prompt templates will be able to define, and abstract away from PromptNode, everything that is necessary to create a Haystack node that is specialized for a certain use-case (e.g. generative QA). Additionally, PromptTemplates will be fully serializable, enabling everyone to share their prompt templates with the community. + +# Basic example + +A generative QA pipeline would be as easy as this: + + ```python + from haystack import Pipeline + from haystack.document_store import InMemoryDocumentStore + from haystack.nodes import PromptNode, EmbeddingRetriever + + document_store = InMemoryDocumentStore() + retriever = EmbeddingRetriever(document_store=document_store, ...) + pn = PromptNode(default_prompt_template="question-answering-with-references") + + p = Pipeline() + p.add_node(component=retriever, name="Retriever", inputs=["Query"]) + p.add_node(component=pn, name="Prompt", inputs=["Retriever"]) + ``` + +As a result we get a pipeline that uses PromptNode as a drop-in replacement for Generators: + + ```python + p.run( + query="What is the most popular drink?" + ) + ``` + + ```python + {'answers': [], + 'invocation_context': {'query': 'What is the most popular drink?', + 'documents': [], + 'answers': []}, + '_debug': {'PromptNode': {'runtime': {'prompts_used': ['Create a concise and informative answer (no more than 50 words) for a given question based solely on the given documents. You must only use information from the given documents. Use an unbiased and journalistic tone. Do not repeat text. Cite the documents using Document[number] notation. If multiple documents contain the answer, cite those documents like ‘as stated in Document[number,number,etc]’. If the documents do not contain the answer to the question, say that ‘answering is not possible given the available information.’\nDocument[1]: Beer is the oldest(1)(2)(3) and most widely consumed(4) type of alcoholic drink in the world, and the third most popular drink overall after potable water and tea.(5) It is produced by the brewing and fermentation of starches, mainly derived from cereal grains—most commonly from malted barley, though wheat, maize (corn), rice, and oats are also used. During the brewing process, fermentation of the starch sugars in the wort produces ethanol and carbonation in the resulting beer.(6) Most modern beer is brewed with hops, which add bitterness and other flavours and act as a natural preservative and stabilizing agent. Other flavouring agents such as gruit, herbs, or fruits may be included or used instead of hops. In commercial brewing, the natural carbonation effect is often removed during processing and replaced with forced carbonation.(7); \n Question: What is the most popular drink?; Answer: ']}}}, + 'root_node': 'Query', + 'params': {}, + 'query': 'What is the most popular drink?', + 'documents': [], + 'node_id': 'PromptNode'} + ``` + +The corresponding prompt template would look like this (provided `join_documents` and `strings_to_answers` Shaper functions are extended a bit): + + ```python + PromptTemplate( + name="question-answering-with-references", + prompt_text="Create a concise and informative answer (no more than 50 words) for a given question " + "based solely on the given documents. You must only use information from the given documents. " + "Use an unbiased and journalistic tone. Do not repeat text. Cite the documents using Document[number] notation. " + "If multiple documents contain the answer, cite those documents like ‘as stated in Document[number,number,etc]’. " + "If the documents do not contain the answer to the question, say that ‘answering is not possible given the available information.’\n" + "{join(documents, '\n', '\nDocument[$idx]: $content', {'\n': ' ', '[': '(', ']': ')'})} \n Question: {query}; Answer: ", + output_shapers=[ + Shaper( + func="strings_to_answers", + inputs={"strings": "results", "documents": "documents"}, + outputs=["answers"], + ) + ], + output_variable="answers", + ) + ``` + +We make sure that we have proper default values for the input shaping function and it is easy to understand. `{join(documents)}` should be usable in most cases. When you want to have more control over document rendering something like `join(documents, DELIMITER, PATTERN, CHAR_REPLACEMENT)` with + + ```python + DELIMITER = "\n" + PATTERN = "$content" # parsable by StringTemplate using data from document.content, document.meta and the index of the document + CHAR_REPLACEMENT = {"[": "(", "}": ")"} # just an example what could be passed here + ``` + +would do. + +Note that the number of how many prompts are created depends on which shaping functions are used. If you use `join(documents)` you will have only one prompt. If you omit the `join` and use `to_list(query)` instead, you will have multiple prompts (one prompt per document). + +# Motivation + +Currently using PromptNode is a bit cumbersome as: +- for using it in popular use-cases like question-answering, it requires to add the Shapers to the pipeline manually which creates a lot of boilerplate code and is not very intuitive +- to customize a prompt within a pipeline, you may need to change four different things: the prompt node, the prompt template, the input shapers and the output shapers. This is not ideal as it requires to write a lot of boilerplate code and makes it hard to iterate quickly on prompts. +- if you wanted to share your prompt template with the community, you would need to share the whole pipeline (as you do need shapers), which is not ideal as it may contain other nodes that are not relevant. + + +# Detailed design + +## General changes +PromptTemplate gets one new attribute: `output_shapers`. These are lists of Shaper objects that are applied to the output of the prompt. +PromptTemplate's syntax is extended to allow for the usage of shaping functions on input variables. These shaping functions are predefined. + +## Basic flow: +PromptNode calls `PromptTemplate.prepare` before executing the prompt. `PromptTemplate.prepare` applies the shaping functions (if present) to the arguments of the `invocation_context`. +PromptNode invokes the prompt on the prepared `invocation_context`. +PromptNode calls `PromptTemplate.post_process` after executing the prompt. `PromptTemplate.post_process` makes all `output_shapers` run on the `invocation_context`. + +## Shaping functions +The PromptTemplate syntax is extended to allow for the usage of shaping functions on input variables. These shaping functions should be easy to understand and use. +We only support positional args for shaping functions. This is because we want to keep the syntax simple and we don't want to overcomplicate the parsing logic. As args any python primitive is allowed (e.g. strings, ints, floats, lists, dicts, None). +Parsing is done by using regular expressions. If we however notice that this is not enough, we can switch to a more complex parsing library like `jinja2`. +Here is a basic (and incomplete) example how the parsing logic could look like: + + ```python + + # template allowing basic list comprehensions to create the wanted string + template = """ + Create a concise and informative answer (no more than 50 words) for a given question + based solely on the given documents. You must only use information from the given documents. + Use an unbiased and journalistic tone. Do not repeat text. Cite the documents using Document[number] notation. + If multiple documents contain the answer, cite those documents like ‘as stated in Document[number,number,etc]’. + If the documents do not contain the answer to the question, say that ‘answering is not possible given the available information. + {join(documents, new_line)} \n Question: {query}; Answer: + """ + + for group in re.findall(r'\{(.*?)\}', template): + if "(" in group and ")" in group: + function_to_call = group[:group.index("(")].strip() + variables_for_function = [var.strip() for var in group[group.index("(")+1:group.index(")")].split(",")] + print(f"Found function '{function_to_call}' with vars '{variables_for_function}'") + else: + print("Found single variable:", group) + + # Returns + # >>> Found function 'join' with vars '['documents', 'new_line']' + # >>> Found single variable: query + ``` + +## Prompt engineering with Haystack Pipelines +Additionally we want to support changing the prompt via a param of `Pipeline.run`. This is useful for example if you want to fine-tune your prompt and iterate quickly on it without having to change the pipeline. The `prompt` param is a string in `Pipeline.run` which will be delegated to the `PromptNode` and then used by `PromptTemplate`. This is similar to how `Pipeline.run` works with the `query` param. Note that the `prompt` param does not affect `output_shapers`. + +## Misc +Note, that `Shapers` are still usable in Pipelines as before. + +# Drawbacks + +Look at the feature from the other side: what are the reasons why we should _not_ work on it? Consider the following: + +- What's the implementation cost, both in terms of code size and complexity? A good day +- Can the solution you're proposing be implemented as a separate package, outside of Haystack? No +- Does it teach people more about Haystack? No, but it makes it easier to use especially for beginners. +- How does this feature integrate with other existing and planned features? It doesn't change any existing features and should nicely integrate with agents. +- What's the cost of migrating existing Haystack pipelines (is it a breaking change?)? None + +It also fosters a bit the nesting of components in Haystack. Although the whole PromptNode ecosystem already does this (e.g. via PromptModel, PromptTemplate being used by PromptNode), it's still a bit of a new concept. However, I think it's a good one and it's not too hard to understand. + +We still don't have access to PromptNode, PromptModel or the invocation layer inside of PromptTemplates. If we want PromptTemplate to access fundamental parts of them (e.g. the tokenizer), we would need to pass them to the PromptTemplate. This would make the whole system more complex, but it would be possible. + +# Alternatives + +Sub-classing specialized PromptNodes like QuestionAnsweringPromptNode, which would have the shapers already defined. This would make it easier to use, but it would be harder to iterate quickly on prompts, be less flexible and sharing is difficult. The same is true for sub-classing PromptTemplate like QuestionAnsweringPromptTemplate. Both sub-classing approaches would make it easier to use, but it would be harder to iterate quickly on prompts, be less flexible and sharing is difficult. + +Having `input_shapers` in the same way as `output_shapers` in the PromptTemplate. This would make it harder for users to get started as they would need to understand Shapers and which functions are relevant for input shaping. +# Adoption strategy + +As the syntax for input variables in `PromptTemplate` changes we can do the following: +- raise an error if the old syntax is used and tell the user to use the new syntax +- support the old syntax for a while and raise a deprecation warning + +# How we teach this + +We should show how: +- predefined PromptTemplates can be used +- predefined PromptTemplates can be customized +- custom PromptTemplates can be created + +# Unresolved questions + +How does `OpenAIAnswerGenerator` make use of input shaping functions and output shapers? +- output shapers: it doesn't use them +- input shaping functions: it uses them if they are present. If not it uses its own default functions. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4284-drop-basecomponent.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4284-drop-basecomponent.md new file mode 100644 index 0000000000000000000000000000000000000000..8ed961b6cbf8c869ec087e9bbe56ae2cd46460c7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4284-drop-basecomponent.md @@ -0,0 +1,950 @@ +- Title: Drop `BaseComponent` and reimplement `Pipeline`. +- Decision driver: @ZanSara +- Start Date: 27/02/2023 +- Proposal PR: #4284 +- Github Issue or Discussion: #2807 + +# Summary + +Haystack Pipelines are very powerful objects, but they still have a number of unnecessary limitations, by design and by implementation. + +This proposal aims to address most of the implementation issues, some fundamental assumptions like the need for DAGs and the `BaseComponent` class, and proposes a solution for the question of `DocumentStore`'s status with respect to the `Pipeline`. + + +# Motivation + +Pipelines are the fundamental component of Haystack and one of its most powerful concepts. At its core, a Pipeline is a DAG (Directed Acyclic Graph) of objects called Nodes, or Components, each of whom executes a specific transformation on the data flowing along the pipeline. In this way, users can combine powerful libraries, NLP models, and simple Python snippets to connect a herd of tools into a one single, coherent object that can fulfill an infinite variety of tasks. + +However, as it currently stands, the `Pipeline` object is also imposing a number of limitations on its use, most of which are likely to be unnecessary. Some of these include: + +- DAGs. DAGs are safe, but loops could enable many more usecases, like `Agents`. + +- `Pipeline` can select among branches, but cannot run such branches in parallel, except for some specific and inconsistent corner cases. For further reference and discussions on the topic, see: + - https://github.com/deepset-ai/haystack/pull/2593 + - https://github.com/deepset-ai/haystack/pull/2981#issuecomment-1207850632 + - https://github.com/deepset-ai/haystack/issues/2999#issuecomment-1210382151 + +- `Pipeline`s are forced to have one single input and one single output node, and the input node has to be called either `Query` or `Indexing`, which softly forbids any other type of pipeline. + +- The fixed set of allowed inputs (`query`, `file_paths`, `labels`, `documents`, `meta`, `params` and `debug`) blocks several usecases, like summarization pipelines, translation pipelines, even some sort of generative pipelines. + +- `Pipeline`s are often required to have a `DocumentStore` _somewhere_ (see below), even in situation where it wouldn't be needed. + - For example, `Pipeline` has a `get_document_store()` method which iterates over all nodes looking for a `Retriever`. + +- The redundant concept of `run()` and `run_batch()`: nodes should take care of this distinction internally if it's important, otherwise run in batches by default. + +- The distinction between a `Pipeline` and its YAML representation is confusing: YAMLs can contain several pipelines, but `Pipeline.save_to_yaml()` can only save a single pipeline. + +In addition, there are a number of known bugs that makes the current Pipeline implementation hard to work with. Some of these include: + +- Branching and merging logic is known to be buggy even where it's supported. +- Nodes can't be added twice to the same pipeline in different locations, limiting their reusability. +- Pipeline YAML validation needs to happen with a YAML schema because `Pipeline`s can only be loaded along with all their nodes, which is a very heavy operation. Shallow or lazy loading of nodes doesn't exist. +- Being forced to use a schema for YAML validation makes impossible to validate the graph in advance. + +On top of these issues, there is the tangential issue of `DocumentStore`s and their uncertain relationship with `Pipeline`s. This problem has to be taken into account during a redesign of `Pipeline` and, if necessary, `DocumentStore`s should also be partially impacted. Some of these issues include: + +- `DocumentStore`s are nodes in theory, but in practice they can be added to `Pipeline`s only to receive documents to be stored. On the other hand, `DocumentStore`'s most prominent usecase is as a _source_ of documents, and currently they are not suited for this task without going through an intermediary, most often a `Retriever` class. + - The relationship between `DocumentStore` and `Retriever` should be left as a topic for a separate proposal but kept in mind, because `Retriever`s currently act as the main interface for `DocumentStore`s into `Pipeline`s. + +This proposal tries to address all the above point by taking a radical stance with: + +- A full reimplementation of the `Pipeline` class that does not limit itself to DAGs, can run branches in parallel, can skip branches and can process loops safely. + +- Dropping the concept of `BaseComponent` and introducing the much lighter concept of `Node` in its place. + +- Define a clear contract between `Pipeline` and the `Node`s. + +- Define a clear place for `DocumentStore`s with respect to `Pipeline`s that doesn't forcefully involve `Retriever`s. + +- Redesign the YAML representation of `Pipeline`s. + +# Basic example + +A simple example of how the new Pipeline could look like is shown here. This example does not address `DocumentStore`s or YAML serialization, but rather focuses on the shift between `BaseComponent` and `Node`s. + +For the detailed explanation behind the design choices and all open questions, see the "Detailed Design" section and the draft implementation here: https://github.com/ZanSara/haystack-2.0-draft + +## Simple example + +This is a very simplified example that performs some mathematical operations. See below for more realistic examples. + +```python +from typing import Dict, Any, List, Tuple +from haystack.pipeline import Pipeline +from haystack.nodes import node + +# A Haystack Node. See below for details about this contract. +# Crucial components are the @node decorator and the `run()` method +@node +class AddValue: + def __init__(self, add: int = 1, input_name: str = "value", output_name: str = "value"): + self.add = add + self.init_parameters = {"add": add} + self.inputs = [input_name] + self.outputs = [output_name] + + def run( + self, + name: str, + data: List[Tuple[str, Any]], + parameters: Dict[str, Any], + stores: Dict[str, Any], + ): + my_parameters = parameters.get(name, {}) + add = my_parameters.get("add", self.add) + + for _, value in data: + value += add + + return ({self.outputs[0]: value}, parameters) + + +@node +class Double: + def __init__(self, input_edge: str = "value"): + self.init_parameters = {"input_edge": input_edge} + self.inputs = [input_edge] + self.outputs = [input_edge] + + def run( + self, + name: str, + data: List[Tuple[str, Any]], + parameters: Dict[str, Any], + stores: Dict[str, Any], + ): + for _, value in data: + value *= 2 + + return ({self.outputs[0]: value}, parameters) + + +pipeline = Pipeline() + +# Nodes can be initialized as standalone objects. +# These instances can be added to the Pipeline in several places. +addition = AddValue(add=1) + +# Nodes are added with a name and an node. Note the lack of references to any other node. +pipeline.add_node("first_addition", addition, parameters={"add": 3}) # Nodes can store default parameters per node. +pipeline.add_node("second_addition", addition) # Note that instances can be reused +pipeline.add_node("double", Double()) + +# Nodes are the connected as input node: [list of output nodes] +pipeline.connect(connect_from="first_addition", connect_to="double") +pipeline.connect(connect_from="double", connect_to="second_addition") + +pipeline.draw("pipeline.png") + +# Pipeline.run() accepts 'data' and 'parameters' only. Such dictionaries can contain +# anything, depending on what the first node(s) of the pipeline requires. +# Pipeline does not validate the input: the first node(s) should do so. +results = pipeline.run( + data={"value": 1}, + parameters = {"second_addition": {"add": 10}} # Parameters can be passed at this stage as well +) +assert results == {"value": 18} +``` + +The result of `Pipeline.draw()`: + +![image](images/4284-drop-basecomponent/pipeline.png) + + +## Query Pipeline + +This query pipeline includes real Reader and Retriever nodes. A new set of primitives and a new DocumentStore has been used for this example: please refer to the draft implementation for details on those: https://github.com/ZanSara/haystack-2.0-draft + + +
+RetrieveByBM25 + +```python +from typing import Dict, Any, List, Tuple + +import logging + +from haystack.data import TextQuery +from haystack.nodes import node + + +@node +class RetrieveByBM25: + """ + Simple dummy BM25 Retriever that works with MemoryStore. + Supports batch processing. + """ + def __init__(self, + input_name: str = "query", + output_name: str = "documents_by_query", + default_store: str = "documents", + default_top_k: int = 10 + ): + self.default_store = default_store + self.default_top_k = default_top_k + + # Pipelne's contract: + self.init_parameters = { + "input_name": input_name, + "output_name": output_name, + "default_store": default_store, + "default_top_k": default_top_k + } + self.inputs = [input_name] + self.outputs = [output_name] + + def run( + self, + name: str, + data: List[Tuple[str, Any]], + parameters: Dict[str, Any], + stores: Dict[str, Any], + ): + my_parameters = parameters.get(name, {}) + store_name = my_parameters.get("store", self.default_store) + top_k = my_parameters.get("top_k", self.default_top_k) + + # This can be done safely, because Nodes expect the Pipeline to respect their contract. + # Errors here are Pipeline's responsibility, so Nodes should not care. + queries = data[0][1] + + # Batch support is not the pipeline's business, but the node's + if isinstance(queries, TextQuery): + queries = [queries] + elif queries and not ( + isinstance(queries, list) and + all(isinstance(query, TextQuery) for query in queries) + ): + raise ValueError(f"'{data[0][0]}' can only contain TextQuery objects. '{data[0][0]}' contains: {queries}") + + if not store_name in stores.keys(): + raise ValueError(f"No store called '{store_name}'.") + + results = stores[store_name].get_relevant_documents(queries=queries, top_k=top_k) + + return ({self.outputs[0]: results}, parameters) +``` + +
+ + +
+ReadByTransformers + +```python +from typing import Dict, Any, List, Tuple + +from haystack.data import TextAnswer, Span +from haystack import node + + +@node +class ReadByTransformers: + """ + Simple dummy Transformers Reader. + Supports batch processing. + """ + def __init__(self, + model_name_or_path: str, + default_top_k: int = 5, + default_no_answer: bool = True, + default_max_seq_len: int = 256, + default_doc_stride: int = 128, + default_batch_size: int = 16, + default_context_window_size: int = 70, + input_name: str = "documents_by_query", + output_name: str = "answers_by_query", + ): + self.model_name_or_path = model_name_or_path + self.default_top_k = default_top_k + self.default_no_answer = default_no_answer + self.default_max_seq_len = default_max_seq_len + self.default_doc_stride = default_doc_stride + self.default_batch_size = default_batch_size + self.default_context_window_size = default_context_window_size + self.model = None + + self.init_parameters = { + "input_name": input_name, + "output_name": output_name, + "model_name_or_path": model_name_or_path, + "default_top_k": default_top_k, + "default_no_answer": default_no_answer, + "default_max_seq_len": default_max_seq_len, + "default_doc_stride": default_doc_stride, + "default_batch_size": default_batch_size, + "default_context_window_size": default_context_window_size, + } + self.inputs = [input_name] + self.outputs = [output_name] + + def warm_up(self): + try: + from transformers import pipeline + except Exception as e: + raise ImportError("Can't import 'transformers': this node won't work.") from e + + if not self.model: + self.model = pipeline( + "question-answering", + model=self.model_name_or_path, + ) + + def run( + self, + name: str, + data: List[Tuple[str, Any]], + parameters: Dict[str, Any], + stores: Dict[str, Any], + ): + my_parameters = parameters.get(name, {}) + top_k = my_parameters.get("top_k", self.default_top_k) + no_answer = my_parameters.get("no_answer", self.default_no_answer) + max_seq_len = my_parameters.get("max_seq_len", self.default_max_seq_len) + doc_stride = my_parameters.get("doc_stride", self.default_doc_stride) + batch_size = my_parameters.get("batch_size", self.default_batch_size) + context_window_size = my_parameters.get("context_window_size", self.default_context_window_size) + + documents_for_queries = data[0][1] + + inputs = [] + for query, documents in documents_for_queries.items(): + inputs.extend([ + self.model.create_sample(question=query.content, context=doc.content) # type: ignore + for doc in documents + ]) + + # Inference + predictions = self.model( # type: ignore + inputs, + top_k=top_k, + handle_impossible_answer=no_answer, + max_seq_len=max_seq_len, + doc_stride=doc_stride, + batch_size=batch_size, + ) + + # Builds the TextAnswer object + answers_for_queries = {query: [] for query in documents_for_queries.keys()} + for query, documents in documents_for_queries.items(): + documents = list(documents) # FIXME consume here the iterator for now + docs_len = len(documents) + relevant_predictions = predictions[:docs_len] + predictions = predictions[docs_len:] + + for document, prediction in zip(documents, relevant_predictions): + if prediction.get("answer", None): + context_start = max(0, prediction["start"] - context_window_size) + context_end = min(len(document.content), prediction["end"] + context_window_size) + answers_for_queries[query].append( + TextAnswer( + content=prediction["answer"], + score=prediction["score"], + context=document.content[context_start:context_end], + offset_in_document=Span(start=prediction["start"], end=prediction["end"]), + offset_in_context=Span(start=prediction["start"] - context_start, end=prediction["end"] - context_start), + document_id=document.id, + meta=document.meta, + ) + ) + elif no_answer: + answers_for_queries[query].append( + TextAnswer( + content="", + score=prediction["score"], + meta=document.meta, + ) + ) + answers_for_queries[query] = sorted(answers_for_queries[query], reverse=True)[:top_k] + return ({self.outputs[0]: answers_for_queries}, parameters) +``` + +
+ +```python +import json +from pathlib import Path + +from haystack.pipeline import Pipeline +from haystack.stores import MemoryDocumentStore +from haystack.data import TextQuery, TextDocument +from haystack.nodes import RetrieveByBM25, ReadByTransformers + +import logging + +logging.basicConfig(level=logging.DEBUG) + + +def test_pipeline(): + document_store = MemoryDocumentStore() + document_store.write_documents([ + TextDocument(content="My name is Anna and I live in Paris."), + TextDocument(content="My name is Serena and I live in Rome."), + TextDocument(content="My name is Julia and I live in Berlin."), + ]) + pipeline = Pipeline() + pipeline.connect_store("my_documents", document_store) + pipeline.add_node("retriever", RetrieveByBM25(default_store="my_documents")) + pipeline.add_node("reader", ReadByTransformers(model_name_or_path="distilbert-base-uncased-distilled-squad")) + + pipeline.connect(connect_from="retriever", connect_to="reader") + pipeline.draw("query_pipeline.png") + + results = pipeline.run({"query": TextQuery(content="Who lives in Berlin?")}) + + print(results) + + +if __name__ == "__main__": + test_pipeline() +``` +Pipeline diagram: + +![image](images/4284-drop-basecomponent/query_pipeline.png) + +Output: +``` +{ + "answers_by_query": { + "TextQuery('Who lives in Berlin?')": [ + "TextAnswer(id='bfe8d4e1fd43db24a61847a4efea7e4b', content='Julia', content_type='text', meta={}, id_hash_keys=['content'], score=0.9149983525276184, context='My name is Julia and I live in Berlin.', offset_in_document=Span(start=11, end=16), offset_in_context=Span(start=11, end=16), document_id='6afac5b39e0ddd125a7513b13fefe27d')" + ] + } +} +``` + +**IMPORTANT NOTE:** This is an example meant to showcase the concept. However, it has a major flaw: it is coupling queries and documents tightly. + +This does not surface as an issue in this simple example, but it limits severely the reusability of Retrievers and Readers because they do not simply output documents anymore, they output a complex structure that is only accessible by them. We should do our best to decouple values as much as possible, so that other nodes can access only the specific output required for them to operate. + +In this specific example, we might imagine a multi-modal Retriever connected to several single-modality Readers. To make that work, we would need a DocumentClassifier, an intermediate node to route the documents by type to each Reader: in the current design, that won't be easy. If instead queries and documents were send out in two separate lists, the task for DocumentClassifier would be far easier. + +This is a bright example of how good and careful design of nodes is going to be vital for the health of the framework, and will force us to be way more strict around best practices and standards. + +# Detailed design + +This section focuses on the concept rather than the implementation strategy. For a discussion on the implementation, see the draft here: https://github.com/ZanSara/haystack-2.0-draft + +## The Pipeline API + +These are the core features that drove the design of the revised Pipeline API: + +- An execution graph that is more flexible than a DAG. +- A clear place for `DocumentStore`s + +Therefore, the revised Pipeline object has the following API: + +- Core functions: + - `__init__(metadata=None)`: Creates an empty Pipeline. Note the `metadata` field, which can be used to carry metadata info. Such metadata might come useful in `Application`s (see below) to distinguish `Pipeline`s, tag them, describe them, etc. + - `run(data, parameters, debug)`: the core of the class. Relies on `networkx` for most of the heavy-lifting. Check out the implementation (https://github.com/ZanSara/haystack-2.0-draft/blob/main/new-haystack/haystack/pipeline/pipeline.py) for details: the code is heavily commented on the main loop and on the handling of non-trivial execution paths like branch selection, parallel branch execution, loops handling, multiple input/output and so on. For the effects of `debug`, see the dedicated section below. + - `draw(path)`: as in the old Pipeline object. Based on `pygraphviz` (which requires `graphviz`), but we might need to look for pure Python alternatives based on Matplotlib to reduce our dependencies. +- Graph building: + - `add_node(name, node, parameters)`: adds a disconnected node to the graph. It expects Haystack nodes in the `node` parameter and will fail if they aren't respecting the contract. See below for a more detailed discussion of the Nodes' contract. + - `get_node(name)`: returns the node's information stored in the graph + - `connect(input_node, output_node)`: connects nodes together. It will fail if the nodes inputs and outputs do not match: see the Nodes' contract to understand how Nodes can declare their I/O. +- Docstore management: + - `add_store(name, store)`: adds a DocumentStore to the stores that are passed down to the nodes through the `stores` variable. + - `list_stores()`: returns all connected stores. + - `get_store(name)`: returns a specific document store by name. + +Example pipeline topologies supported by the new implementation (images taken from the test suite): + +
+Merging pipeline + +![image](images/4284-drop-basecomponent/merging_pipeline.png) + +In this pipeline, several nodes send their input into a single output node. Note that this pipeline has several starting nodes, something that is currently not supported by Haystack's `Pipeline`. + +
+ +
+Branching pipeline with branch skipping + +![image](images/4284-drop-basecomponent/decision_pipeline.png) + +In this pipeline, only one edge will run depending on the decision taken by the `remainder` node. Note that this pipeline has several terminal nodes, something that is currently not supported by Haystack's `Pipeline`. + +
+ +
+Branching pipeline with parallel branch execution + +![image](images/4284-drop-basecomponent/parallel_branches_pipeline.png) + +In this pipeline, all the edges that leave `enumerate` are run by `Pipeline`. Note that this usecase is currently not supported by Haystack's `Pipeline`. + +
+ +
+Branching pipeline with branch skipping and merge + +![image](images/4284-drop-basecomponent/decision_and_merge_pipeline.png) + +In this pipeline, the merge node can understand that some of its upstream nodes will never run (`remainder` selects only one output edge) and waits only for the inputs that it can receive, so one from `remainder`, plus `no-op`. + +
+ +
+Looping pipeline + +![image](images/4284-drop-basecomponent/looping_pipeline.png) + +This is a pipeline with a loop and a counter that statefully counts how many times it has been called. + +Note that the new `Pipeline` can set a maximum number of allowed visits to nodes, so that loops are eventually stopped if they get stuck. + +
+ +
+Looping pipeline with merge + +![image](images/4284-drop-basecomponent/looping_and_merge_pipeline.png) + +This is a pipeline with a loop and a counter that statefully counts how many times it has been called. There is also a merge node at the bottom, which shows how Pipeline can wait for the entire loop to exit before running `sum`. + +
+ +
+Arbitrarily complex pipeline + +![image](images/4284-drop-basecomponent/complex_pipeline.png) + +This is an example of how complex Pipelines the new objects can support. This pipeline combines all cases above: +- Multiple inputs +- Multiple outputs +- Decision nodes and branches skipped due to a selection +- Distribution nodes and branches executed in parallel +- Merge nodes where it's unclear how many edges will actually carry values +- Merge nodes with repeated inputs (`sum` takes three `value` edges) or distinct inputs (`diff` takes `value` and `sum`) +- Loops along a branch +
+ +NOTE: the draft implementation supports all of these topologies already. You can find the code for each of these pipelines under https://github.com/ZanSara/new-haystack-pipeline-draft/tree/main/new-haystack/tests/integration + +## The Node contract + +A Haystack node is any class that abides the following contract: + +```python +# This decorator does very little, but is necessary for Pipelines to recognize +# this class as a Haystack node. Check its implementation for details. +@node +class MyNode: + + def __init__(self, model_name: str: "deepset-ai/a-model-name"): + """ + Haystack nodes should have an `__init__` method where they define: + + - `self.inputs = []`: + A list with all the edges they can possibly receive input from + + - `self.outputs = []`: + A list with the edges they might possibly produce as output + + - `self.init_parameters = {}`: + Any state they wish to be persisted in their YAML serialization. + These values will be given to the `__init__` method of a new instance + when the pipeline is deserialized. + + The `__init__` must be extremely lightweight, because it's a frequent + operation during the construction and validation of the pipeline. If a node + has some heavy state to initialize (models, backends, etc...) refer to the + `warm_up()` method. + """ + # Lightweight state can be initialized here, for example storing the model name + # to be loaded later. See self.warm_up() + self.model = None + self.model_name = model_name + self.how_many_times_have_I_been_called = 0 + + # Contract - all three are mandatory. + self.init_parameters = {"model_name": model_name} + self.inputs = ["input_name"] + self.outputs = ["output_name"] + + def 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 nodes it called `warm_up` on. + """ + if not self.model: + self.model = AutoModel.load_from_pretrained(self.model_name) + + def run( + self, + name: str, + data: List[Tuple[str, Any]], + parameters: Dict[str, Any], + stores: Dict[str, Any], + ): + """ + Mandatory method. + + This is the method where the main functionality of the node should be carried out. + It's called by `Pipeline.run()`, which passes the following parameters to it: + + - `name: str`: the name of the node. Allows the node to find its own parameters in the `parameters` dictionary (see below). + + - `data: List[Tuple[str, Any]]`: the input data. + Pipeline guarantees that the following assert always passes: `assert self.inputs == [name for name, value in data]`, + which means that: + - `data` is of the same length as `self.inputs`. + - `data` contains one tuple for each string stored in `self.inputs`. + - no guarantee is given on the values of these tuples: notably, if there was a decision node upstream, some values might be `None`. + For example, if a node declares `self.inputs = ["value", "value"]` (think of a Sum node), `data` might look like: + - `[("value", 1), ("value", 10)]` + - `[("value", None), ("value", 10)]` + - `[("value", None), ("value", None)]`, or even + - `[("value", 1), ("value", ["something", "unexpected"])]` + but it will never look like: + - `[("value", 1), ("value", 10), ("value", 100)]`, + - `[("value": 15)]` or + - `[("value": 15), ("unexpected", 10)]`. + + - `parameters: Dict[str, Dict[str, Any]]`: a dictionary of dictionaries with all the parameters for all nodes. + Note that all nodes have access to all parameters for all other nodes: this might come handy to nodes like `Agent`s, that + want to influence the behavior of nodes downstream. + Nodes can access their own parameters using `name`, but they must not assume their name is present in the dictionary. + Therefore the best way to get the parameters is with `my_parameters = parameters.get(name, {})` + + - `stores`: a dictionary of all the (Document)Stores connected to this pipeline. + + Pipeline expect the output of this function to be a tuple in the following format: + + `( {edge: value for edge in }, {the parameters dictionary}) + + Which means that: + - Nodes are not forced to produce output on all the expected outputs: for example nodes taking a decision, like classifiers, + can produce output on a subset of the expected output edges and Pipeline will figure out the rest. + - Nodes must not add any key in the data dictionary that is not present in `self.outputs`, + - Nodes can alter the content of `parameters` and their changes will be propagated downstream. + """ + self.how_many_times_have_I_been_called += 1 + + value = data[0][1] + print(f"Hello I'm {name}! This instance have been called {self.how_many_times_have_I_been_called} times and this is the value I received: {value}") + + return ({self.outputs[0]: value}, parameters) +``` + +This contract is stored in the docstring of `@node` and acts as the single source of truth. + +Note how there are a few fundamental shifts from the old concept of pipelines and nodes: + +- There's no base class for nodes anymore. A node is whatever object is decorated with `@node`. + +- Pipelines can now be validated by instantiating them, and instantiation is going to be very fast, because the nodes are supposed to defer heavy operations to the `warm_up()` method. This does not prevent us from having shallow validation with a schema, but gives us more room for other validation strategies too. + +- Edges are designed to carry one value, be it a primitive like an `int` or a complex dictionary or an object. We have no more "fat edges" by default that carry complex output: we can now safely output several values on several edges and, if need be, connect multiple edges between the same two nodes. + - For example, if `node_a` outputs `value_1` and `value_2`, both these edges can be given to a `sum` node. + +- There's no more naming ambiguity between nodes and components. + +### Nodes discovery logic + +When pipelines are loaded from YAML, Pipeline needs to find the classes definition somewhere in the imported modules. Currently, at initialization `Pipeline` looks for classes which is decorated with the `@node` decorator under `haystack`, however such search can be extended (or narrowed) by setting the `search_nodes_in` init parameter of `Pipeline`. Note that it will try to import any module that is not imported yet. + +Search might fail in narrow corner cases: for example, inner classes are not discovered (often the case in tests). For these scenarios, `Pipeline` also accepts an `extra_nodes` init parameter that allows users to explicitly provide a dictionary of nodes to merge with the other discovered nodes. + +Name collisions are handled by prefixing the node name with the name of the module it was imported from. + +## Validation + +Pipeline performs validation on the edge name level: when calling `Pipeline.connect()`, it uses the values of the nodes' `self.inputs` and `self.outputs` to make sure that the connection is possible. + +Nodes are required, by contract, to explicitly define their inputs and outputs, and these values are used by the `connect` method to validate the connection, and by the `run` method to route values. + +For example, let's imagine we have two nodes with the following I/O declared: + +```python +@node +class NodeA: + + def __init__(self): + self.inputs = ["input"] + self.outputs = ["intermediate_value"] + + def run(self): + pass + +@node +class NodeB: + + def __init__(self): + self.inputs = ["intermediate_value"] + self.outputs = ["output"] + + def run(self): + pass +``` + +This is the behavior of `Pipeline.connect()`: + +```python +pipeline.connect('node_a', 'node_b') +# Succeeds: no output + +pipeline.connect('node_a', 'node_a') +# Traceback (most recent call last): +# File "/home/sara/work/haystack-2/example.py", line 29, in +# pipeline.connect('node_a', 'node_a') +# File "/home/sara/work/haystack-2/new-haystack/haystack/pipeline/pipeline.py", line 224, in connect +# raise PipelineConnectError( +# haystack.pipeline._utils.PipelineConnectError: Cannot connect 'node_a' with 'node_a' with an edge named 'intermediate_value': their declared inputs and outputs do not match. +# Upstream node 'node_a' declared these outputs: +# - intermediate_value (free) +# Downstream node 'node_a' declared these inputs: +# - input (free) + +pipeline.connect('node_b', 'node_a') +# Traceback (most recent call last): +# File "/home/sara/work/haystack-2/example.py", line 29, in +# pipeline.connect('node_b', 'node_a') +# File "/home/sara/work/haystack-2/new-haystack/haystack/pipeline/pipeline.py", line 224, in connect +# raise PipelineConnectError( +# haystack.pipeline._utils.PipelineConnectError: Cannot connect 'node_b' with 'node_a' with an edge named 'output': their declared inputs and outputs do not match. +# Upstream node 'node_b' declared these outputs: +# - output (free) +# Downstream node 'node_a' declared these inputs: +# - input (free) +``` + +This type of error reporting was found especially useful for nodes that declare a variable number and name of inputs and outputs depending on their initialization parameters (think of language classifiers, for example). + +One shortcoming is that currently Pipeline "trusts" the nodes to respect their own declarations. So if a node states that it will output `intermediate_value`, but outputs something else once run, `Pipeline` will fail. We accept this failure as a "contract breach": the node should fix its behavior and `Pipeline` should not try to prevent such scenarios. + +Note: the draft implementation does not validate the type of the values, but only their names. So two nodes might agree to pass a variable called `documents` to each other, but one might output a `Set` when the receiver expects a `List`, and that will cause a crash. However, such check will be added. + +Other features planned for addition are: +- automatically connect nodes if matching edges are found, even if the match is partial +- double check for unconnected nodes and edges + +### Parameters hierarchy + +Parameters can be passed to nodes at several stages, and they have different priorities. Here they're listed from least priority to top priority. + +1. **Node's default `__init__` parameters**: nodes's `__init__` can provide defaults. Those are used only if no other parameters are passed at any stage. +2. **Node's `__init__` parameters**: at initialization, nodes might be given values for their parameters. These are stored within the node instance and, if the instance is reused in the pipeline several times, they will be the same on all of them +3. **Pipeline's `add_node()`**: When added to the pipeline, users can specify some parameters that have to be given only to that node specifically. They will override the node instance's parameters, but they will be applied only in that specific location of the pipeline and not be applied to other instances of the same node anywhere else in the graph. +4. **Pipeline's `run()`**: `run()` also accepts a dictionary of parameters that will override all conflicting parameters set at any level below, quite like Pipeline does today. + +Example: + +```python + +class Node: + def __init__(self, value_1: int = 1, value_2: int = 1, value_3: int = 1, value_4: int = 1): + ... + +node = Node(value_2=2, value_3=2, value_4=2) +pipeline = Pipeline() +pipeline.add_node("node", node, parameters={"value_3": 3, "value_4": 3}) +... +pipeline.run(data={...}, parameters={"node": {"value_4": 4}}) + +# Node will receive {"value_1": 1, "value_2": 2, "value_3": 3,"value_4": 4} +``` + +### Debug mode + +The strategy towards debugging: + +- Pipelines are aware of debug mode, Nodes aren't. +- Pipeline will produce debug output entirely through machine-readable logs. + +This implies that nodes don't have any **standardized** way to tell whether they're being debugged (while nothing prevents them from accepting a `debug` parameter if need be), and that they don't have any **standardized** way to output debug info except from logs (while nothing prevents them from supporting a `debug` edge if need be). + +We took this decision to encourage nodes to implement the same behavior regardless of debug mode, and to incentivize the use of machine-readable logs. + +### Evaluation + +Evaluation of Pipelines is a topic too wide for the scope of this proposal, so it has been left out on purpose. We will open a separate proposal after this one has been approved. + +### Pipeline Serialization + +_(Disclaimer: no draft implementation available yet)_ + +We decide to remove the possibility of serializing single `Pipeline`s and to defer such task to a dedicated marshalling utility. This decision was made to remove the current ambiguity of `Pipeline` YAMLs being able to store several `Pipeline`s, while `Pipeline.save_to_yaml()` can only save one. + +In code, saving and loading pipelines will look like this: + +```python +from haystack.pipelines import Pipeline, save_pipelines, load_pipelines + +query_pipeline = Pipeline() +indexing_pipeline = Pipeline() +# .. assemble the pipelines ... + +# Save the pipelines +save_pipelines( + pipelines={ + "query": query_pipeline, + "indexing": indexing_pipeline, + }, + path="my_pipelines.json", + writer=json.dumps +) + +# Load the pipelines +new_pipelines = load_pipelines( + path="my_pipelines.json", + reader=json.loads +) + +assert new_pipelines["query"] == query_pipeline +assert new_pipelines["indexing"] == indexing_pipeline +``` + +Note how the save/load functions accept a writer/reader function: this choice frees us from committing strongly to a specific template language, and although a default will be set (be it YAML, TOML, HCL or anything else) the decision can be overridden by passing another explicit reader/writer function to the `save_pipelines`/`load_pipelines` functions. + +This is how the resulting file will look like, assuming a JSON writer was chosen. + +`my_pipeline.json` + +```json +{ + # A list of "dependencies" for the application. + # Used to ensure all external nodes are present when loading. + "dependencies" : [ + "haystack == 2.0.0", + "my_custom_node_module == 0.0.1", + ], + + # Stores are defined here, outside single pipeline graphs. + # All pipelines have access to all these docstores. + "stores": { + # Nodes will be able to access them by the name defined here, + # in this case `my_first_store` (see the retrievers below). + "my_first_store": { + # class_name is mandatory + "class_name": "InMemoryDocumentStore", + # Then come all the additional parameters for the store + "use_bm25": true + }, + "my_second_store": { + "class_name": "InMemoryDocumentStore", + "use_bm25": false + } + }, + + # Nodes are defined here, outside single pipeline graphs as well. + # All pipelines can use these nodes. Instances are re-used across + # Pipelines if they happen to share a node. + "nodes": { + # In order to reuse an instance across multiple nodes, instead + # of a `class_name` there should be a pointer to another node. + "my_sparse_retriever": { + # class_name is mandatory, unless it's a pointer to another node. + "class_name": "BM25Retriever", + # Then come all the additional init parameters for the node + "store_name": "my_first_store", + "top_k": 5 + }, + "my_dense_retriever": { + "class_name": "EmbeddingRetriever", + "model_name": "deepset-ai/a-model-name", + "store_name": "my_second_store", + "top_k": 5 + }, + "my_ranker": { + "class_name": "Ranker", + "inputs": ["documents", "documents"], + "outputs": ["documents"], + }, + "my_reader": { + "class_name": "Reader", + "model_name": "deepset-ai/another-model-name", + "top_k": 3 + } + }, + + # Pipelines are defined here. They can reference all nodes above. + # All pipelines will get access to all docstores + "pipelines": { + "sparse_question_answering": { + # Mandatory list of edges. Same syntax as for `Pipeline.connect()` + "edges": [ + ("my_sparse_retriever", ["reader"]) + ], + # To pass some parameters at the `Pipeline.add_node()` stage, add them here. + "parameters": { + "my_sparse_retriever": { + "top_k": 10 + } + }, + # Metadata can be very valuable for dC and to organize larger Applications + "metadata": { + "type": "question_answering", + "description": "A test pipeline to evaluate Sparse QA.", + "author": "ZanSara" + }, + # Other `Pipeline.__init__()` parameters + "max_allowed_loops": 10, + }, + "dense_question_answering": { + "edges": [ + ("my_dense_retriever", ["reader"]) + ], + "metadata": { + "type": "question_answering", + "description": "A test pipeline to evaluate Sparse QA.", + "author": "an_intern" + } + }, + "hybrid_question_answering": { + "edges": [ + ("my_sparse_retriever", ["ranker"]), + ("my_dense_retriever", ["ranker"]), + ("ranker", ["reader"]), + ], + "metadata": { + "type": "question_answering", + "description": "A test pipeline to evaluate Hybrid QA.", + "author": "the_boss" + } + } + } +} +``` + +# Open questions + +None left. + +# Drawbacks + +There are a number of drawbacks about the proposed approach: + +- Migration is going to be far from straightforward for us. Although many nodes can probably work with minor adaptations into the new system, it would be beneficial for most of them to be reduced to their `run()` method, especially indexing nodes. This means that nodes need, at least, to be migrated one by one to the new system and code copied over. + +- Migration is going to be far from straightforward for the users: see "Adoption strategy". + +- This system allows for pipelines with more complex topologies, which brings the risk of more corner cases. `Pipeline.run()` must be made very solid in order to avoid this scenario. + +- Nodes might break more easily while running due to unexpected inputs. While well designed nodes should internally check and deal with such situations, we might face larger amount of bugs due to our failure at noticing the lack of checks at review time. + +- The entire system work on the assumption that nodes are well behaving and "polite" to other nodes, for example not touching their parameters unless necessary, etc. Malicious or otherwise "rude" nodes can wreak havoc in `Pipeline`s by messing with other node's parameters. + +## Known limitations + +- **Reusability of nodes across Pipelines in REST API.** Currently, REST API are designed in such a way that a separate worker is spawned for each pipeline deployed. That makes sharing node instances across them a non-starter. However, we believe this specific limitation can be addressed by a different approach to the problem, like splitting pipelines in a way that shared nodes are stored in a dedicated sub-pipeline and so on. We postpone addressing this problem when it arises, as we don't consider it blocking and workarounds can be found. + +# Adoption strategy + +Old and new `Pipeline` and nodes are going to be fully incompatible. We must provide a migration script that can convert their existing pipeline YAMLs into the new ones. + +This proposal is best thought as part of the design of Haystack 2.0. + +## Rollout process + +These changes are going to be release with Haystack 1.x in a hidden internal package called `haystack.v2.pipelines`, and won't be promoted straight away. + +We will progressively add nodes to this `haystack.v2` package and build a folder structure under it (`haystack.v2.nodes`, `haystack.v2.stores`, ...) version after version, until we believe the content of the package is usable. Documentation will be built in parallel and we will progressively start pushing users towards the 2.0 API. +Power users like dC and other Haystack experts will be able to test out these changes from the start and provide feedback while still in Haystack 1.x. + +Once we're confident that the v2 version covers all of Haystack v1.x usecases, Haystack 2.0 will be released and the packages are going to be switched: the content of `haystack` will be moved into `haystack.v1` and deprecated, and the content of `haystack.v2` will me moved under `haystack`. A few 2.x versions later, `haystack.v1` will then be dropped. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4370-documentstores-and-retrievers.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4370-documentstores-and-retrievers.md new file mode 100644 index 0000000000000000000000000000000000000000..bf2b985bc28b5c1cfdd5bbefece8475ed1e8697b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4370-documentstores-and-retrievers.md @@ -0,0 +1,239 @@ +- Title: `DocumentStores` and `Retrievers` +- Decision driver: @ZanSara +- Start Date: 2023-03-09 +- Proposal PR: 4370 +- Github Issue or Discussion: (only if available, link the original request for this change) + +# Summary + +Haystack's Document Stores are a very central component in Haystack and, as the name suggest, they were initially designed around the concept of `Document`. + +As the framework grew, so did the number of Document Stores and their API, until the point where keeping them aligned aligned on the same feature set started to become a serious challenge. + +In this proposal we outline a reviewed design of the same concept. + +Note: these stores are designed to work **only** alongside Haystack 2.0 Pipelines (see https://github.com/deepset-ai/haystack/pull/4284) + +# Motivation + +Current `DocumentStore` face several issues mostly due to their organic growth. Some of them are: + +- `DocumentStore`s perform the bulk of retrieval, but they need to be tightly coupled to a `Retriever` object to work. We believe this coupling can be broken by a clear API boundary between `DocumentStores`, `Retriever`s and `Embedder`s. In this PR we focus on decoupling them. + +- `DocumentStore`s tend to bring in complex dependencies, so less used stores should be easy to decouple into external packages at need. + +# Basic example + +Stores will have to follow a contract rather than subclassing a base class. We define a contract for `DocumentStore` that defines a very simple CRUD API for Documents. Then, we provide one implementation for each underlying technology (`MemoryDocumentStore`, `ElasticsearchDocumentStore`, `FaissDocumentStore`) that respects such contract. + +Once stores are defined, we will create one `Retriever` for each `DocumentStore`. Such retrievers are going to be highly specialized nodes that expect one specific document store and can handle all its specific requirements without being bound to a generic interface. + +For example, this is how embedding-based retrieval would look like: + +```python +from haystack import Pipeline +from haystack.nodes import ( + TxtConverter, + PreProcessor, + DocumentWriter, + DocumentEmbedder, + StringEmbedder, + MemoryRetriever, + Reader, +) +from haystack.document_stores import MemoryDocumentStore + +docstore = MemoryDocumentStore() + +indexing_pipe = Pipeline() +indexing_pipe.add_store("document_store", docstore) +indexing_pipe.add_node("txt_converter", TxtConverter()) +indexing_pipe.add_node("preprocessor", PreProcessor()) +indexing_pipe.add_node("embedder", DocumentEmbedder(model_name="deepset/model-name")) +indexing_pipe.add_node("writer", DocumentWriter(store="document_store")) +indexing_pipe.connect("txt_converter", "preprocessor") +indexing_pipe.connect("preprocessor", "embedder") +indexing_pipe.connect("embedder", "writer") + +indexing_pipe.run(...) + +query_pipe = Pipeline() +query_pipe.add_store("document_store", docstore) +query_pipe.add_node("embedder", StringEmbedder(model_name="deepset/model-name")) +query_pipe.add_node("retriever", MemoryRetriever(store="document_store", retrieval_method="embedding")) +query_pipe.add_node("reader", Reader(model_name="deepset/model-name")) +query_pipe.connect("embedder", "retriever") +query_pipe.connect("retriever", "reader") + +results = query_pipe.run(...) +``` + +Note a few key differences with the existing Haystack process: + +- During indexing we do not use any `Retriever`, but rather a `DocumentEmbedder`. This class accepts a model name and simply adds embeddings to the `Document`s it receives. + +- We used an explicit `DocumentWriter` node instead of adding the `DocumentStore` at the end of the pipeline. That node will be generic for any document store, because the `DocumentStore` contract declares a `write_documents` method (see "Detailed Design"). + +- During query, the first step is not a `Retriever` anymore, but a `StringEmbedder`. Such node will convert the query into its embedding representation and forward it over to a `Retriever` that expects it. In this case, an imaginary `MemoryRetriever` can be configured to expect an embedding by setting the `retrieval_method` flag to `embedding`. + + +# Detailed design + +## `DocumentStore` contract + +Here is a summary of the basic contract that all `DocumentStore`s are expected to follow. + +```python +class MyDocumentStore: + + def count_documents(self, **kwargs) -> int: + ... + + def filter_documents(self, filters: Dict[str, Any], **kwargs) -> List[Document]: + ... + + def write_documents(self, documents: List[Document], **kwargs) -> None: + ... + + def delete_documents(self, ids: List[str], **kwargs) -> None: + ... +``` + +The contract is quite narrow to encourage the use of specialized nodes. `DocumentStore`s' primary focus should be storing documents: the fact that most vector stores also support retrieval should be outside of this abstraction and made available through methods that do not belong to the contract. This allows `Retriever`s to carry out their tasks while avoiding clutter on `DocumentStore`s that do not support some features. + +Note also how the concept of `index` is not present anymore, as it it mostly ES-specific. + +For example, a `MemoryDocumentStore` could offer the following API: + +```python +class MemoryDocumentStore: + + def filter_documents(self, filters: Dict[str, Any], **kwargs) -> List[Document]: + ... + + def write_documents(self, documents: List[Document], **kwargs) -> None: + ... + + def delete_documents(self, ids: List[str], **kwargs) -> None: + ... + + def bm25_retrieval( + self, + queries: List[str], # Note: takes strings! + filters: Optional[Dict[str, Any]] = None, + top_k: int = 10 + ) -> List[List[Document]]: + ... + + def vector_similarity_retrieval( + self, + queries: List[np.array], # Note: takes embeddings! + filters: Optional[Dict[str, Any]] = None, + top_k: int = 10 + ) -> List[List[Document]]: + ... + + def knn_retrieval( + self, + queries: List[np.array], # Note: takes embeddings! + filters: Optional[Dict[str, Any]] = None, + top_k: int = 10 + ) -> List[List[Document]]: + ... +``` + +In this way, a `DocumentWriter` could easily use the `write_documents` method defined in the contract on all document stores, while `MemoryRetriever` can leverage the fact that it only supports `MemoryDocumentStore`, so it can assume all its custom methods like `bm25_retrieval`, `vector_similarity_retrieval`, etc... are present. + +Here is, for comparison, an example implementation of a `DocumentWriter`, a document-store agnostic node. + +```python +@node +class DocumentWriter: + + def __init__(self, inputs=['documents'], stores=["documents"]): + self.store_names = stores + self.inputs = inputs + self.outputs = [] + self.init_parameters = {"inputs": inputs, "stores": stores} + + def run( + self, + name: str, + data: List[Tuple[str, Any]], + parameters: Dict[str, Dict[str, Any]] + ) -> Dict[str, Any]: + writer_parameters = parameters.get(name, {}) + stores = writer_parameters.pop("stores", {}) + + all_documents = [] + for _, documents in data: + all_documents += documents + + for store_name in self.store_names: + stores[store_name].write_documents(documents=all_documents, **writer_parameters) + + return ({}, parameters) +``` +This class does not check which document store it is using, because it can safely assume they are going to have a `write_documents` method. + +Here instead we can see an example implementation of a `MemoryRetriever`, a document-store aware node. + +```python +@node +class MemoryRetriever: + + def __init__(self, inputs=['query'], output="documents", stores=["documents"]): + self.store_names = stores + self.inputs = inputs + self.outputs = [output] + self.init_parameters = {"inputs": inputs, "output": output "stores": stores} + + def run( + self, + name: str, + data: List[Tuple[str, Any]], + parameters: Dict[str, Dict[str, Any]] + ) -> Dict[str, Any]: + + retriever_parameters = parameters.get(name, {}) + stores = retriever_parameters.pop("stores", {}) + retrieval_method = retriever_parameters.pop("retrieval_method", "bm25") + + for store_name in self.store_names: + if not isinstance(stores[store_name], MemoryStore): + raise ValueError("MemoryRetriever only works with MemoryDocumentStore.") + + if retrieval_method == "bm25": + documents = stores[store_name].bm25_retrieval(queries=queries, **retriever_parameters) + elif retrieval_method == "embedding": + documents = stores[store_name].vector_similarity_retrieval(queries=queries, **retriever_parameters) + ... + + return ({self.outputs[0]: documents}, parameters) +``` + +Note how `MemoryRetriever` is making use of methods that are not specified in the contract and therefore has to check that the document store it has been connected to is a proper one. + +# Drawbacks + +### Migration effort + +We will need to migrate all `DocumentStore`s and heavily cut their API. Although it is going to be a massive undertaking, this process will allow us to drop less used `DocumentStore` backends and focus on the most important ones. It will also highly reduce the code we have to maintain. + +We will also need to re-implement the ehtire Retrieval stack. We believe a lot of code could be reused, but we will focus on leveraging each document store facilities a lot more, and that will require almost complete rewriters. The upside is that the resulting code should be several times shorter, so the maintenance burden should be limited. + +# Alternatives + +We could force support for the old Docstores into the new Pipelines, but I see no value in such effort given that with the same investment we can get a massively smaller codebase. + +# Adoption strategy + +This proposal is part of the Haystack 2.0 rollout strategy. See https://github.com/deepset-ai/haystack/pull/4284. + +# How we teach this + +Documentation is going to be crucial, as much as tutorials and demos. We plan to start working on those as soon as basic nodes (one reader and one retriever) are added to Haystack v2 and `MemoryDocumentStore` receives its first implementation. + +# Open questions + +- We should enable validation of `DocumentStore`s for nodes that are document-store aware. It could be done by an additional `validation` method with relative ease, but it's currently not mentioned in the node/pipeline contract. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5289-recentness-ranker.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5289-recentness-ranker.md new file mode 100644 index 0000000000000000000000000000000000000000..b98b1224dd3a3b3996f6f655c3a737a7e4bfa079 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5289-recentness-ranker.md @@ -0,0 +1,185 @@ +- Title: Addition of a RecentnessRanker node +- Decision driver: @elundaeva +- Start Date: 2023-07-05 +- Proposal PR: https://github.com/deepset-ai/haystack/pull/5289 +- Github Issue or Discussion: some links available in the "Detailed design" section below + +# Summary + +This ranker allows to have retrieved documents sorted not only by relevance (default) but also with recency factored in. + +# Basic example + +The RecentnessRanker would be instantiated as follows: + + ``` python + + ranker = RecentnessRanker( + date_identifier="date", + weight="0.5", + top_k=3, + method="reciprocal_rank_fusion", + ) + ``` + +And here is an example of how the node would work in the context of a generative QA pipeline: + + ``` yaml + +version: '1.18.0' +name: 'Example pipeline' + +components: +- name: DocumentStore + type: DeepsetCloudDocumentStore +- name: EmbeddingRetriever + type: EmbeddingRetriever + params: + document_store: DocumentStore + embedding_model: [embedding model here] + model_format: sentence_transformers + top_k: 30 +- name: BM25Retriever + type: BM25Retriever + params: + document_store: DocumentStore + top_k: 30 +- name: JoinDocuments + type: JoinDocuments + params: + top_k_join: 30 + join_mode: reciprocal_rank_fusion +- name: Ranker + type: SentenceTransformersRanker + params: + model_name_or_path: [cross-encoder model here] + top_k: 15 +- name: RecentnessRanker + type: RecentnessRanker + params: + date_identifier: release_date + top_k: 3 + method: score +- name: qa_template + type: PromptTemplate + params: + output_parser: + type: AnswerParser + prompt: "prompt text here" +- name: PromptNode + type: PromptNode + params: + default_prompt_template: qa_template + max_length: 300 + model_kwargs: + temperature: 0 + model_name_or_path: gpt-3.5-turbo +- name: FileTypeClassifier + type: FileTypeClassifier +- name: TextConverter + type: TextConverter +- name: PDFConverter + type: PDFToTextConverter +- name: Preprocessor + params: + language: en + split_by: word + split_length: 200 + split_overlap: 10 + split_respect_sentence_boundary: true + type: PreProcessor + +pipelines: +- name: query + nodes: + - name: EmbeddingRetriever + inputs: [Query] + - name: BM25Retriever + inputs: [Query] + - name: JoinDocuments + inputs: [EmbeddingRetriever, BM25Retriever] + - name: Ranker + inputs: [JoinDocuments] + - name: RecentnessRanker + inputs: [Ranker] + - name: PromptNode + inputs: [RecentnessRanker] + +- name: indexing + nodes: + - inputs: + - File + name: FileTypeClassifier + - inputs: + - FileTypeClassifier.output_1 + name: TextConverter + - inputs: + - FileTypeClassifier.output_2 + name: PDFConverter + - inputs: + - TextConverter + - PDFConverter + name: Preprocessor + - inputs: + - Preprocessor + name: EmbeddingRetriever + - inputs: + - EmbeddingRetriever + name: DocumentStore + + ``` + +# Motivation + +Initially this ranker was implemented by Timo for a customer case where the date of the document mattered for retrieval. The reason we would like to add it to Haystack is because we see wider use for this node in future customer and community cases. One example where document recency matters is in a QA solution based on technical documentation with release notes of a software product - the older release notes should naturally have less priority in the responses than the most recent ones. And another example is news content - news articles retrieval can definitely benefit from recency being factored into the relevance calculation. + +# Detailed design + +You can see the code for this proposal here: https://github.com/deepset-ai/haystack/pull/5301/files. + +As a general description, the ranker has the following parameters (date_identifier and method are required, the rest are optional): +- date_identifier (string pointing to the date field in the metadata) +- weight (the options are: + - 0.5 default, relevance and recency will have the same impact in the calculation; + - 0 only relevance will be considered for the calculation, so the RecentnessRanker is effectively disabled; + - 1 only recency will be considered for the calculation) +- top_k (number of documents to return, works the same way as top-k in other rankers as well as retrievers) +- method (the options are: + - "reciprocal_rank_fusion" which does not require any relevance score from the previous node; + - "score" requires a 0-1 relevance score provided from the previous node in the pipeline. + More information on method compatibility with different retrievers is in the Drawbacks section below) + +The RecentnessRanker works by: +1. Adjusting the relevance score based on the chosen weight. + For the "reciprocal_rank_fusion" the calculation is rrf * (1 - weight). The rrf is calculated as 1 / (k + rank) where k=61 (see reasoning below). + And the "score" method performs the calculation as relevance score * (1 - weight). +2. Adding to the relevance score the recentness score by: + For the "reciprocal_rank_fusion" - performing the rrf * weight calculation on the documents dictionary sorted by date where rrf is 1 / (k + rank), k=61. + For the "score" method - performing the recentness score * weight calculation where recentness score is (amount of documents - rank) / amount of documents. +3. Returning top-k documents in the documents dictionary sorted by final score (relevance score + recentness score both adjusted by weight). + +k is set to 61 in reciprocal rank fusion based on a University of Waterloo paper (co-authored with Google) called "Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods" [https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf] where k=60 was suggested, and 1 was added as python lists are 0-based and the paper used 1-based ranking. + +# Drawbacks + +Since this is a relatively small change without any effect on existing nodes, I do not see major reasons not to add this ranker. The only important limitation to using this node is the need to have a metadata field with document date already present. + +For the "score" method, you would also need to double-check that the previous node outputs a score within [0,1] range (e.g. CohereRanker, SentenceTransformersRanker, EmbeddingRetriever). With the "reciprocal_rank_fusion" method, you do not need to have the relevance score pre-calculated, so using this method allows to combine RecentnessRanker with other retrieval nodes, like BM25 retriever. + +# Alternatives + +Without adding this feature it will not be possible to handle customer and community cases where recency of documents matters for the response, see examples in the Motivation section. + +# Adoption strategy + +This is not a breaking change and there does not seem to be any need for a migration script. Existing Haystack users can just start using this node on as-needed basis in combination with existing retrieval options (sparse/dense/hybrid). + +# How we teach this + +A small change like this might not require creating a whole new tutorial (although it is of course up to you), although it can be interesting to discuss this ranker with example usage in blog post format like we have for metadata filtering (https://www.deepset.ai/blog/metadata-filtering-in-haystack). + +As for documentation needs, it would be good to add some info on how to use this recentness ranker - it can be added to the same page where the other existing rankers are explained. If you need help writing the documentation and/or the blog post/tutorial, please do not hesitate to reach out to me. + +# Unresolved questions + +Since it has already been implemented and is functional, there are not many known unresolved design questions. We just need to make sure that if/when the custom node is deprecated and we transition to using this node in Haystack, there are no disruptions to production pipelines that have been using this node and they get adjusted accordingly. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5390-embedders.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5390-embedders.md new file mode 100644 index 0000000000000000000000000000000000000000..5314570f343d5402ce3ec3063240013662a8e546 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5390-embedders.md @@ -0,0 +1,249 @@ +- Title: Embedders +- Decision driver: @anakin87 +- Start Date: 2023-07-19 +- Proposal PR: https://github.com/deepset-ai/haystack/pull/5390 + +# Summary + +As decided in the previous proposals ([Embedding Retriever](3558-embedding_retriever.md) and [DocumentStores and Retrievers](4370-documentstores-and-retrievers.md)), in Haystack V2 we want to introduce a new component: the Embedder. + +**Separation of concerns** +- DocumentStores: store the Documents, their metadata and representations (vectors); they offer a CRUD API. +- Retrievers: retrieve Documents from the DocumentStores; they are specific and aware of the used Store (e.g., MemoryRetriever for the MemoryDocumentStore). They will be commonly used in query pipelines (not in indexing pipelines). +- **Embedders**: encode a list of data points (strings, images, etc.) into a list of vectors (i.e., the embeddings) using a model. They are used both in indexing pipelines (to encode the Documents) and query pipelines (to encode the query). + +*In the current implementation, the Embedder is part of Retriever, which is unintuitive and comes with several disadvantages (explained in the previous proposals).* + +**This proposal aims to define the Embedder design.** + +# Basic example + +*This code snippet is merely an example and may not be completely up-to-date.* + + +```python +from haystack import Pipeline +from haystack.components import ( + TxtConverter, + PreProcessor, + DocumentWriter, + OpenAITextEmbedder, + OpenAIDocumentEmbedder, + MemoryRetriever, + Reader, +) +from haystack.document_stores import MemoryDocumentStore +docstore = MemoryDocumentStore() + +indexing_pipe = Pipeline() +indexing_pipe.add_store("document_store", docstore) +indexing_pipe.add_node("txt_converter", TxtConverter()) +indexing_pipe.add_node("preprocessor", PreProcessor()) +indexing_pipe.add_node("embedder", OpenAIDocumentEmbedder(model_name="text-embedding-ada-002")) +indexing_pipe.add_node("writer", DocumentWriter(store="document_store")) +indexing_pipe.connect("txt_converter", "preprocessor") +indexing_pipe.connect("preprocessor", "embedder") +indexing_pipe.connect("embedder", "writer") + +indexing_pipe.run(...) + +query_pipe = Pipeline() +query_pipe.add_store("document_store", docstore) +query_pipe.add_node("embedder", OpenAITextEmbedder(model_name="text-embedding-ada-002")) +query_pipe.add_node("retriever", MemoryRetriever(store="document_store", retrieval_method="embedding")) +query_pipe.add_node("reader", Reader(model_name="deepset/model-name")) +query_pipe.connect("embedder", "retriever") +query_pipe.connect("retriever", "reader") + +results = query_pipe.run(...) +``` + +- The `OpenAITextEmbedder` uses OpenAI models to convert a list of strings into a list of vectors. It is used in the query pipeline to embed the query. +- The `OpenAIDocumentEmbedder` uses OpenAI models to enrich a list of Documents with the corresponding vectors (stored in the `embedding` field). It is used in the indexing pipeline to embed the Documents. +- The Retriever is no longer needed in the indexing pipeline. + +# Motivation + +The motivations behind this change were already provided in the previous proposals ([Embedding Retriever](3558-embedding_retriever.md) and [DocumentStores and Retrievers](4370-document_stores_and_retrievers.md)). Here is a summary: +- Retrievers shouldn't be responsible for embedding Documents. +- Currently, Retrievers have many parameters just to support and configure different underlying Encoders(≈Embedders). +- Adding support for new embedding providers or strategies is difficult. It requires changing the Retriever code. + +# Detailed design + +## Handle queries and Documents +This is the most critical aspect of the design. + +- When embedding queries, the Embedder component receives a list of strings in input that are transformed into a list of vectors returned as output. +- When embedding documents, the Embedder component receives a list of `Document` objects in input; for each item in the list, the corresponding vectors are computed and stored in the `embedding` field of the item itself. The list is then returned as the component output. +- When working with documents, there's the possibility to compute embeddings also for document's metadata. In this case, the Embedder will be responsible for performing any text-manipulation work needed in preparation of the actual embedding process. + +**Below, I will focus on the public API. The internal implementation is discussed in [Implementation details](#implementation-details).** + +```python +@component +class HFTextEmbedder: + ... + + @component.output_types(result=List[np.ndarray]) + def run(self, strings: List[str]): + ... + return {"result": list_of_computed_embeddings} + + +@component +class HFDocumentEmbedder: + ... + + @component.output_types(result=List[Document]) + def run(self, documents: List[Document]): + ... + return {"result": list_of_documents_with_embeddings} +``` + +## Different providers/strategies + +- We can define different embedder components depending on the models or services providing the actual embeddings: `OpenAIEmbedder`, `CohereEmbedder`, `HuggingFaceEmbedder`, `SentenceTransformersEmbedder`, etc. +- Additionally, we could define different classes depending on the embedding strategy if necessary. +While this is not a prominent use case, there are scenarios where [new strategies](https://github.com/deepset-ai/haystack/issues/5242) are introduced, requiring different libraries (`InstructorEmbedder`) or involving a different string preparation (`E5Embedder`). Supporting these scenarios with minimal effort would be nice. + +## Different models in the same embedding/retrieval task + +As you can observe from the [current implementation](https://github.com/deepset-ai/haystack/blob/main/haystack/nodes/retriever/dense.py), some embedding/retrieval tasks require the usage of different models. + +This is not the most popular approach today, compared to what we call Embedding Retrieval (based on a single model). But it still has some relevant applications. + +Some examples: +- In Dense Passage Retrieval, you need a model to encode queries and another model to encode Documents +- in the TableTextRetriever, we use 3 different models: one for queries, one for textual passages and one for tables +- in Multimodal Retrieval, we can specify different models to encode queries and Documents + +Since the Embedder will not be included in the Retriever, it makes sense to have different Embedders, each one using a single model. + +```python +dpr_query_embedder = SentenceTransformersTextEmbedder(model_name="facebook/dpr-question_encoder-single-nq-base") +dpr_doc_embedder = SentenceTransformersDocumentEmbedder(model_name="facebook/dpr-ctx_encoder-single-nq-base") +``` + +## Implementation details + +*You can skip this section if you are primarily interested in user experience.* + +There have been much discussion on how to effectively implement this proposal. +The most important aspects to consider: +- we want different Embedders for queries and Documents as they require a different treatment +- if the same model is internally used for different Embedders, we want to reuse the same instance in order to save memory + +On top of the embedder components we already discussed, we introduce one additional abstraction: +an `EmbeddingBackend`, which is NOT a component, responsible for performing the actual embedding computation, implemented as a singleton class in order to reuse instances. It will live in a different package and will be hidden from the public API. +```python +@singleton # implementation is out of scope +class HFEmbeddingBackend: + """ + NOT A COMPONENT! + """ + def __init__(self, model_name: str, ... init params ...): + """ + init takes the minimum parameters needed at init time, not + the params needed at inference, so they're easier to reuse. + """ + self.model = ... + + def embed(self, data: str, ... inference params ... ) -> np.ndarray: + # compute embedding + return embedding + + +class OpenAIEmbeddingBackend: + ... same as above ... +``` + +Implemented as singletons, when instantiating an EmbeddingBackend class, if another identical one exists, the existing one will be returned without allocating additional resources for a new one. This makes model reusability transparent, saving lots of memory without any user intervention. + +This is how an EmbeddingBackend would be used by a text embedder component: +**Part of the public API**. +```python +@component +class HFTextEmbedder: + + def __init__(self, model_name: str, ... init params ...): + self.model_name = model_name + self.model_params = ... params ... + + def warm_up(self): + self.embedding_backend = HFEmbeddingBackend(self.model_name, **self.model_params) + + @component.output_types(result=List[np.ndarray]) + def run(self, strings: List[str]): + return {"result": self.embedding_backend.embed(data)} +``` + +Another example, using an embedder component expecting Documents: +**Part of the public API**. + +```python +@component +class HFDocumentEmbedder: + + def __init__(self, model_name: str, ... init params ...): + self.model_name = model_name + self.model_params = ... params ... + + def warm_up(self): + self.embedding_backend = HFEmbeddingBackend(self.model_name, **self.model_params) + + @component.output_types(result=List[Document]) + def run(self, documents: List[Document]): + text_strings = [document.content for document in data] + embeddings = self.embedding_backend.embed(text_strings) + documents_with_embeddings = [Document.from_dict(**doc.to_dict, "embedding": emb) for doc, emb in zip(documents, embeddings)] + return {"result": documents_with_embeddings} +``` + +# Drawbacks + +## Migration +The drawbacks of separating Retrievers and Embedders were already discussed in [this proposal](https://github.com/deepset-ai/haystack/blob/main/proposals/text/4370-documentstores-and-retrievers.md) and mainly consist of **migration effort**. + +For example, if a user has indexed documents in the store and wants to update the embeddings using a different model instead, with the current Haystack implementation the user would run `document_store.update_embeddings(retriever)`. + +With the new Embedder design, I can imagine something similar (based on the MemoryDocumentStore v2 implementation): +```python +# get all the documents +docs = memory_document_store.filter_documents() + +# compute the embedding with the new model +new_embedder = HFDocumentEmbedder(model_name="new-model") +docs_with_embeddings = new_embedder.run(documents=docs) + +# overwrite the documents +memory_document_store.write_documents(documents=docs_with_embeddings, policy=DuplicatePolicy.OVERWRITE) +``` +## Other aspects +Regarding the design proposed in this document, there are some potential drawbacks to consider: + - Proliferation of classes (though they will be small and easy to maintain). + - Users need to know which models are appropriate for which task (e.g. embedding queries rather than embedding documents, see [Different models in the same embedding/retrieval task](#different-models-in-the-same-embeddingretrieval-task)). On the other hand, this approach is more explicit and will help making users aware of problems and tradeoffs related to the topic. + +# Alternatives + +Several alternatives to this design were considered. The main challenge was handling the differences between queries and Documents. +Some ideas: +- Have a single Embedder component for text (HFTextEmbedder instead of HFEmbeddingBackend, HFTextEmbedder and HFDocumentEmbedder) and adapt Documents before and after that, using other Components. --> Many components. +- Make Embedders only work on Documents and represent the query as a Document. --> Unintuitive and require changes in the Retriever. +- Create another primitive like Data (content + embedding) and use it for both queries and Documents. --> More conversion components like DataToDocument. +- Have the DocumentEmbedder take a TextEmbedder as an input parameter. --> Fewer classes but serialization issues. + +# Adoption strategy + +This change will constitute a part of Haystack v2. + +# How we teach this + +Documentation and tutorials will be of fundamental importance. + +# Unresolved questions + +- Migration and refactoring of existing Encoders hidden in Retrievers. +I prepared a table. Should it be shared here? +- The migration and refactoring of TableTextRetriever require input and ownership from people involved in TableQA. +- How to approach MultiModal Embedding? How many classes? Take into consideration that a query could also be an Image or a Table. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5540-llm-support-2.0.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5540-llm-support-2.0.md new file mode 100644 index 0000000000000000000000000000000000000000..f40dc604878ab32046ea20a265b7d0b1b9349de5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5540-llm-support-2.0.md @@ -0,0 +1,253 @@ +- Title: LLM SUpport in Haystack 2.0 +- Decision driver: @ZanSara +- Start Date: 2023-08-10 +- Proposal PR: #5540 +- Github Issue or Discussion: https://github.com/deepset-ai/haystack/issues/5330 + +# Summary + +In this proposal we outline our migration strategy of the `PromptNode` stack of functionality into Haystack 2.0 components. + +This proposal, however, does not discuss Agents or Agent-related features and functionality, which are going to be addressed into a separate proposal. + +# Motivation + +This proposal is part of a larger effort of migrating existing Haystack 1.x components into their 2.0 counterpart. + +# Basic example + +In Haystack 2.0 components should be smaller than their 1.x counterpart. Therefore, we plan to split the functionality of `PromptNode` into a few smaller components. + +As this proposal concerns LLM support, not specifically Agents, the main usecase in question is RAG (Retrieval-Augmented Generation). + +## Example: RAG Pipeline + +Using the components discussed in the Detailed Design section, a Haystack 2.0 RAG pipeline may look like this: + +```mermaid +graph TD; + +IN{IN} -- "questions (List[str])" --> Retriever +IN{IN} -- "questions (List[str])" --> PromptBuilder +Retriever -- "documents (List[List[Doc]])" --> PromptBuilder +PromptBuilder -- "prompts (List[str])" --> GPT4Generator +GPT4Generator -- "replies (List[List[str]])" --> RepliesToAnswersConverter +RepliesToAnswersConverter -- "answers (List[List[Answer]])" --> OUT{OUT} +``` + +While the code for such pipeline may look like: + +```python +from haystack.preview.components import MemoryRetriever, PromptBuilder, ChatGPTGenerator, RepliesToAnswersConverter +from haystack.preview.document_stores import MemoryDocumentStore +from haystack.preview.pipeline import Pipeline + +pipe = Pipeline() +pipe.add_store("store", MemoryDocumentStore()) +pipe.add_component("retriever", MemoryRetriever(), store="store") +pipe.add_component("prompt_builder", PromptBuilder("deepset/question-answering")) +pipe.add_component("llm", GPT4Generator(api_key="...")) +pipe.add_component("replies_converter", RepliesToAnswersConverter()) + +pipe.connect("retriever", "prompt_builder") +pipe.connect("prompt_builder", "llm") +pipe.connect("llm", "replies_converter") + +questions = ["Why?", "Why not?"] +results = pipe.run({ + "retriever": {"queries": questions}, + "prompt_builder": {"questions": questions}, +}) + +assert results == { + "replies_converter": { + "answers": [[Answer("Because of this.")], [Answer("Because of that.")]] + } +} +``` + +# Detailed design + +Haystack’s `PromptNode` is a very complex component that includes under its name several functionalities: loading prompt templates through the `PromptTemplate` class, rendering such prompt template with the variables from the invocation context, choosing which LLM backend to use, sending the prompt to the LLM using the correct invocation layer, interpreting the results, parsing them into objects, and putting them back in the pipeline in a way other components can understand. + +in Haystack 2.0 we unpack these functionalities into a few separate components, to clarify what is happening, how it works, and provide additional flexibility. + +The main functionalities we identified are the following: + +1. Fetching the prompt from different sources +2. Rendering the prompt using variables +3. Invoke the LLM +4. Parse the output +5. History/Memory management + +We leave the discussion about History/Memory to a separate proposal, as it concerns mostly Agents, and focus on the other points. + +## LLM invocation + +In Haystack 1.x, `PromptNode` uses `InvocationLayer` to query different LLMs under a unified API. In that design, users do not need to know which invocation layer is used for the model they select, as `PromptNode` takes responsibility of selecting it. + +Such invocation layers can be ported to 2.0 as standalone components. In this way we will have one component for each LLM backed that we support. + +Each component should be named after the class of models it supports, plus a `Generator` suffix. For example we should have `GPT4Generator`, `HuggingFaceLocalGenerator`, `CohereGenerator`, etc. + +Note that having separate components for each LLM makes easy to deprecate them when we realize they are dropping out of favor or become severely outdated. It also makes very easy for external contributors to make their own external components to support rarer LLMs, without having to add them to Haystack’s core. + +All these LLM clients will have a near-identical I/O: + +```python +@component +class ChatGPTGenerator: + + @component.output_types(replies=List[List[str]]) + def run(self, prompts: List[str], ... chatgpt specific params...): + ... + return {'replies': [...]} +``` + +Note how the component takes a list of prompts and LLM parameters only, but no variables nor templates, and returns only strings. This is because input rendering and output parsing are delegated to separate components, which description follows. + +Note: whether LLM components accept multiple prompts or a single one depends only on whether we want the LLM to support batching of prompts. Therefore it's an implementation decision that will be evaluated once we know the internals of the component. We strive to keep the interfaces as similar as possible to ease switching the various LLMs, but we won't force identical interfaces over them where it doesn't make sense with respect to their internal implementation. + +### Chat API + +Most LLMs support Chat interfaces, where they expect not a single prompt, but a list of messages in a format such as: + +``` +[ + {"role": "system", "content": "\nYou are a helpful assistant speaking like a pirate. argh!"}, + {"role": "user", "content": "What is the sun?"}, +] +``` + +In this proposal we're not taking this way of querying the LLMs into account, we will just focus on simple completion. We're going to address the Chat completion topic in a dedicated proposal. + +### Returning metadata + +In the example above we made the LLM return only a list of replies, as strings. However, in order to be able to parse the output into meaningful objects (see “Output parsing”) we may need additional metadata from these clients. + +1. Do we already have any such situation? +2. Can we foresee any other? + +If the answer to any of the above is yes, a simple, maybe temporary solution would be to add a second output, called for example `'replies_meta'` . Any component that need such meta to parse the output would then request this second output along with the first and zip the two lists together to reconstruct the original output of the LLM. + +### Returning streams + +Most LLMs like ChatGPT have the option to stream the tokens as their generated. As we're already supporting this use case in version 1.x we want to support it in 2.x too. + +Currently we're supporting it by accepting a callback during `PromptNode` initialization that will be called every time a new chunk of the streamed response is received. + +In version 2.x we're going to do the same and have all generator components accept an optional callback during initialization. + +### How many clients we will have? + +Basing on the list of current invocation layers in Haystack 1.x, the list might look like: + +1. `ClaudeGenerator` +2. `ChatGPTGenerator`, supporting GPT4 as well + - it may have an alias `GPT4Generator` to help users +3. `CohereGenerator` +4. `HuggingFaceInferenceGenerator` +5. `HuggingFaceLocalGenerator` +6. `GPT3Generator` +7. `SagemakerGenerator` + +Plus one more for any other inference hosting/library that may appear in the future. + +## Prompt Builder + +In Haystack 1.x, prompts fetching and rendering is carried out by `PromptTemplate`. In 2.0, we rather make a separate `PromptBuilder` component to handle this process. + +The goal of `PromptBuilder` is to transform prompt templates, which are strings with variables (for example f-strings, Jinja-like templates), and fill up those variables with values that come from other components in the pipeline or from the pipeline inputs. The output of tis component is one (or more) prompts, where prompts means strings that the LLM can directly use. + +`PromptBuilder` is not tokenizer aware: the prompt will be checked for length by the LLM component before inference. If the need arise, we may later extend the component. + +Draft I/O for `PromptBuilder`: + +```python +@component +class PromptBuilder: + + def __init__(self, template: Union[str, Path]): + self.template = # Download the template + template_variables = # extracts the variables from the template text + component.set_input_parameters(**{var: Any for var in template_variables}) + + @component.output_types(prompts=List[str]) + def run(self, **kwargs): + # Render the template using the variables + return {"prompts": prompts} +``` + +### Template variables + +Due to the dynamic nature of prompt templates, the `PromptBuilder.run()` method takes `kwargs`, which contains all the variables that will be filled in the template. However, for this component to work with Canals, we need to know in advance which values this dict will contain: therefore, we need the users to specify in the `__init__` of the component the template to use. + +Such template names **cannot be changed at runtime**. + +The design above derives from one Canals limitation: component’s sockets need to be all known the latest at `__init__` time, in order for the connections to be made and validated. Therefore, we need to know all the prompt variables before building the pipelines, because the prompt variables are inputs of the `run()` method. + +However, earlier iterations of Canals did support so-called “true variadic” components: components that do not need to know what they will be connected to, and build the input sockets at need. Such components of course lack input validation, but enable usecases like the above. + +If we decide that Canals should support again such components, we would be able to rewrite `PromptBuilder` to take a prompt as its input parameter and just accept any other incoming input, on the assumption that users knows that they’re doing. + +For example: + +```python +@component +class PromptBuilder: + + @variadic_input + @component.output_types(prompts=List[str]) + def run(self, template: Union[str, Path], **kwargs): + # ... loads the template ... + # ... render the prompts ... + return {"prompts": prompts} +``` + +### Why a separate `PromptBuilder` component at all? + +`PromptNode` used to take the prompt template and the variables to render it directly, and then forward the result to the LLM. + +The key advantage of `PromptBuilder` is ability to use any tool from the ever growing list of LLM prompting template libs. If someone has invested a lot in guidance and considers using a framework like Haystack or LangChain this will be one of the biggest selling points: an ability to use `PromptBuilder` for a specific prompt tooling lib. + +On top of that, it also allows users to skip the template rendering step altogether and send prompts directly to the LLM, which may be beneficial in some context (for example, if users just want to chat with the LLM without RAG). + +The drawback is that `PromptBuilder` is an additional component, so we must evaluate if this additional flexibility is worth the additional complexity. However, at this point in time we are convinced that the benefits are worth the cost. + +## Output parsing + +LLMs clients output strings, but many components expect other object types, and LLMs may produce output in a parsable format that can be directly converted into objects. Output parsers transform these strings into objects of the user’s choosing. + +In Haystack 1.x, this task was assigned to the subclasses of `BaseOutputParser`. In 2.0 we’re going to have a very similar situation, with the difference that such classes are components. + +The most straightforward component in this category is `RepliesToAnswersConverter`. It takes the string replies of an LLM and produce `Answer` objects. One additional output parser could be `RepliesToAnswersWithReferencesConverter`, which also connects answers to the documents used to produce them. As the need for additional output parsers arises, we will progressively add more. + +Draft I/O for `RepliesToAnswersConverter` (note: this may end up being almost the entire component’s implementation): + +```python +@component +class RepliesToAnswersConverter: + + @component.output_types(answers=List[List[Answer]]) + def run(self, replies: List[List[str]]): + return {"answers": Answer(answer=answer) for answers in replies for answer in answers} +``` + +# Drawbacks + +Possible drawbacks of this design: + +1. Users now need to use three components instead of a single, large one. +2. We lose the capability to change the prompt for the LLM at runtime. + +# Alternatives + +1. Porting the existing `PromptNode` to Haystack 2.0: would be a massive effort and make the new version inherit some design decision that, with time, proved unnecessary and/or clumsy to use, like the “hiding” of invocation layer that makes it quite hard for external contributors to add support for other LLMs to `PromptNode`, or it’s imperfect layer selection algorithm. + +# Adoption strategy + +Follows the same strategy outlines for all other Proposal relative to the Haystack 2.0 migration + +# How we teach this + +We need brand new tutorials and examples of pipelines using these components. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5738-document-2.0.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5738-document-2.0.md new file mode 100644 index 0000000000000000000000000000000000000000..43a1ebf2f57466ded64f8a75fd0b48562644d424 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5738-document-2.0.md @@ -0,0 +1,108 @@ +- Title: Document class for Haystack 2.0 +- Decision driver: ZanSara +- Start Date: 2023-09-07 +- Proposal PR: 5738 + +# Summary + +With Haystack 2.0 we want to provide a lot more flexibility to Pipelines and Components. In a lot of situations, +we found that the Document class inherited from Haystack 1.x was not up to the task: therefore we chose to expand its +API to work best in this new paradigm. + +# Basic example + +Documents 2.0 have two fundamental differences with Documents 1.x: + +- They have more than one content field. Documents 1.x only have a `content: Any` field that needs to match with the + `content_type` field in meaning. Documents 2.0 instead support `text`, `array`, `dataframe` and `blob`, each typed + correctly. + +- The `content_type` field is gone: In Haystack 1.x we used the `content_type` field to interpret the data contained + in the `content` field: with the new design, this won't be necessary any longer. Haystack 2.0, however, have + a `mime_type` field that helps interpret the content of the `blob` field if necessary. + +# Motivation + +During the development of Haystack 2.0 components, we often found ourselves hold back by the design limitations of +the Document class. Unlike in Haystack 1.x, Documents now carry more information across the pipeline: for example, +they might contain the file they originated from, they might support more datatypes, etc. + +Therefore we decided to extend the Document class to support a wider array of data. + +# Detailed design + +The design of this class was inspired by the [DocArray API](https://docarray.jina.ai/fundamentals/document/). + +Here is the high-level API of the new Document class: + +```python +@dataclass(frozen=True) +class Document: + id: str = field(default_factory=str) + text: Optional[str] = field(default=None) + array: Optional[numpy.ndarray] = field(default=None) + dataframe: Optional[pandas.DataFrame] = field(default=None) + blob: Optional[bytes] = field(default=None) + mime_type: str = field(default="text/plain") + metadata: Dict[str, Any] = field(default_factory=dict, hash=False) + id_hash_keys: List[str] = field(default_factory=lambda: ["text", "array", "dataframe", "blob"], hash=False) + score: Optional[float] = field(default=None, compare=True) + embedding: Optional[numpy.ndarray] = field(default=None, repr=False) + + def to_dict(self): + """ + Saves the Document into a dictionary. + """ + + def to_json(self, json_encoder: Optional[Type[DocumentEncoder]] = None, **json_kwargs): + """ + Saves the Document into a JSON string that can be later loaded back. Drops all binary data from the blob field. + """ + + @classmethod + def from_dict(cls, dictionary): + """ + Creates a new Document object from a dictionary of its fields. + """ + + @classmethod + def from_json(cls, data, json_decoder: Optional[Type[DocumentDecoder]] = None, **json_kwargs): + """ + Creates a new Document object from a JSON string. + """ + + def flatten(self) -> Dict[str, Any]: + """ + Returns a dictionary with all the document fields and metadata on the same level. + Helpful for filtering in document stores. + """ + +``` + +As you can notice, the main difference is the management of the content fields: we now have: + +- `text`: for text data +- `array`: for array-like data, for example images, audio, video +- `dataframe`: for tabular data +- `blob`: for binary data. + +In order to help interpret the content of these field, there's a `mime_type` field that components can use to figure out +how to use the content fields they need. + +There are additional information that we may want to add, for example `path`. For now such info can be +kept into the metadata: if we realize we access it extremely often while processing Documents we should consider +bringing those fields out of `metadata` as top-level properties of the dataclass. + + +# Drawbacks + +As the Document class becomes a bit more complex, components need to be adapted to it. This may cause some issues +to DocumentStores, because now they not only need to be able to store text but binary blobs as well. + +We can imagine that some very simple DocumentStore will refuse to store the binary blobs. Fully-featured, +production-ready document stores instead should be able to find a way to store such blobs. + + +# Unresolved questions + +Are the 4 content fields appropriate? Are there other content types we can consider adding? diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5794-evaluation-haystack-2.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5794-evaluation-haystack-2.md new file mode 100644 index 0000000000000000000000000000000000000000..9093a19e0a6e0bc59a6e448a0bcf2eb4868dc6f2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5794-evaluation-haystack-2.md @@ -0,0 +1,227 @@ +- Title: Evaluation in Haystack 2.0 +- Decision driver: (Silvano Cerza, Julian Risch) +- Start Date: 2023-08-23 +- Proposal PR: [#5794](https://github.com/deepset-ai/haystack/pull/5794/) +- Github Issue or Discussion: https://github.com/deepset-ai/haystack/issues/5628 + +# Summary + +Given the below requirements we redefine how evaluation and metrics are handled in Haystack 2.x. + +Our goal is to lower the barrier of entry for new comers but also making it more flexible and extensible for more advanced and expert users. +All this while making it more modular and easier to test and maintain. + +The requirements are: + +- compare the performance of different pipelines on level of pipeline outputs (user perspective, integrated eval) + - while running the full pipeline we can store intermediate results and calculate metrics for each component that returns answers or documents +- find out which component is the performance bottleneck in one pipeline by evaluating subpipelines (isolated evaluation) +- as above, get evaluation metrics for every component in a pipeline that returns answer or documents (ranker, retriever, reader, PromptNode) +- compare the performance of two components, for example two Readers, without the need to create a full retriever-reader pipeline +- export evaluation results to a file (similar to Haystack 1.x but faster) and evaluation report +- choose evaluation metrics from a list of metrics (e.g. F1, BLEU, ROUGE, Semantic Answer Similarity) based on the output type of a component +- evaluate pipelines that return ExtractiveAnswers +- evaluate pipelines that return GenerativeAnswers +- evaluate hallucinations (check generated answers are backed up by retrieved documents) +- evaluate pipelines with PromptNodes and arbitrary PromptTemplates (for example with Semantic Answer Similarity or BLEU, ROUGE (metrics from machine translation and summarization) if I provide labels) +- load evaluation data for example from BEIR + +# Basic example + +```python +pipe = Pipeline() +... +inputs = [{"component_name": {"query": "some question"}, ...}, ...] +expected_output = [{"another_component_name": {"answer": "42"}, ...}, ...] +result = eval(pipe, inputs=inputs, expected_output=expected_output) +metrics = result.calculate_metrics(Metric.SAS) +metrics.save("path/to/file.csv") +``` + +A more thorough example of a real use case can be found in the `0000-evaluation-haystack-2.py` file. It creates a small RAG Pipeline and shows how one would run evaluation on it. + +# Motivation + +Since the new version 2.x of Haystack is going toward a completely different approach to run `Pipeline`s and `component`s we also need to rework how we evaluate them. + +The current implementation in version 1.x is convoluted and mixes evaluation and metrics at different steps during the process. This makes it harder to reason about it and maintain. This is noticeable also by the fact that only a limited amount of nodes can be evaluated. Also it's currently not easy to calculate custom metrics. + +The goal of this new approach is to make it easier for users to evaluate and calculate metrics for their `Pipeline`s and `component`s. Evaluation is not an easy task to reason about and understand. Making it simpler will also make it less intimidating to less experienced users, pushing more people to approach this important part of Haystack. + +It must be flexible by making it possible to evaluate any type of `component`. This is also an hard requirement since we want to make it easier for users to define new `component`s. Limiting the types of `component`s that can be evaluated would also limit the usage of custom or novelty ones, thus limiting the user creativity. + +Extensibility is part of the goal too. We want to make is possible for user to calculate some of most common metrics, but also use custom logic to calculate any other one. As of now it's not possible to calculate custom metrics without knowing the nitty gritty of the Haystack internals. + +All these goals merge also into another goal, maintainability. By making evaluation and metrics calculation more modular and easy to use we're also going to make it more maintainable and testable. + +# Detailed design + +### The `eval` function + +We'll implement an `eval` function that will be able to evaluate all `Pipeline`s and `Component`s. +A minimal implementation could look like this: + +```python +def eval(runnable: Union[Pipeline, Component], inputs: List[Dict[str, Any]], expected_outputs: List[Dict[str, Any]]) -> EvaluationResult: + outputs = [] + for input_ in inputs: + output = runnable.run(input_) + outputs.append(output) + return EvaluationResult(runnable, inputs, outputs, expected_outputs) +``` + +This is obviously an overtly simplistic example but the core concept remains. +`inputs` must be a list of data that will be passed to either the `Pipeline` or the `Component`. +`expected_outputs` could be a list with the same length of `inputs` or an empty list for blind evaluation. + +Blind in this context means running an evaluation without providing a list of expected output. This could be done for several reasons, like if we don't know what to expect as output, or to compare output of different components. + +`EvaluationResult` could either be a `Dict` or its own class, this is open to discussion. Either way it must be easy to save to disk. When saving the results to disk we can also include the `Pipeline` or `Component` in a serialized form. + +When evaluating a `Pipeline` we could also override its private `_run_component` function to evaluate every node it will run. This will 100% work for our implementation of `Pipeline`. If a user tries to evaluate a `Pipeline` that reimplements its own `run` method it might not be able to evaluate each `Component`. I believe this a worthy risky tradeoff. + +Overriding `_run_component` would also give us the chance to simulate optimal component outputs. `eval` could also accept an optional `simulated_output` dictionary containing the outputs of one or more `Component` that are in the `Pipeline`. It would look similar to this: + +```python +simulated_output = { + "component_name": {"answer": "120"}, + "another_component_name": {"metadata": {"id": 1}} +} +``` + +Another alternative would be to use the `expected_output` also to simulate outputs of intermediate components. + +#### Tracking progress + +To track progress we can also go on another direction. We could return partials results while iterating our inputs: + +``` +def eval(runnable, inputs, expected_outputs): + result = EvaluationResult(runnable, inputs, {}, expected_outputs) + for input_ in inputs: + output = runnable.run(input_) + result.append_output(output) + yield result +``` + +Or return some progress percentage and only in the end the final result. + +``` +def eval(runnable, inputs, expected_outputs): + outputs = [] + total = len(inputs) + for i, input_ in enumerate(inputs): + output = runnable.run(input_) + outputs.append(output) + yield 100 * (i / total), None + + yield 100, EvaluationResult(runnable, inputs, outputs, expected_outputs) +``` + +### `EvaluationResult` + +`EvaluationResult` won't contain partial metrics anymore as it does in v1.x but it will keep track of all the information used by `eval()`. +This way we'll be able to save all the necessary information to a single file. That information will probably be: + +- Serialized Pipeline or Component +- Inputs +- Expected outputs +- Actual outputs + +This data should be serializable to string so that it can be saved to file and loaded back whenever necessary. +We shouldn't expect all input and output data to implement serialization methods like `to_dict` and `from_dict` like `Pipeline` and `component`s do, so we probably should find an alternative to handle serialization of types that don't. An unsafe option would be the use of `pickle`, but that's dangerous as it could lead to malicious code being executed. + +Given the above information we should be able to implement a single method to calculate predeterminated metrics or even custom ones. +Known metrics could be defined as an enum to ease discoverability and documentation. + +```python +class Metric(Enum): + RECALL = "Recall" + MRR = "Mean Reciprocal Rank" + MAP = "Mean Average Precision" + EM = "Exact Match" + F1 = "F1" + SAS = "SemanticAnswerSimilarity" +``` + +The method to calculate metrics could look similar to this: + +```python +MetricsResult = Dict[str, Dict[str, float]] +MetricCalculator = Callable[..., MetricResult] + +def calculate_metrics(self: EvaluationResult, metric: Union[Metric, MetricCalculator], **kwargs) -> MetricsResult: + # Verify if we're calculating a known metric + if metric == Metric.RECALL: + return self._calculate_recall(**kwargs) + elif metric == Metric.MRR: + return self._calculate_mrr(**kwargs) + # Other metrics... + + # If it's not a known metric it must be a custom one + return metric(self, **kwargs) +``` + +This gives the users the flexibility to easily calculate metrics that we support but also use custom logic to calculate any kind of metric given the available data. +Since users will need to save their calculated metrics to file we could create a simple `MetricResult` class that simply wraps the generated metrics dictionary, something similar: + +```python +class MetricResult(dict): + def save(self, file: Union[str, Path]): + # Dump info to file here +``` + +### Ease input specification + +When declaring the input of a `Pipeline` we must specify both a `component` name and its input names. This can be annoying so we could simplify this by making certain assumptions. + +An approach to this problem could be letting the user skip the `component` name specification when declaring the `Pipeline` input. This could work up until the point the user changes their `Pipeline` to have multiple inputs with the same name. + +So given a `Pipeline` that has single input `component` name `foo` that takes a `query` as its input we can let the user specify the `eval` input like so: + +```python +eval(pipe, {"query": "This is the query"}) +``` + +If the user adds a new `component` name `bar` that also takes a `query` as input we'll make evaluation fail preventively since we cannot be sure whether both `component`s must take `query` as input and force explicit specification: + +```python +eval(pipe, {"foo": {"query": "This is the query"}, "bar": {"query": "This is the query"}}) +``` + +# Drawbacks + +The major drawback found from the feedback gathered is always the same, and it's also common to `Pipeline.run()`. It's frustrating and annoying having to update the evaluation input and/or output data if I make changes to my `Pipeline`. + +Given that new `Pipeline` can have multiple inputs to different `component`s we must specify which component will take which input. As an example given a `Pipeline` with two input components called `foo` and `bar` that takes a `input_query` value we'll have to specify input as follow: + +```python +input = { + "foo": {"input_query": "This my input query"}, + "bar": {"input_query": "This my input query"} +} +``` + +I believe this a worthy tradeoff as it gives huge amount of customization that wasn't possible in Haystack 1.x. + +We could ease inputs specification in some cases as specified in the above section but that would make evaluation prone to errors. I believe that to be a dangerous approach as it could mean making evaluation "easier to use" at the cost of making it also more error prone if not done properly and with the correct safe guards. + +The same thing can be said for the `Pipeline` output. There will be multiple outputs most of the times since we're going to evaluate individual nodes and the whole `Pipeline` input with a single evaluation run. So the user must specify from which `component` the output should be expected from. + +Expected output specification suffers from the same issue of inputs specification. So making assumption to try and match expected output with the actual `Pipeline` output is still error prone but probably can be handled for really simple `Pipeline`s with only a single output `component`. + +Evaluation should be an advanced topic for users that know what they're actually doing. This might seem contradictory to what has been said above regarding approachability of the feature but I believe this to be an easy to use but and hard to master feature. + +# Adoption strategy + +This is obviously a breaking change as it's meant for Haystack 2.x. + +# How we teach this + +Much like the current situation we'll write tutorials, examples and documentation to go along with this new feature. We can also leverage future ready-made `Pipeline`s to show how to evaluate them. + +We're also going to have new community spotlights in Discord to show how to approach evaluation in Haystack 2.x. + +# Unresolved questions + +Evaluation of pipelines containing Agents or other loops is out of scope for this proposal (except for integrated pipeline evaluation). diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5794-evaluation-haystack-2.py b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5794-evaluation-haystack-2.py new file mode 100644 index 0000000000000000000000000000000000000000..5e0661d0cb8cd1d934569dfa6bd0688d20f3b0e7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5794-evaluation-haystack-2.py @@ -0,0 +1,141 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +# mypy: ignore-errors +# pylint: skip-file +### +### This is an example script of how to use the eval function to evaluate a RAG Pipeline. +### For more information see the relative proposal. +### + +import os + +from haystack import Pipeline +from haystack.components.builders.prompt_builder import PromptBuilder +from haystack.components.generators.openai.gpt35 import GPT35Generator +from haystack.components.retrievers.memory import MemoryBM25Retriever +from haystack.dataclasses.document import Document +from haystack.document_stores.memory import MemoryDocumentStore + +docstore = MemoryDocumentStore() + +# Write some fake documents +docstore.write_documents( + [ + Document(content="This is not the answer you are looking for.", meta={"name": "Obi-Wan Kenobi"}), + Document(content="This is the way.", meta={"name": "Mandalorian"}), + Document(content="The answer to life, the universe and everything is 42.", meta={"name": "Deep Thought"}), + Document(content="When you play the game of thrones, you win or you die.", meta={"name": "Cersei Lannister"}), + Document(content="Winter is coming.", meta={"name": "Ned Stark"}), + ] +) + +# Create our retriever, we set top_k to 3 to get only the best 3 documents otherwise by default we get 10 +retriever = MemoryBM25Retriever(document_store=docstore, top_k=3) + +# Create our prompt template +template = """Given the context please answer the question. +Context: +{# We're receiving a list of lists, so we handle it like this #} +{% for list in documents %} + {% for doc in list %} + {{- doc -}}; + {% endfor %} +{% endfor %} +Question: {{ question }}; +Answer: +""" +prompt_builder = PromptBuilder(template) + +# We're using OpenAI gpt-3.5 +OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "") +generator = GPT35Generator(api_key=OPENAI_API_KEY) + +# Build the pipeline +pipe = Pipeline() + +pipe.add_component("docs_retriever", retriever) +pipe.add_component("builder", prompt_builder) +pipe.add_component("gpt35", generator) + +pipe.connect("docs_retriever.documents", "builder.documents") +pipe.connect("builder.prompt", "gpt35.prompt") + +# Run the pipeline +query = "What is the answer to life, the universe and everything?" +result = pipe.run({"docs_retriever": {"queries": [query]}, "builder": {"question": query}}) + +print(result["gpt35"]["replies"]) + + +# These are the input that will be passed to the Pipeline when running eval, much like we've done a couple of lines above +inputs = [ + {"docs_retriever": {"queries": ["What is the answer?"]}, "builder": {"question": "What is the answer?"}}, + { + "docs_retriever": {"queries": ["Take a deep breath and think. What is the answer?"]}, + "builder": {"question": "Take a deep breath and think. What is the answer?"}, + }, + { + "docs_retriever": {"queries": ["What is the answer to life, the universe and everything?"]}, + "builder": {"question": "What is the answer to life, the universe and everything?"}, + }, +] + +# These are the expected output that will be compared to the actual output of the Pipeline. +# We have a dictionary for each input so that len(inputs) == len(expected_output). +# This gives the possibility to have different expected output for each different input. +# NOTE: I omitted the gpt35 metadata output because it's too long. +expected_output = [ + { + # This is the output that we expect from the docs_retriever component + "docs_retriever": { + "documents": [ + [ + Document( + content="The answer to life, the universe and everything is 42.", meta={"name": "Deep Thought"} + ), + Document(content="This is not the answer you are looking for.", meta={"name": "Obi-Wan Kenobi"}), + Document(content="This is the way.", meta={"name": "Mandalorian"}), + ] + ] + }, + # This is the output that we expect from the builder component + "builder": {"prompt": "I should write the actual template here but I'm lazy so I won't."}, + # This is the output that we expect from the gpt35 component + "gpt35": {"replies": ["The answer to life, the universe and everything is 42."], "metadata": {}}, + }, + { + "docs_retriever": { + "documents": [ + [ + Document( + content="The answer to life, the universe and everything is 42.", meta={"name": "Deep Thought"} + ), + Document(content="This is not the answer you are looking for.", meta={"name": "Obi-Wan Kenobi"}), + Document(content="This is the way.", meta={"name": "Mandalorian"}), + ] + ] + }, + "builder": {"prompt": "I should write the actual template here but I'm lazy so I won't."}, + "gpt35": {"replies": ["The answer to life, the universe and everything is 42."], "metadata": {}}, + }, + { + "docs_retriever": { + "documents": [ + [ + Document( + content="The answer to life, the universe and everything is 42.", meta={"name": "Deep Thought"} + ), + Document(content="This is not the answer you are looking for.", meta={"name": "Obi-Wan Kenobi"}), + Document(content="This is the way.", meta={"name": "Mandalorian"}), + ] + ] + }, + "builder": {"prompt": "I should write the actual template here but I'm lazy so I won't."}, + "gpt35": {"replies": ["The answer to life, the universe and everything is 42."], "metadata": {}}, + }, +] + +eval_result = eval(pipe, inputs=inputs, expected_output=expected_output) +metrics = result.calculate_metrics(Metric.SAS) # noqa +metrics.save("path/to/file.csv") diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6001-document-store-filter-rework.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6001-document-store-filter-rework.md new file mode 100644 index 0000000000000000000000000000000000000000..64e7ab9bfb605b3df7db6f6ba3052e693bbf0a9d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6001-document-store-filter-rework.md @@ -0,0 +1,183 @@ +- Title: Document Stores filter specification for Haystack 2.x +- Decision driver: Silvano Cerza +- Start Date: 2023-10-08 +- Proposal PR: [#6001](https://github.com/deepset-ai/haystack/pull/6001) + +# Summary + +This proposal introduces a new fully detailed and extensible specification for filtering Document Stores in Haystack 2.x. +This comes from my personal experience and struggles trying to implement filters conversion for `ElasticsearchDocumentStore`. + +# Basic example + +``` +{ + "conditions": [ + { "field": "age", "operator": ">=", "value": 18 }, + { + "operator": "OR", + "conditions": [ + { "field": "country", "operator": "==", "value": "USA" }, + { "field": "country", "operator": "==", "value": "Canada" } + ] + } + ] +} +``` + +The above snippet would be equivalent to the following Python code: + +```python +age >= 18 and (country == "USA" or country == "Canada) +``` + +# Motivation + +Filtering in Haystack 1.x has no detailed clear specification, we only have an [high level overview][filters-high-level-doc] in the documentation that also mixes REST APIs documentation in. It's also inherited from MongoDB and is a subset of the Mongo Query Language. + +Converting from the current filters to another query language is quite hard as there are tons of corner cases. Handling nested filters is usually really error prone as the operators can be keys, this requires ton of nested and/or recursive logic to figure out whether the current key is a field or an operator. There's also quite some backtracking involved as the field could be two or three levels above its comparison operator and/or value. + +As a practical example the below two filters are equivalent. Given that they're structured differently and `$and` is implicit in the second one: + +``` +{"number": {"$and": [{"$lte": 2}, {"$gte": 0}]}} + +{"number": {"$lte": 2, "$gte": 0}} +``` + +With the newly proposed approach both filters would be equivalent to: + +``` +{ + "operator": "AND", + "conditions": [ + { "field": "number", "operator": "<=", "value": 2 }, + { "field": "number", "operator": ">=", "value": 0 }, + ] +} +``` + +As you can see all the required information is one the same level and clearly recognisable. This makes it much easier both to read by a human and convert with code. + +In Python code: + +```python +number <= 2 AND number >= 0 +``` + +# Detailed design + +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` + +--- + +As an example this: + +``` +{ + "$and": { + "type": {"$eq": "article"}, + "$or": {"genre": {"$in": ["economy", "politics"]}, "publisher": {"$eq": "nytimes"}}, + "date": {"$gte": "2015-01-01", "$lt": "2021-01-01"}, + "rating": {"$gte": 3}, + } +} +``` + +would convert to: + +``` +{ + "operator": "AND", + "conditions": [ + { "field": "type", "operator": "==", "value": "article" }, + { + "operator": "OR", + "conditions": [ + { "field": "genre", "operator": "in", "value": ["economy", "politics"] }, + { "field": "publisher", "operator": "==", "value": "nytimes" }, + ] + }, + { "field": "date", "operator": ">=", "value": "2015-01-01" }, + { "field": "date", "operator": "<", "value": "2021-01-01" }, + { "field": "rating", "operator": ">=", "value": 3 }, + ] +} +``` + +In Python code: + +```python +type == "article" and ( + genre in ["economy", "politics"] or publisher == "nytimes" +) and date >= "2015-01-01" and date < "2021-01-01" and rating >= 3 +``` + +Dates have been kept as strings but ideally in the new implementation they would be converted to `datetime` instances so the Document Store will be able to convert it to whatever format it needs to actually compare them. As different Document Stores might have different ways of storing the same value it's important that they handle the conversion from Python type to stored type. + +Another thing that in my opinion should be changed is the that filtering metadata fields must be explicitly specified for filtering. In the example above all `field`s would be prefixed with `metadata.` to get in return the expected `Document`s. e.g. `date` -> `metadata.date` +This connects to `Document` implementation and is not the focus of this proposal, but it should be taken into account. + +# Drawbacks + +The only drawback would be that we need to adapt the existing Document Stores already created for Haystack 2.x to support this filtering system. `MemoryDocumentStore`, `ElasticsearchDocumentStore`, `ChromaDocumentStore` and `MarqoDocumentStore` are the currently existing Document Stores. + +# Alternatives + +An alternative would be keeping the current strategy of declaring filters. +This wouldn't require any change but supporting a new filtering language after the release of Haystack 2.x would be more difficult than doing it now. + +# Adoption strategy + +We're going to release this new strategy of filters declaration for Haystack 2.x. At the same time we'll deprecate the current strategy but we'll keep supporting it for a while. + +Since we're going to provide an utility function to convert from old style to new style it will be easy for Document Stores to support both. + +# How we teach this + +We're going to provide documentation and specifications on how the filters should be declared, this proposal is a good starting point as it already defines the specs. + +We're also going to provide utility functions to migrate filters from old style to new style. + +# Unresolved questions + +This is the full design and there are no unresolved questions. + +[filters-high-level-doc]: https://docs.haystack.deepset.ai/docs/metadata-filtering diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6141-meta-field-ranker.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6141-meta-field-ranker.md new file mode 100644 index 0000000000000000000000000000000000000000..ca177366055107d8b7307f7a1455d9d088fac4ee --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6141-meta-field-ranker.md @@ -0,0 +1,68 @@ +- Title: Meta Field Ranker +- Decision driver: @domenicocinque +- Start Date: 2023-10-20 +- Proposal PR: https://github.com/deepset-ai/haystack/pull/6141 +- Github Issue or Discussion: https://github.com/deepset-ai/haystack/issues/6054 + +# Summary + +This ranker should allow to sort the documents based on a meta field of choice. + +# Basic example + +The ranker could be instantiated as follows: + +``` python +ranker = MetaFieldRanker( + meta_field="rating", + weight="0.5", + ascending=False, + top_k=3, +) +``` +In the context of a simple pipeline with a retriever and a MetaFieldRanker in which +the documents are provided with a meta field "rating". The documents are first retrieved by the retriever and +then sorted by the MetaFieldRanker. + +``` python +pipeline = Pipeline() +pipeline.add_component(component=InMemoryBM25Retriever(document_store=document_store, top_k=20) +, name="Retriever") +pipeline.add_component(component=MetaFieldRanker(meta_field="rating"), name="Ranker") +pipeline.connect("Retriever.documents", "MetaFieldRanker.documents") +``` + +# Motivation + +I found the need for this feature while working on system that retrieves books based on their description and the +similarity to the query. After retrieving the documents it makes sense to expose them to the user in order of popularity. +This is just one example of a use case for this feature, but I think it could be useful in many other contexts. + +# Detailed design + +The actual implementation of the ranker is very similar to the already present RecentnessRanker. The main difference +is to remove the date parsing logic. + +# Drawbacks + +The main drawback is that it would be very similar to the already present RecentnessRanker. However, this could be +solved by making the RecentnessRanker a subclass of the MetaFieldRanker and adding the date parsing logic to it. +Apart from that, it is a very simple component that should not have any other drawbacks. + +# Alternatives + +The alternative is to make the user implement its own ranking logic. + +# Adoption strategy + +MetaFieldRanker is a Haystack 2.0 component. As it is not a breaking change, it should be easy to adopt in combination with the other components. + +# How we teach this + +It would be sufficient to integrate a small comparison with the RecentnessRanker in the documentation. + + +# Unresolved questions + +The main issue is the implementation strategy. Especially if we want to include the `ranking_mode` parameter in the +MetaFieldRanker, it would make sense to have the RecentnessRanker as a subclass of the MetaFieldRanker. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6784-integrations-for-eval-framworks.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6784-integrations-for-eval-framworks.md new file mode 100644 index 0000000000000000000000000000000000000000..e3b245f1062befe91ba514f199e057092c219961 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6784-integrations-for-eval-framworks.md @@ -0,0 +1,151 @@ +- Title: Integration of LLM Evaluation Frameworks +- Decision driver: Madeesh Kannan, Julian Risch +- Start Date: 2024-01-19 +- Proposal PR: https://github.com/deepset-ai/haystack/pull/6784 +- Github Issue or Discussion: https://github.com/deepset-ai/haystack/issues/6672 + +# Summary + +- Create integrations for three different LLM evaluation frameworks in https://github.com/deepset-ai/haystack-core-integrations +- The LLM evaluation frameworks in question are: [Uptrain](https://docs.uptrain.ai/getting-started/introduction), [RAGAS](https://docs.ragas.io/en/stable/index.html) and [DeepEval](https://docs.confident-ai.com/docs/getting-started). +- The integrations introduce the following components in this order: `UptrainEvaluator`, `RagasEvaluator`, `DeepEvalEvaluator`. +- Users can run a Haystack pipeline and evaluate the result with model-based metrics implemented by the evaluation frameworks. +- Calculation of metrics is done by the frameworks through running prompts with OpenAI (Uptrain) or using langchain to make the OpenAI call (RAGAS, DeepEval). + +# Basic example + +With the integration, users can use Haystack’s pipeline concept for the evaluation too. They need to provide the outputs of the RAG pipeline as inputs to the Evaluator component in an evaluation pipeline: + +```python +p = Pipeline() +p.add_component(instance=DeepEvalEvaluator(metric="Hallucination", params={"threshold": 0.3)}, name="evaluator")) +# p.add_component(instance=RagasEvaluator()... + +questions = [...] +contexts = [...] +answers = [...] + +p.run({"evaluator": {"questions": questions, "context": contexts, "answer": answers}) +# {"evaluator": DeepEvalResult(metric='hallucination', score=0.817)} +``` + +# Motivation + +Users of Haystack that deploy RAG pipelines currently do not have an avenue of evaluating the outputs of the same. Traditional methods of evaluation that involves the creation of labelled datasets is often out of reach for open-source practitioners due resource- and time-constraints. Furthermore, this approach is not necessarily scalable and applicable to LLMs due to the generative property of RAG-based information retrieval. + +This is given rise to model-based evaluation approaches, i.e., the method of training language models to act as classifiers and scorers. A very popular implementation of this approach revolves around designing prompt-based natural language metrics that are used in conjunction with an instruction-trained LLM. The LLM then acts as the judge, evaluating the outputs based on the criteria defined in the metrics. This approach is eminently more scalable and low-friction for the end-user. + +Other LLM application frameworks such as LlamaIndex already provide support for this approach to evaluation, and it is in Haystack's interests to do the same. This will also help establish a baseline against which our future efforts in this area can be compared. + +# Detailed design + +As with evaluation in Haystack 1.x, we reaffirm the core idea of implementing different pipelines for different concerns. We consider evaluation a separate process and consequently separate the execution of RAG and the metric calculation into two different pipelines. This allows for greater flexibility - for instance, the evaluation pipeline could contain an additional component that routes the inputs to different evaluator components based on certain criteria, etc. Another example would be the ability to convert the inputs from/to different formats before passing them to the evaluator. + +A further advantage of this approach is that any tool we develop in the future to facilitate introspection and observability of pipelines can transparently be appled to evaluation as well. + +The implementation of the three evaluator components should follow the general guidelines for custom component development. There are two approaches we could take: + +- **Metric wrapping**: Make each metric an individual component. + + Advantages: + + - Inputs and outputs are explicitly defined for each metric, which makes the API more explicit. + - We can control which metrics to include. + - We can use the execution graph for control flow. + + Disadvantages: + + - Duplication between frameworks. + - Maintenance burden. + - Less freedom for the user. + +- **Framework wrapping**: Make each evaluation framework an individual component. + + Advantages: + + - Straightforward implementation. + - Easier to reason about. + - Low maintenance burden. + - More freedom for the user. + + Disadvantages: + + - API has to accommodate all possible inputs for all supported metrics. + - Less flexibility. + +Given the above comparison, **we will be implementing the second approach, i.e., framework as the component**. The disadvantages mentioned above can be mitigated by leaning into Haystack 2.x's I/O system. + +## API overview + +- We implement three components: `DeepEvalEvaluator`, `RagasEvaluator`, `UpTrainEvaluator`. +- Their constructors take a two parameters: `Literal["MetricName"]` and `Optional[Dict[str, Any]]` for the metric name and optional parameters for the same. + - We use JSON-serializable types here to ensure serde support. +- The component initializes the internal framework-specific metric representation. +- Depending on the metric, the component also calls `set_input_types` to register the appropriate input sockets for the given metric, e.g: `question`, `contexts`, `answer` for groundness, etc. + - This approach lets the user modulate the inputs individually, which wouldn't be possible if we use a generic representation for all metrics/frameworks. +- Outputs can be implemented in one of two ways: + + - `set_output_types` is also called to enumerate the outputs of the metric + - The output is a `dataclass` specific to the evaluation framework. + + As opposed to their inputs, the outputs of metrics are not likely to require sophisticated routing for their usage further downstream. So, each evaluator will implement a dataclass that encapsulates the results of the evaluation. + +### Illustrative example + +```python +from deepeval import BaseMetric, FaithfulnessMetric + +@component +class DeepEvalEvaluator: + self._metric: BaseMetric + + def __init__(self, metric: str, params: Optional[Dict[str, Any]]): + params = {} if params is None + if metric == "Faithfulness": + self._metric = FaithfulnessMetric(**params) + self.set_input_types(questions=List[str], answers=List[str], contexts=Listt[List[str]]) + elif metric == "ContextRecall": + ... + + def run(self, **kwargs): + # Logic to unwrap the inputs based on the metric and + # execute the backend code. + ... + +``` + +# Drawbacks + +- **Lack of support for custom components**: The aforementioned API inherently restricts the user to the pre-defined metrics provided by the frameworks. On the other hand, we'd like to keep these integrations limited in their scope. Since we also plan on providing custom metric support in the future, this becomes a moot point. +- **No support for batching across metrics**: Batching here refers to calculating multiple metrics on the inputs with a single API call. With the exception of UpTrain, the frameworks in question do not support this either. UpTrain's implementation is not publicly available, so we cannot determine if this type of batching happens on their server. +- **Additional dependencies**: RAGAS and DeepEval depend on langchain, whereas UpTrain uses both its own client and OpenAI's. + - https://github.com/confident-ai/deepeval/blob/main/pyproject.toml + - https://github.com/explodinggradients/ragas/blob/main/pyproject.toml + - https://github.com/uptrain-ai/uptrain/blob/main/pyproject.toml + +# Alternatives + +- Eschewing the pipeline paradigm and using a separate evaluation API. + - Similar to how it was done in Haystack 1.x. +- Implement them as components but run them individually. + - This would also be possible with the proposed API. + +# Adoption strategy + +This is a new feature with no breaking changes. Existing users can simply try out the evaluation with existing pipelines after installing additional dependencies and providing an OpenAI API key. + +# How we teach this + +We provide a new section in the documentation about evaluation. This proposal specifically deals with model-based evaluation, so it would be prudent to have a separate subsection for it. + +We should impress upon them the idea that evaluation is "just" another pipeline with different steps. A tutorial would also be helpful to guide them through the same. Apart from that, we should include pointers to the API docs of the different evaluation frameworks, etc. + +We clarify in the documentation how users can decide which Evaluation framework is best for them with a simple overview. They should not need to research the different frameworks before running their first evaluation. + +# Unresolved questions & future work + +- We see the integrated evaluation frameworks as a baseline. To what extent and when Haystack will have its own model-based metrics is out-of-scope for this proposal. +- We envision an `Evaluator` component in Haystack's core with customizable model and prompt. +- Terminology around existing `calculate_metrics`/`eval` functions and the `EvaluationResult` class need to be discussed (c.f https://github.com/deepset-ai/haystack/pull/6505). +- Alternative take on the evaluation API - https://github.com/deepset-ai/haystack/pull/5794/ + - The ideas proposed in the above should compatible with those of this proposal. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/7462-rag-evaluation.md b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/7462-rag-evaluation.md new file mode 100644 index 0000000000000000000000000000000000000000..21935ce88f457a2a52ec9676d1b9bbe20e4c5880 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/proposals/text/7462-rag-evaluation.md @@ -0,0 +1,223 @@ +- Title: Proposal for presentation of evaluation results +- Decision driver: David S. Batista +- Start Date: 2024-04-03 +- Proposal PR: #7462 +- Github Issue or Discussion: https://github.com/deepset-ai/haystack/issues/7398 + +# Summary + +Add a new component to Haystack allowing users interact with the results of evaluating the performance of a RAG model. + + +# Motivation + +RAG models are one of them most popular use cases for Haystack. We are adding support for evaluations metrics, but there is no way to present the results of the evaluation. + + +# Detailed design + +The output results of an evaluation pipeline composed of `evaluator` components are passed to a `EvaluationResults` +(this is a placeholder name) which stores them internally and acts as an interface to access and present the results. + +The examples below are just for illustrative purposes and are subject to change. + +Example of the data structure that the `EvaluationResults` class will receive for initialization: + +```python + +data = { + "inputs": { + "query_id": ["53c3b3e6", "225f87f7"], + "question": ["What is the capital of France?", "What is the capital of Spain?"], + "contexts": ["wiki_France", "wiki_Spain"], + "answer": ["Paris", "Madrid"], + "predicted_answer": ["Paris", "Madrid"] + }, + "metrics": + [ + {"name": "reciprocal_rank", "scores": [0.378064, 0.534964, 0.216058, 0.778642]}, + {"name": "single_hit", "scores": [1, 1, 0, 1]}, + {"name": "multi_hit", "scores": [0.706125, 0.454976, 0.445512, 0.250522]}, + {"name": "context_relevance", "scores": [0.805466, 0.410251, 0.750070, 0.361332]}, + {"name": "faithfulness", "scores": [0.135581, 0.695974, 0.749861, 0.041999]}, + {"name": "semantic_answer_similarity", "scores": [0.971241, 0.159320, 0.019722, 1]} + ], + }, + +``` + +The `EvaluationResults` class provides the following methods to different types of users: + +Basic users: +- `individual_aggregate_score_report()` +- `comparative_aggregate_score_report()` + +Intermediate users: +- `individual_detailed_score_report()` +- `comparative_detailed_score_report()` + +Advanced users: +- `find_thresholds()` +- `find_inputs_below_threshold()` + + +### Methods description +An evaluation report that provides a summary of the performance of the model across all queries, showing the +aggregated scores for all available metrics. + +```python +def individual_aggregate_score_report(): +``` + +Example output + +```bash +{'Reciprocal Rank': 0.448, + 'Single Hit': 0.5, + 'Multi Hit': 0.540, + 'Context Relevance': 0.537, + 'Faithfulness': 0.452, + 'Semantic Answer Similarity': 0.478 + } + ``` + +A detailed evaluation report that provides the scores of all available metrics for all queries or a subset of queries. + +```python +def individual_detailed_score_report(queries: Union[List[str], str] = "all"): +``` + +Example output + +```bash +| question | context | answer | predicted_answer | reciprocal_rank | single_hit | multi_hit | context_relevance | faithfulness | semantic_answer_similarity | +|----------|---------|--------|------------------|-----------------|------------|-----------|-------------------|-------------|----------------------------| +| What is the capital of France? | wiki_France | Paris | Paris | 0.378064 | 1 | 0.706125 | 0.805466 | 0.135581 | 0.971241 | +| What is the capital of Spain? | wiki_Spain | Madrid | Madrid | 0.534964 | 1 | 0.454976 | 0.410251 | 0.695974 | 0.159320 | +``` + +### Comparative Evaluation Report + +A comparative summary that compares the performance of the model with another model based on the aggregated scores +for all available metrics. + +```python +def comparative_aggregate_score_report(self, other: "EvaluationResults"): +``` + +```bash +{ + "model_1": { + 'Reciprocal Rank': 0.448, + 'Single Hit': 0.5, + 'Multi Hit': 0.540, + 'Context Relevance': 0.537, + 'Faithfulness': 0.452, + 'Semantic Answer Similarity': 0.478 + }, + "model_2": { + 'Reciprocal Rank': 0.448, + 'Single Hit': 0.5, + 'Multi Hit': 0.540, + 'Context Relevance': 0.537, + 'Faithfulness': 0.452, + 'Semantic Answer Similarity': 0.478 + } +} + +``` + +A detailed comparative summary that compares the performance of the model with another model based on the scores of all +available metrics for all queries. + + +```python +def comparative_detailed_score_report(self, other: "EvaluationResults"): +``` + +```bash +| question | context | answer | predicted_answer_model_1 | predicted_answer_model_2 | reciprocal_rank_model_1 | reciprocal_rank_model_2 | single_hit_model_1 | single_hit_model_2 | multi_hit_model_1 | multi_hit_model_2 | context_relevance_model_1 | context_relevance_model_2 | faithfulness_model_1 | faithfulness_model_2 | semantic_answer_similarity_model_1 | semantic_answer_similarity_model_2 | +|----------|---------|--------|--------------------------|--------------------------|-------------------------|-------------------------|--------------------|--------------------|-------------------|-------------------|---------------------------|---------------------------|----------------------|----------------------|------------------------------------|------------------------------------| +| What is the capital of France? | wiki_France | Paris | Paris | Paris | 0.378064 | 0.378064 | 1 | 1 | 0.706125 | 0.706125 | 0.805466 | 0.805466 | 0.135581 | 0.135581 | 0.971241 | 0.971241 | +| What is the capital of Spain? | wiki_Spain | Madrid | Madrid | Madrid | 0.534964 | 0.534964 | 1 | 1 | 0.454976 | 0.454976 | 0.410251 | 0.410251 | 0.695974 | 0.695974 | 0.159320 | 0.159320 | +```` + + +Have a method to find interesting scores thresholds, typically used for error analysis, for all metrics available. +Some potentially interesting thresholds to find are: the 25th percentile, the 75th percentile, the mean , the median. + +```python +def find_thresholds(self, metrics: List[str]) -> Dict[str, float]: +``` + +```bash +data = { + "thresholds": ["25th percentile", "75th percentile", "median", "average"], + "reciprocal_rank": [0.378064, 0.534964, 0.216058, 0.778642], + "context_relevance": [0.805466, 0.410251, 0.750070, 0.361332], + "faithfulness": [0.135581, 0.695974, 0.749861, 0.041999], + "semantic_answer_similarity": [0.971241, 0.159320, 0.019722, 1], +} +```` + +Then have another method that + +```python +def find_inputs_below_threshold(self, metric: str, threshold: float): + """Get the all the queries with a score below a certain threshold for a given metric""" +``` + +# Drawbacks + +- Having the output in a format table may not be flexible enough, and maybe too verbose for datasets with a large number of queries. +- Maybe the option to export to a .csv file would be better than having the output in a table format. +- Maybe a JSON format would be better with the option for advanced users to do further analysis and visualization. + + +# Adoption strategy + +- Doesn't introduce any breaking change, it is a new feature that can be adopted by users as they see fit for their use cases. + +# How we teach this + +- A tutorial would be the best approach to teach users how to use this feature. +- Adding a new entry to the documentation. + +# User stories + +### 1. I would like to get a single summary score for my RAG pipeline so I can compare several pipeline configurations. + +Run `individual_aggregate_score_report()` and get the following output: + +```bash +{'Reciprocal Rank': 0.448, + 'Single Hit': 0.5, + 'Multi Hit': 0.540, + 'Context Relevance': 0.537, + 'Faithfulness': 0.452, + 'Semantic Answer Similarity': 0.478 + } + ``` + +### 2. I am not sure what evaluation metrics work best for my RAG pipeline, specially when using the more novel LLM-based + +Use `context relevance` or `faithfulness` + +### 3. My RAG pipeline has a low aggregate score, so I would like to see examples of specific inputs where the score was low to be able to diagnose what the issue could be. + +Let's say it's a low score in `reciprocal_rank` and one already has an idea of what "low" is a query/question, then simply run: + + find_inputs_below_threshold("reciprocal_rank", ) + +If the low score is in `reciprocal_rank` one can first get thresholds for this metric using: + + `find_thresholds(["reciprocal_rank"])` + +this will give: + +- 25th percentile: (Q1) the value below which 25% of the data falls. +- median percentile: (Q2) the value below which 50% of the data falls. +- 75th percentile: (Q3) the value below which 75% of the data falls. + +this can help to decide what is considered a low score, and then get, for instance, queries with a score below +the Q2 threshold using `find_inputs_below_threshold("context_relevance", threshold)` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-TEI-embedders-8c76593bc25a7219.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-TEI-embedders-8c76593bc25a7219.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7547ee187a315b748433c4acc45d0214979a7c16 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-answerbuilder-2.0-5dd255eeba68041f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-answerbuilder-2.0-5dd255eeba68041f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..60e79ba40de041c8af265259845e8b31eb071bfb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-apple-silicon-gpu-acceleration-38bf69781a933b95.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-apple-silicon-gpu-acceleration-38bf69781a933b95.yaml new file mode 100644 index 0000000000000000000000000000000000000000..10df92afb2c03837137230a76c07bcd3bab40109 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-apply_filter_policy-function-ae3152e6afe0ca57.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-apply_filter_policy-function-ae3152e6afe0ca57.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c890a442977a404d6bbac07322ae0c1e250c054d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure-kwargs-6a5ab1358ef7f44c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure-kwargs-6a5ab1358ef7f44c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..19e3bb0b6265e570ae6dca641b8a9f510f782f4d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure-kwargs-6a5ab1358ef7f44c.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Expose default_headers to pass custom headers to Azure API including APIM subscription key. + - | + Add optional azure_kwargs dictionary parameter to pass in parameters undefined in Haystack but supported by AzureOpenAI. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure_ocr_doc_converter-935130b3b243d236.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure_ocr_doc_converter-935130b3b243d236.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a259261574d843a412f2430690ee51d6d175d7f9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-batch_size_faiss_init-5e97c1fb9409f873.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-batch_size_faiss_init-5e97c1fb9409f873.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7d0956d68221a6ee48f4a0a6465b557954146f81 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-batch_size_faiss_init-5e97c1fb9409f873.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Add batch_size to the __init__ method of FAISS Document Store. This works as the default value for all methods of + FAISS Document Store that support batch_size. \ No newline at end of file diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-blob-type-2a9476a39841f54d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-blob-type-2a9476a39841f54d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..163d9631efa635f49252a7c39a16794d3576d4e8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-branch-joiner-037298459ca74077.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-branch-joiner-037298459ca74077.yaml new file mode 100644 index 0000000000000000000000000000000000000000..75893aa537c83f707a7de0964d81d198f9cf9438 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-calculate-metrics-metricsresults-03bf27ce8b16cff5.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-calculate-metrics-metricsresults-03bf27ce8b16cff5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ab163705b764f61e6c145369a7438cde55fe2bf2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-custom-filters-to-conditional-router-631eba8bab3c2ae7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-custom-filters-to-conditional-router-631eba8bab3c2ae7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9f4cdde9f78d57359f43cfb3c346da8e9d07a7ec --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-default-value-to-input-socket-2e62116fc4be5214.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-default-value-to-input-socket-2e62116fc4be5214.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c2cb22f98a058ba4e3ccf0c8836e41c6730a7874 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-document-writer-number-of-documents-written-2c57f3a5d6ae2131.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-document-writer-number-of-documents-written-2c57f3a5d6ae2131.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f742601594f4a64d4af706dbf2eb59fa60200480 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-dynamic-prompt-builder-e61c4b11405b8d80.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-dynamic-prompt-builder-e61c4b11405b8d80.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b5d6c53c00fb39cdb65a86494bd32323f7e08fc5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-exact-match-a7df21717238b771.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-exact-match-a7df21717238b771.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f553cac7aa92f278ef18d2122e83f3c730d1c4bc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-f1-d54cc900bec753f7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-f1-d54cc900bec753f7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6c6fcabdcd95c86fa7c098c69df58efde0536f81 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-huggingface-tgi-generator-9d7eed86f5246ea9.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-huggingface-tgi-generator-9d7eed86f5246ea9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..838351608dfba42f1ada9fa39fea74e66bb6e055 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-indexing-ready-made-pipeline-85c1da2f8f910f9d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-indexing-ready-made-pipeline-85c1da2f8f910f9d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e4e0d25c98595864c03a1fe49516ddf6e4be722 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-keep-id-to-document-cleaner-2a9854b5f195bb78.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-keep-id-to-document-cleaner-2a9854b5f195bb78.yaml new file mode 100644 index 0000000000000000000000000000000000000000..805c811d507d36b7930d306aa04ec57138660de2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-link-content-fetcher-145915976f38e1e0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-link-content-fetcher-145915976f38e1e0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f2699d40519097e161686b5754ac51006f5b5e51 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-lost-in-the-middle-ranker-6ad7dda754fad5a9.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-lost-in-the-middle-ranker-6ad7dda754fad5a9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2588daf593eb5265181b6a9defc9be78af4e0e21 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-lost-in-the-middle-ranker-976f2e9bf83c3c68.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-lost-in-the-middle-ranker-976f2e9bf83c3c68.yaml new file mode 100644 index 0000000000000000000000000000000000000000..83c9e57682c051ad7f02f0ca8f2ef725ec41f112 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-lost-in-the-middle-ranker-976f2e9bf83c3c68.yaml @@ -0,0 +1,8 @@ +--- + +features: + - | + Add 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. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-markdown-file-type-router-support-39a607faa5c1436f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-markdown-file-type-router-support-39a607faa5c1436f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e9cf3e7dda8f4b120c182f00c5dc65921dd6e8a8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-metadata-HTMLToDocument-42dbd074a46c979e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-metadata-HTMLToDocument-42dbd074a46c979e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..709a9c0f663b69bd19d11060b2cc8be975eb0ffe --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-metadata_router-2.0-63829ac5a0528e9d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-metadata_router-2.0-63829ac5a0528e9d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..58330ba0c1e06b0944bae84ba11dc7666766ca46 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-min-top-k-top-p-sampler-dc65f97d420e70b0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-min-top-k-top-p-sampler-dc65f97d420e70b0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5173f2db195dd7d74b547e81d98798af584b6227 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-min-top-k-top-p-sampler-dc65f97d420e70b0.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + The parameter min_top_k is added to the TopPSampler which sets the minimum number of documents to be returned when the top-p sampling algorithm results in fewer documents being selected. The documents with the next highest scores are added to the selection. This is useful when we want to guarantee a set number of documents will always be passed on, but allow the Top-P algorithm to still determine if more documents should be sent based on document score. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-mrr-metric-362527e55e21c24c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-mrr-metric-362527e55e21c24c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2048fcf8d7419a89ebffe2cfaa68fd03b8d6884e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-mrr-metric-362527e55e21c24c.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Add support for Mean Reciprocal Rank (MRR) Metric to `StatisticalEvaluator`. + MRR measures the mean reciprocal rank of times a label is present in at least one or more predictions. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-new-rankers-schema-generation-7ad92fd5c5de8937.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-new-rankers-schema-generation-7ad92fd5c5de8937.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b77bdf0ccb85ef9ff0b6d955d46b40359cdf35f0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-output-adapter-5fab4cfcb0218925.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-output-adapter-5fab4cfcb0218925.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fba2fdcce32b908bc40e526569fda5952f8365c2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-output-adapter-5fab4cfcb0218925.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Introducing the OutputAdapter component which enables seamless data flow between pipeline components by adapting the output of one component to match the expected input of another using Jinja2 template expressions. This addition opens the door to greater flexibility in pipeline configurations, facilitating custom adaptation rules and exemplifying a structured approach to inter-component communication. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-pptx-converter-625b745d64b3c939.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-pptx-converter-625b745d64b3c939.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3a7aa5f9622e327a66d48862219149713266b40e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-promptnode-arun-bc4c2bcc9c653015.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-promptnode-arun-bc4c2bcc9c653015.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e9e3305eab50575219caeef287ffe516bf2c88f8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-pypdf-to-document-converter-4a39c29abc4da7ba.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-pypdf-to-document-converter-4a39c29abc4da7ba.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b8fe874d51fddecbc31e671712e3166572c3a65f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-rag-openapi-services-f3e377c49ff0f258.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-rag-openapi-services-f3e377c49ff0f258.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dab28853aaf39d45bfb714e17501f16e04f8cb08 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-rag-openapi-services-f3e377c49ff0f258.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Adds RAG OpenAPI services integration. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-reno-e284cb173ab45ab3.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-reno-e284cb173ab45ab3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7008e1c37bf1368babb401e271bc4fd7f2b9e213 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-required-flag-for-prompt-builder-inputs-f5d3ffb3cb7df8d0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-required-flag-for-prompt-builder-inputs-f5d3ffb3cb7df8d0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9aad19db92bd2bea8950e00f8edee242cc6904e5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-searchapi-integration-bb9130485c3c9429.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-searchapi-integration-bb9130485c3c9429.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1cd3e046dffb98e589bf0c4098c84d5a48f49e8e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-searchapi-integration-bb9130485c3c9429.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Integrate SearchApi as an additional websearch provider. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-sentence-transformers-document-embedder-f1e8612b8eaf9b7f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-sentence-transformers-document-embedder-f1e8612b8eaf9b7f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..15689050b03b0458a0fa940e69b6eed5cb0b545a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-sentence-window-retrieval-5de4b0d6b2e8b0d6.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-sentence-window-retrieval-5de4b0d6b2e8b0d6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6679d84757bc306bea9c45baa233d0f510f63433 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-split-by-page-to-DocumentSplitter-63232c17d858d787.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-split-by-page-to-DocumentSplitter-63232c17d858d787.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3fccae32cc420be0a1baecde5d9592f2c899f026 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-top-p-sampler-ad6e0f5d623a6bb5.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-top-p-sampler-ad6e0f5d623a6bb5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..729c8b624540c47e0bb933d740dfc71594fd5285 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-transformers-text-router-5542b9d13a3c91c9.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-transformers-text-router-5542b9d13a3c91c9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bf0d7c8e82dc72768cc82f2ac2d64421e0f68cb4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-truncate-normalize-tei-6c998b14154267bb.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-truncate-normalize-tei-6c998b14154267bb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a76a4b61bb96d3e4ab5d0df1a9aa698370ea78fc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-truncate-normalize-tei-6c998b14154267bb.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Adds `truncate` and `normalize` parameters to `HuggingFaceTEITextEmbedder` and `HuggingFaceTEITextEmbedder` for allowing truncation and normalization of embeddings. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-usage-huggingfaceapi-generators-de8979cad6b6ec45.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-usage-huggingfaceapi-generators-de8979cad6b6ec45.yaml new file mode 100644 index 0000000000000000000000000000000000000000..27cde7a3088aa190df6f5655ce0db7c41e05d39f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-usage-huggingfaceapi-generators-de8979cad6b6ec45.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Adds 'usage' meta field with 'prompt_tokens' and 'completion_tokens' keys to HuggingFaceAPIChatGenerator. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-v2-answer-class-31bc8d3116922594.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-v2-answer-class-31bc8d3116922594.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e719652b49b7406bfe0bc1d8b764ac5ae25a0122 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-v2-extractive-reader-a2158d38781803ec.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-v2-extractive-reader-a2158d38781803ec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..75854604b62a4d9e800afbfffa4aebe2cc64d820 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-window-size-parameter-runtime-e841c4471f9d6b9c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-window-size-parameter-runtime-e841c4471f9d6b9c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e9d5aa2ed77c8c3fbb565a330fae505af5d36bae --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-window-size-parameter-runtime-e841c4471f9d6b9c.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + The SentenceWindowRetriever now supports the `window_size` parameter at run time, overwriting the value set in the constructor. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-yaml-marshaller-030e889f46484573.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-yaml-marshaller-030e889f46484573.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fa9663c27087e4c9d0840c3054f2b637833afa0c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/allow-simplified-pipeline-run-input-e3dd98ff38f0bc01.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/allow-simplified-pipeline-run-input-e3dd98ff38f0bc01.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6badfe24edf10c3fb19f92e632c17d020df1f982 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/async-pipeline-20649b54ecff2706.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/async-pipeline-20649b54ecff2706.yaml new file mode 100644 index 0000000000000000000000000000000000000000..58d689fff2a9f2bb5c03d66b1decef5aa8e44303 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/async-pipeline-20649b54ecff2706.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add experimental support for asynchronous `Pipeline` run diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/bedrock-support-bce28e3078c85c12.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/bedrock-support-bce28e3078c85c12.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d31ec387c491cfbff25ea54ff20d2a51902b17ef --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/better-doc-repr-6d35de1cf4b25697.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/better-doc-repr-6d35de1cf4b25697.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b4515c7f272043be40cac281b2ef1d35b8a64bf3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/better-error-FileExtensionClassifier-4defc51ed116c2a2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/better-error-FileExtensionClassifier-4defc51ed116c2a2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7177606cb487558352745d26412355ccf0fc3291 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/cache_checker_output_type-0b05e75ca41aab61.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/cache_checker_output_type-0b05e75ca41aab61.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3c14d75c9acb74beed7fe9e8a41fd05f4f570473 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/canals-0.10.0-bfa4020a8cf207c4.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/canals-0.10.0-bfa4020a8cf207c4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..34ea124b34ded291d4c4bb1c837ffd6b3c78753c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/canals-0.10.0-bfa4020a8cf207c4.yaml @@ -0,0 +1,2 @@ +preview: + - Upgrade Canals to 0.10.0 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-context-relevance-evaluator-da770bf05c83cfbd.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-context-relevance-evaluator-da770bf05c83cfbd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b530ce460022c1caec6d63c6471af106d3401869 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-default-openai-model-99ed5477500196e2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-default-openai-model-99ed5477500196e2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c4c36b33ff4fa1e90964bd861a53de96836e532e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-default-openai-model-99ed5477500196e2.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + `gpt-3.5-turbo` was replaced by `gpt-4o-mini` as the default model for all components relying on OpenAI API diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-import-paths-3d4eae690412e545.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-import-paths-3d4eae690412e545.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a285a6d68d21794886f2d358895f42fd93d9ef77 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-localwhispertranscriber-run-3b0a818060867720.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-localwhispertranscriber-run-3b0a818060867720.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b32d880caba9162de5f64ca0bfb683467b7d5075 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-trafilatura-dependency-575985a2271c8370.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/change-trafilatura-dependency-575985a2271c8370.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ff158a6c61f5a59c3f33538edc6218e38266b88f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/changed-metadata-to-meta-64cceb9ed19722fe.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/changed-metadata-to-meta-64cceb9ed19722fe.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5710841bab5624d210184d8dd2cca46e25fc7a7c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/changed-metadata-to-meta-64cceb9ed19722fe.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Rename all metadata references to meta. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/chat-with-website-template-23bec121f1a78726.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/chat-with-website-template-23bec121f1a78726.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d2ba30b4148ec89d660df09801f00081b651fdfb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/chat-with-website-template-23bec121f1a78726.yaml @@ -0,0 +1,18 @@ +--- +features: + - | + Add a new pipeline template `PredefinedPipeline.CHAT_WITH_WEBSITE` to quickly create a pipeline + that will answer questions based on data collected from one or more web pages. + + Usage example: + ```python + from haystack import Pipeline, PredefinedPipeline + + pipe = Pipeline.from_template(PredefinedPipeline.CHAT_WITH_WEBSITE) + result = pipe.run({ + "fetcher": {"urls": ["https://haystack.deepset.ai/overview/quick-start"]}, + "prompt": {"query": "How should I install Haystack?"}} + ) + + print(result["llm"]["replies"][0]) + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/check-for-None-SAS-eval-0b982ccc1491ee83.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/check-for-None-SAS-eval-0b982ccc1491ee83.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d12adfde0cbc3d89c040664df0c95fc394bc3958 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/code-instrumentation-9ef657728bec3508.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/code-instrumentation-9ef657728bec3508.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d3709c2e21fa43b5c7895afb0e9ab21b9cf1b815 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/code-instrumentation-9ef657728bec3508.yaml @@ -0,0 +1,89 @@ +--- +features: + - | + Added option to instrument pipeline and component runs. + This allows users to observe their pipeline runs and component runs in real-time via their chosen observability + tool. Out-of-the-box support for OpenTelemetry and Datadog will be added in separate contributions. + + Example usage for [OpenTelemetry](https://opentelemetry.io/docs/languages/python/): + + 1. Install OpenTelemetry SDK and exporter: + ```bash + pip install opentelemetry-sdk opentelemetry-exporter-otlp-proto-http + ``` + + 2. Configure OpenTelemetry SDK with your tracing provider and exporter: + ```python + from opentelemetry.sdk.resources import SERVICE_NAME, Resource + + from opentelemetry import trace + from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter + from opentelemetry.sdk.trace import TracerProvider + from opentelemetry.sdk.trace.export import BatchSpanProcessor + + # Service name is required for most backends + resource = Resource(attributes={ + SERVICE_NAME: "haystack" + }) + + traceProvider = TracerProvider(resource=resource) + processor = BatchSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces")) + traceProvider.add_span_processor(processor) + trace.set_tracer_provider(traceProvider) + + tracer = traceProvider.get_tracer("my_application") + + + 3. Create tracer + ```python + import contextlib + from typing import Optional, Dict, Any, Iterator + + from opentelemetry import trace + from opentelemetry.trace import NonRecordingSpan + + from haystack.tracing import Tracer, Span + from haystack.tracing import utils as tracing_utils + 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: + coerced_value = tracing_utils.coerce_tag_value(value) + self._span.set_attribute(key, coerced_value) + + + class OpenTelemetryTracer(Tracer): + def __init__(self, tracer: opentelemetry.trace.Tracer) -> None: + self._tracer = tracer + + @contextlib.contextmanager + def trace(self, operation_name: str, tags: Optional[Dict[str, Any]] = None) -> Iterator[Span]: + with self._tracer.start_as_current_span(operation_name) as span: + span = OpenTelemetrySpan(span) + if tags: + span.set_tags(tags) + + yield span + + def current_span(self) -> Optional[Span]: + current_span = trace.get_current_span() + if isinstance(current_span, NonRecordingSpan): + return None + + return OpenTelemetrySpan(current_span) + + ``` + + 4. Use the tracer with Haystack: + ```python + from haystack import tracing + + haystack_tracer = OpenTelemetryTracer(tracer) + tracing.enable_tracing(haystack_tracer) + ``` + + 5. Run your pipeline diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/codespell-d4a32b9c589ca26e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/codespell-d4a32b9c589ca26e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9fb4efa0ddee324fae5f8f8458de73f958c3296c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/codespell-d4a32b9c589ca26e.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + ci: Fix typos discovered by codespell running in pre-commit. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/compatibility-hh-hub-0.26.0-a5b61f7bf99a97b7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/compatibility-hh-hub-0.26.0-a5b61f7bf99a97b7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f12d1c3dc829fbbb8b5cad6b653b78212fb92c15 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/compatibility-hh-hub-0.26.0-a5b61f7bf99a97b7.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Adjusted a test on `HuggingFaceAPIGenerator` to ensure compatibility with the `huggingface_hub==0.26.0`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/complex-types-openapi-support-84d3daf8927ad915.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/complex-types-openapi-support-84d3daf8927ad915.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2041b74081174c5c1143b86de70d0b6dca8fe86d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/complex-types-openapi-support-84d3daf8927ad915.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Enhanced OpenAPI integration by handling complex types of requests and responses in OpenAPIServiceConnector and OpenAPIServiceToFunctions. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/connect-return-pipeline-dcc1e0786b19861e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/connect-return-pipeline-dcc1e0786b19861e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..686acfa039d0ce0426773861b1227bc746aa7dcf --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/content-tracing-25df3909e11924b1.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/content-tracing-25df3909e11924b1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ff290e9ec7c9b36b287d38f868590270b931e621 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/content-tracing-25df3909e11924b1.yaml @@ -0,0 +1,12 @@ +--- +enhancements: + - | + Allow code instrumentation to also trace the input and output of components. + This is useful for debugging and understanding the behavior of components. + This behavior is disabled by default and can be enabled with one of the following methods: + - Set the environment variable `HAYSTACK_CONTENT_TRACING_ENABLED_ENV_VAR` to `true` before importing Haystack. + - Enable content tracing in the code: + ```python + from haystack import tracing + tracing.tracer.is_content_tracing_enabled = True + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/context-relevance-04063b9dc9fe7379.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/context-relevance-04063b9dc9fe7379.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2ab79f87cfe4e901c8822da8d8db5d91ecdc769e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/custom-query-dynamic-filters-dd83ec358d2f64a6.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/custom-query-dynamic-filters-dd83ec358d2f64a6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4dc69accde0b808f62fcd430975374ff3c169143 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/datadog-tracer-b084cf64fcc575c6.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/datadog-tracer-b084cf64fcc575c6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..58d24fe537063829c91f302989b673ea5e6b218c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/datadog-tracer-b084cf64fcc575c6.yaml @@ -0,0 +1,21 @@ +--- +features: + - | + Added out-of-the-box support for the Datadog Tracer. This allows you to instrument pipeline and component + runs using Datadog and send traces to your preferred backend. + + To use the Datadog Tracer you need to have the `ddtrace` package installed in your environment. + To instruct Haystack to use the Datadog tracer, you have multiple options: + + * Run your Haystack application using the `ddtrace` command line tool as described in the + the [ddtrace documentation](https://ddtrace.readthedocs.io/en/stable/installation_quickstart.html#tracing). + This behavior can be disabled by setting the `HAYSTACK_AUTO_TRACE_ENABLED_ENV_VAR` environment variable to `false`. + * Configure the tracer manually in your code using the `ddtrace` package: + ```python + from haystack.tracing import DatadogTracer + import haystack.tracing + import ddtrace + + tracer = ddtrace.tracer + tracing.enable_tracing(DatadogTracer(tracer)) + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/default-to-from-dict-7f7d89b6c36e2ab8.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/default-to-from-dict-7f7d89b6c36e2ab8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3592483606a2f4f4a02dff8c19d6bab12d59a105 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/default-write-documents-policy-95afe5fb34fc73ad.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/default-write-documents-policy-95afe5fb34fc73ad.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d04a960ebc6420641c5bfbd02e30a2097ba7f7fd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/delete-old-eval-api-d83b3b0c83f847f3.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/delete-old-eval-api-d83b3b0c83f847f3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..232324f27479e267d0fdb7286d8b1cb99564ac1b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/delete-old-eval-api-d83b3b0c83f847f3.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Remove the old evaluation API in favor of a Component based API. + We now have `SASEvaluator` and `StatisticalEvaluator` replacing the old API. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-greedy-argument-4b8c39572f5df25c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-greedy-argument-4b8c39572f5df25c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c868a9a1930eb35a69c75d7933ae8a8b8826437e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-greedy-argument-4b8c39572f5df25c.yaml @@ -0,0 +1,13 @@ +--- +enhancements: + - | + Add new `GreedyVariadic` input type. This has a similar behaviour to `Variadic` input type + as it can be connected to multiple output sockets, though the Pipeline will run it as soon + as it receives an input without waiting for others. + This replaces the `is_greedy` argument in the `@component` decorator. + If you had a Component with a `Variadic` input type and `@component(is_greedy=True)` you need + to change the type to `GreedyVariadic` and remove `is_greedy=true` from `@component`. +deprecations: + - | + `@component` decorator `is_greedy` argument is deprecated and will be removed in version `2.7.0`. + Use `GreedyVariadic` type instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-openai-answergenerator-537266612ba1ffff.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-openai-answergenerator-537266612ba1ffff.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3e42dfacab7b3cfb2a4d000ff0926f3fc6b6bbc0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-pipeline-run-debug-param-e69190338a8e041b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-pipeline-run-debug-param-e69190338a8e041b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c6a72b8728f6670c55b9496c9d2b7d840a2b057a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-sentence-window-retrieval-9d7f8a61429a514b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-sentence-window-retrieval-9d7f8a61429a514b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0bcc5bf533d1434df764d9509e5d571dfdce5da7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/deprecate-sentence-window-retrieval-9d7f8a61429a514b.yaml @@ -0,0 +1,4 @@ +--- +deprecations: + - | + `SentenceWindowRetrieval` is deprecated and will be removed in future. Use `SentenceWindowRetriever` instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/device-management-eed64f411c48fbc7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/device-management-eed64f411c48fbc7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..72caefc41caad47de918eb1ef8092dedfccdd12f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/diversity-ranker-add-topk-24f23136f316129a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/diversity-ranker-add-topk-24f23136f316129a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5fba39f330bd4b7fdf578354b8e981c42c4c27bf --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docstore-deserialization-in-init-params-a123a39d5fbc957f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docstore-deserialization-in-init-params-a123a39d5fbc957f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1582b9b74c3630decfd271a3dc9d2e96e59644da --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docstore-deserialization-in-init-params-a123a39d5fbc957f.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Introduce an utility function to deserialize a generic Document Store + from the init_parameters of a serialized component. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-blob-ae28734c5be561d9.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-blob-ae28734c5be561d9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..596917d4301752376620a896877221f666966ca8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-joiner-2-126bd60c84be6efa.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-joiner-2-126bd60c84be6efa.yaml new file mode 100644 index 0000000000000000000000000000000000000000..13029d0ede64f4a38dc851104912cbda6953dc3e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-map-evaluator-de896c94b54fe3fa.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-map-evaluator-de896c94b54fe3fa.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c7b8532379d4b3f1cd50c53115cd28e665e2c4f9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-metadata-to-meta-8564aa3c045bb526.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-metadata-to-meta-8564aa3c045bb526.yaml new file mode 100644 index 0000000000000000000000000000000000000000..577b69a91e878f201dbfaa1b8fb6a34ce3ed2068 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-mrr-evaluator-fa7c266cc91201a7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-mrr-evaluator-fa7c266cc91201a7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..152fea593a7472df319e89a145a3d0812e980828 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-splitter-accept-split-threshold-467abb9fcd1c316b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-splitter-accept-split-threshold-467abb9fcd1c316b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..37f6bda3e70860201191dd1ce3c1f2472cf94518 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-store-testing-c1a8050f06ff3e97.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-store-testing-c1a8050f06ff3e97.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3bf89ac7fb11d22452de057dfc4d2b1fd9501e50 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-writer-default-policy-693027781629fc73.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/document-writer-default-policy-693027781629fc73.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b90629fe8be3da9cbed2f879fe518e4e9448a2ed --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docx-extract-page-breaks-09279c95f73a06f5.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docx-extract-page-breaks-09279c95f73a06f5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8aacfeaf0c18cd83025936147b3de2eaa0332e4f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docx-extract-page-breaks-09279c95f73a06f5.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fixed an issue where page breaks were not being extracted from DOCX files. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docxmetadata-json-serializable-e4205ce70d042aed.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docxmetadata-json-serializable-e4205ce70d042aed.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7a08095bf6aec8de6d062ea8641ed73af85003c0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/docxmetadata-json-serializable-e4205ce70d042aed.yaml @@ -0,0 +1,6 @@ +--- +fixes: + - | + The metadata produced by `DOCXToDocument` component is now JSON serializable. + Previously, it contained `datetime` objects automatically extracted from DOCX files, which are not JSON serializable. + Now, the `datetime` objects are converted to strings. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/embedding-instructions-4feb216cbf796678.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/embedding-instructions-4feb216cbf796678.yaml new file mode 100644 index 0000000000000000000000000000000000000000..612a3160cdf895051543193d8b886b09c5622344 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enable-set-max-length-during-runtime-097d65e537bf800b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enable-set-max-length-during-runtime-097d65e537bf800b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..32c5219fd2b3713317d519c22e7ee1925a5d9cfd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enable_pass_use_fast_to_transformers-b5fdf14d69aa58ec.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enable_pass_use_fast_to_transformers-b5fdf14d69aa58ec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..33aacb3987ffb553c9ee3e1590ba134b9c0cf516 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enforce-python-types-serde-0c5cd0a716bab7d0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enforce-python-types-serde-0c5cd0a716bab7d0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..79e3db407425ff1a8f454173e8517769055470e3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enforce-python-types-serde-0c5cd0a716bab7d0.yaml @@ -0,0 +1,8 @@ +--- +features: + - | + Improved serialization/deserialization errors to provide extra context about the delinquent components when possible. + +fixes: + - | + Serialized data of components are now explicitly enforced to be one of the following basic Python datatypes: str, int, float, bool, list, dict, set, tuple or None. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhance-pipeline-draw-5fe3131db71f6f54.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhance-pipeline-draw-5fe3131db71f6f54.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8f586b90fba04d4ccda30b0fd1b66ccf57e72ec4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhance-pipeline-draw-5fe3131db71f6f54.yaml @@ -0,0 +1,7 @@ +--- +enhancements: + - | + Add new `Pipeline.show()` method to generated image inline if run in a Jupyter notebook. + If called outside a notebook it will raise a `PipelineDrawingError`. + `Pipeline.draw()` has also been simplified and the `engine` argument has been removed. + Now all images will be generated using Mermaid. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhance-repr-0c5efa1e2ca6bafa.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhance-repr-0c5efa1e2ca6bafa.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a9f1914efcf0c3a173af42df6eaed5f1a8003aa2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/enhance-repr-0c5efa1e2ca6bafa.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Customize `Pipeline.__repr__()` to return a nice text representation of it. + If run on a Jupyter notebook it will instead have the same behaviour as `Pipeline.show()`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/exact-match-evaluator-197bb87b65e19d0c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/exact-match-evaluator-197bb87b65e19d0c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c872542bee3f14482eb45a3663ed805923443f2d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/faithfulness-evaluator-2e039a697c847d1c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/faithfulness-evaluator-2e039a697c847d1c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5279d0d9c8814647a981f5d300ffc0ce95b2c969 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/faithfulness-evaluator-2e039a697c847d1c.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Add a new FaithfulnessEvaluator component that can be used to evaluate faithfulness / groundedness / hallucinations of LLMs in a RAG pipeline. + Given a question, a list of retrieved document contents (contexts), and a predicted answer, FaithfulnessEvaluator returns a score ranging from 0 (poor faithfulness) to 1 (perfect faithfulness). + The score is the proportion of statements in the predicted answer that could by inferred from the documents. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/feat-documentsplitter-add-split-by-function-77501f439b63bb49.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/feat-documentsplitter-add-split-by-function-77501f439b63bb49.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e8b170442abdb39582594bc7e494c29bbbac18af --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/feat-documentsplitter-add-split-by-function-77501f439b63bb49.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Added the option to use a custom splitting function in DocumentSplitter. The function must accept a string as + input and return a list of strings, representing the split units. To use the feature initialise `DocumentSplitter` + with `split_by="function"` providing the custom splitting function as `splitting_function=custom_function`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/file-router-additional-mime-types-47fe57e6816b83da.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/file-router-additional-mime-types-47fe57e6816b83da.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5d5b8a9d997bec2ac0b23fd9f3597380c358f7e2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/file-router-additional-mime-types-47fe57e6816b83da.yaml @@ -0,0 +1,22 @@ +--- +features: + - | + Added a new parameter `additional_mimetypes` to the FileTypeRouter + component. + + This allows users to specify additional MIME type mappings, ensuring + correct + + file classification across different runtime environments and Python + versions. +enhancements: + - | + Improved file type detection in FileTypeRouter, particularly for Microsoft + Office file formats like .docx and .pptx. This enhancement ensures more + consistent behavior across different environments, including AWS Lambda + functions and systems without pre-installed office suites. +fixes: + - | + Addressed an issue where certain file types (e.g., .docx, .pptx) were + incorrectly classified as 'unclassified' in environments with limited + MIME type definitions, such as AWS Lambda functions. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/filters-converter-485cd24cf38407d0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/filters-converter-485cd24cf38407d0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..49cca08828237da1a79d82d0632d571edc3365b2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-azure-ocr-bytestream-meta-0d2c8e6ea761b791.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-azure-ocr-bytestream-meta-0d2c8e6ea761b791.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b0f6ad9c85702af18a3c9d90aef4eca7947f1fa2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-chat-prompt-builder-from-dict-template-none-56c91effe61e823c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-chat-prompt-builder-from-dict-template-none-56c91effe61e823c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9cb1ae0f387d9ed69209f84d8109ec83eec2d294 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-chat-prompt-builder-from-dict-template-none-56c91effe61e823c.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix ChatPromptBuilder from_dict method when template value is None. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-chat-web-pipe-template-0b00144b1099cda3.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-chat-web-pipe-template-0b00144b1099cda3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..60b2f90a411c8218748ff812683e54fe774b523b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-chat-web-pipe-template-0b00144b1099cda3.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Update the `CHAT_WITH_WEBSITE` Pipeline template to reflect the changes in + the `HTMLToDocument` converter component. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-component-type-checking-issues-8eefa1157ffc3eba.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-component-type-checking-issues-8eefa1157ffc3eba.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a8e3aaf016390e148ab7838ad9f2b68555e63eed --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-component-type-checking-issues-8eefa1157ffc3eba.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Update `Component` protocol to fix type checking issues with some Language Servers. + Most Language Servers and some type checkers would show warnings when calling `Pipeline.add_component()` + as technically most `Component`s weren't respecting the protocol we defined. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-splitter-split-info-1704f16c8b0f374a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-document-splitter-split-info-1704f16c8b0f374a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..87108281ba96589fc12f392bf5104b166106523d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-e2e-test-preprocessing-7b24f848e074c48a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-e2e-test-preprocessing-7b24f848e074c48a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..99e6d5242bef804b007d5640f1f65c6ea1b9eb6d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-entityextractor-json-serialzable-b7d643eb83a3e58c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-entityextractor-json-serialzable-b7d643eb83a3e58c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ad1415b8faa0ec2cea2fdb58cd023ef17bc9eb9d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-entityextractor-json-serialzable-b7d643eb83a3e58c.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix EntityExtractor output not JSON serializable. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-hf-api-serialization-026b84de29827c57.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-hf-api-serialization-026b84de29827c57.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5fa7d9c3cf04a091891aba635d93215a33290bfe --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-issue-7758-d35b687ca226a707.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-issue-7758-d35b687ca226a707.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b1accdd2ac6c927e33dd74dcb34d50092f6aa80b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-issue-7758-d35b687ca226a707.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fixed the calculation for MRR and MAP scores. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-joinDocuments-concatenate-56a7cdba00a7248e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-joinDocuments-concatenate-56a7cdba00a7248e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e282f7b9fb1cef12d49763947171b98a964cbc2a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-llmevaluator-subclass-deserialization-c633b2f95c84fe4b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-llmevaluator-subclass-deserialization-c633b2f95c84fe4b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8a2adbca7886f24632ae60b84aeb070e3336b967 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-named-entity-entity-extractor-backend-enum-2e64e25f8d7f1b08.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-named-entity-entity-extractor-backend-enum-2e64e25f8d7f1b08.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0df95101c8557d8b835517b1e727ef6613d8954e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pipe-rendering-50261e0472f0d267.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pipe-rendering-50261e0472f0d267.yaml new file mode 100644 index 0000000000000000000000000000000000000000..59bb282f5f6e4a09d38a5a24ee811ced6d594c10 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pipe-rendering-50261e0472f0d267.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix the Pipeline visualization issue due to changes in the new release of Mermaid. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pipeline-run-disorder-382da1e6bd6db510.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pipeline-run-disorder-382da1e6bd6db510.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5255e6038e873652200432561635661187d8734 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pipeline-run-disorder-382da1e6bd6db510.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + Fixes `Pipeline.run()` logic so Components that have all their inputs with a default are run in the correct order. + This happened we gather a list of Components to run internally when running the Pipeline in the order they are + added during creation of the Pipeline. + This caused some Components to run before they received all their inputs. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pypdf-serialization-93744fd01ef5b841.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-pypdf-serialization-93744fd01ef5b841.yaml new file mode 100644 index 0000000000000000000000000000000000000000..04d042c6fdb8885f53abc5fbd5889296c5157271 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-recursive-json-schema-validator-cdb7684de3c75e4e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-recursive-json-schema-validator-cdb7684de3c75e4e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c24e687005d93e3fce6ce056c9aebafcb4369aaf --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-run-loop-63bf0ffc26887e66.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-run-loop-63bf0ffc26887e66.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9ec3525cd8af1b04c3b5e131c236bb830d87e2fb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-run-loop-63bf0ffc26887e66.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + Fix a bug in `Pipeline.run()` that would cause it to get stuck in an infinite loop and never return. + + This was caused by Components waiting forever for their inputs when parts of the Pipeline graph are skipped + cause of a "decision" Component not returning outputs for that side of the Pipeline. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-sentence-window-retriever-filter-b7b136eedf6e8488.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-sentence-window-retriever-filter-b7b136eedf6e8488.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3e29f416d2626ed8790690a9fc8ec62d445cc535 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-sentence-window-retriever-filter-b7b136eedf6e8488.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fixing the filters in the `SentenceWindowRetriever` allowing now support for 3 more DocumentStores: Astra, PGVector, Qdrant diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-serialization-openai-generator-cf7e9a04562dde75.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-serialization-openai-generator-cf7e9a04562dde75.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5e815b68b0115460204480beff41b75d13140b80 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-splitter-cleaner-hash-key-3b6f042af7da9ab4.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-splitter-cleaner-hash-key-3b6f042af7da9ab4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..33708f0b4dd5fd6113ff6d94be898cf4c54e12de --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-stop-words-strip-issue-22ce51306e7b91e4.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-stop-words-strip-issue-22ce51306e7b91e4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3dab779ede30cd4775552cc527c5b373f5adc77f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-tika-page_number-2d600b2dc8a4faa7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-tika-page_number-2d600b2dc8a4faa7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e66f4229585418298308e94c7cd6032cfbe00291 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-tika-page_number-2d600b2dc8a4faa7.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + `TikaDocumentConverter` now returns page breaks ("\f") in the output. + This only works for PDF files. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-transformersranker-single-doc-12448c3d7bc8dc6c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-transformersranker-single-doc-12448c3d7bc8dc6c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5dffe1ebfaf660372624b808e4554c26e35a1c0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-weaviate-date-fields-request-bottleneck-d9784b7e1044cacd.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/fix-weaviate-date-fields-request-bottleneck-d9784b7e1044cacd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d40fe7c5bae3bd46da74169b42d7b7b496f60bf4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/force-valid-JSON-OpeanAI-LLM-based-evaluators-64816e68f137739b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/force-valid-JSON-OpeanAI-LLM-based-evaluators-64816e68f137739b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..19e1ddb15ca93f46a26fae831b4ac5ee90bea596 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/generators-module-261376beb9c031cc.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/generators-module-261376beb9c031cc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0c57e6bc7b0181ebc9a0b35469ce787f93691149 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/generators-module-261376beb9c031cc.yaml @@ -0,0 +1,2 @@ +preview: + - Add generators module for LLM generator components. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/gpt4-llm-generator-60708087ec42211f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/gpt4-llm-generator-60708087ec42211f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fb67de3ccda1c4090be57c21f3f4110bd689ceab --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/gpt4-llm-generator-60708087ec42211f.yaml @@ -0,0 +1,3 @@ + +preview: + - Adds `GPT4Generator`, an LLM component based on `GPT35Generator` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hf-tei-bug-fix-07732c672600aadd.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hf-tei-bug-fix-07732c672600aadd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7fd5fd1787757b51f3bbcac95ba288cbd0f0ce76 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hf-tei-bug-fix-07732c672600aadd.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Fixes `HuggingFaceTEITextEmbedder` returning an embedding of incorrect shape when used with a + Text-Embedding-Inference endpoint deployed using Docker. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hfapitextembedder-97bf5f739f413f3e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hfapitextembedder-97bf5f739f413f3e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1f8ac29deef7c5d16e1098f8c1b58050a52e123e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hflocalgenerator-generation-kwargs-in-run-2bde10d398a3712a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hflocalgenerator-generation-kwargs-in-run-2bde10d398a3712a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cf605f9c38faab82e0d762bfccce023b49abe220 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hugging-face-local-generator-a9a0ba011506f932.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hugging-face-local-generator-a9a0ba011506f932.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2038626f3dedaf3a3517d55fbcdef12d8d9fe591 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hugging-face-local-generator-streaming-callback-38a77d37199f9672.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hugging-face-local-generator-streaming-callback-38a77d37199f9672.yaml new file mode 100644 index 0000000000000000000000000000000000000000..47b1f6776eb2df524459257ac30fa002cdc2e0fb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/hugging-face-local-generator-streaming-callback-38a77d37199f9672.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Adds 'streaming_callback' parameter to 'HuggingFaceLocalGenerator', allowing users to handle streaming responses. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/implement-merge-filter-logic-99e6785a78f80ae9.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/implement-merge-filter-logic-99e6785a78f80ae9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c90479c2c61724a4ca5853b932c44643b641d54a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/implement-merge-filter-logic-99e6785a78f80ae9.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Enhanced filter application logic to support merging of filters. It facilitates more precise retrieval filtering, allowing for both init and runtime complex filter combinations with logical operators. For more details see https://docs.haystack.deepset.ai/docs/metadata-filtering diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-ContextRelevance-evaluator-prompt-6b80229c99e3bc38.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-ContextRelevance-evaluator-prompt-6b80229c99e3bc38.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3dd7e8342b62a04beaed49d3ee8da2f15fe3a146 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-hf-invocation-layer-tests-c42250d11d1d06c1.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-hf-invocation-layer-tests-c42250d11d1d06c1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7e1329af398ce253b78b48f2b2098ba3e8a72377 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-hf-invocation-layer-tests-c42250d11d1d06c1.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Minor PromptNode HFLocalInvocationLayer test improvements diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-pipeline-run-tracing-1d80aa7810df4205.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/improve-pipeline-run-tracing-1d80aa7810df4205.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c25257fd3730e6f7e6e3f65c65fdaead1aefe2ea --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/inmemorybm25retriever-zero-score-docs-67406062a76aa7f4.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/inmemorybm25retriever-zero-score-docs-67406062a76aa7f4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3ae440162aa8bfdea777651791f0d87a29d9479f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/issue-5616-convert-files-to-docs-list-f75a057249ba8992.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/issue-5616-convert-files-to-docs-list-f75a057249ba8992.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f1f05697db3f6901b98d2bae5a475172af66cfa8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/json-converter-a747e9c44543dfb5.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/json-converter-a747e9c44543dfb5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f8a269d2c0cded144dc738fec18ffeab5d11aed4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/json-converter-a747e9c44543dfb5.yaml @@ -0,0 +1,48 @@ +--- +features: + - | + Add new `JSONConverter` Component to convert JSON files to `Document`. + Optionally it can use jq to filter the source JSON files and extract only specific parts. + + ```python + import json + + from haystack.components.converters import JSONConverter + from haystack.dataclasses import ByteStream + + data = { + "laureates": [ + { + "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", + }, + { + "firstname": "Rita", + "surname": "Levi-Montalcini", + "motivation": "for their discoveries of growth factors", + }, + ], + } + source = ByteStream.from_string(json.dumps(data)) + converter = JSONConverter( + jq_schema=".laureates[]", content_key="motivation", extra_meta_fields=["firstname", "surname"] + ) + + results = converter.run(sources=[source]) + documents = results["documents"] + print(documents[0].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' + + print(documents[0].meta) + # {'firstname': 'Enrico', 'surname': 'Fermi'} + + print(documents[1].content) + # 'for their discoveries of growth factors' + + print(documents[1].meta) + # {'firstname': 'Rita', 'surname': 'Levi-Montalcini'} + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/link-content-fetcher-enhancements-49babe1c60888043.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/link-content-fetcher-enhancements-49babe1c60888043.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6a7d2428582b1f63bd922c303382bce3b5bb9d5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/llm-evaluator-serde-fix-aa5b27d2524db9c5.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/llm-evaluator-serde-fix-aa5b27d2524db9c5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aabfaaa6c722903d488307b54ed4e7d895702040 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/llmevaluator-0ae63b2b9715fb9b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/llmevaluator-0ae63b2b9715fb9b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3b68f16a33c5402346f44ef1ebfa44936780925a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/llmevaluator-0ae63b2b9715fb9b.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add a new LLMEvaluator component that leverages LLMs through the OpenAI api to evaluate pipelines. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/logging-tracer-e991a43ef44fe906.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/logging-tracer-e991a43ef44fe906.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c44382db93628fa337ae8ab6a699f6f4e9decdab --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/logging-tracer-e991a43ef44fe906.yaml @@ -0,0 +1,20 @@ +--- +highlights: > + With the new Logging Tracer, users can inspect in the logs everything + that is happening in their Pipelines in real time. This feature aims to + improve the user experience during experimentation and prototyping. +features: + - | + Introduce a Logging Tracer, that sends all traces to the logs. + + It can enabled as follows: + ```python + import logging + from haystack import tracing + from haystack.tracing.logging_tracer import LoggingTracer + + logging.basicConfig(format="%(levelname)s - %(name)s - %(message)s", level=logging.WARNING) + logging.getLogger("haystack").setLevel(logging.DEBUG) + tracing.tracer.is_content_tracing_enabled = True # to enable tracing/logging content (inputs/outputs) + tracing.enable_tracing(LoggingTracer()) + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/logging-tty-detection-8136769cb4d1da67.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/logging-tty-detection-8136769cb4d1da67.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8493fe964835b5c0a8d6357d429c8ebfe929dece --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/logging-tty-detection-8136769cb4d1da67.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + The `logging` module now detects if the standard output is a TTY. If it is not and `structlog` is installed, it + will automatically disable the console renderer and log in JSON format. This behavior can be overridden by setting + the environment variable `HAYSTACK_LOGGING_USE_JSON` to `false`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/make-from-dict-more-robust-for-conditionalrouter-c6ed6f841ad8e58d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/make-from-dict-more-robust-for-conditionalrouter-c6ed6f841ad8e58d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2cc64cc06448c14591bb406229fc3f8aca92f6c1 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/make-from-dict-more-robust-for-conditionalrouter-c6ed6f841ad8e58d.yaml @@ -0,0 +1,6 @@ +--- +fixes: + - | + The `from_dict` method of `ConditionalRouter` now correctly handles + the case where the `dict` passed to it contains the key `custom_filters` explicitly + set to `None`. Previously this was causing an `AttributeError` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/make-warm-up-consistent-0247da81b155b136.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/make-warm-up-consistent-0247da81b155b136.yaml new file mode 100644 index 0000000000000000000000000000000000000000..49cc2a91a120c23e1ad9850c7d93ad0bc48e9833 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/max-loops-in-run-df9f5c068a723f71.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/max-loops-in-run-df9f5c068a723f71.yaml new file mode 100644 index 0000000000000000000000000000000000000000..00c6d3a5db2ee2f8d9cc5ca73d2d72dcb579db29 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/max-loops-in-run-df9f5c068a723f71.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Change `Pipeline.run()` to check if `max_loops_allowed` has been reached. + If we attempt to run a Component that already ran the number of `max_loops_allowed` a `PipelineMaxLoops` will be raised. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/max_retries-for-AzureOpenAIChatGenerator-9e49b4c7bec5c72b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/max_retries-for-AzureOpenAIChatGenerator-9e49b4c7bec5c72b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..888a53a8dbd488e6d2871fbff9186f2a88ecdc4b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/merge-hf-utils-modules-5c16e04025123568.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/merge-hf-utils-modules-5c16e04025123568.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d57cdfcd70fd8634b473d204c96ccb03b07178d0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/metadata_enhancement_for_SQuAD_files-2247c72f07760465.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/metadata_enhancement_for_SQuAD_files-2247c72f07760465.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ed90d46a25f8a8460d599cf7ccce902a5e4571c8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/metafieldranker-meta-value-type-365ff1bdb412257b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/metafieldranker-meta-value-type-365ff1bdb412257b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f2be1fb87a4fd7363ea6ca8fc9095fadd4a49fe3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/metafieldranker-meta-value-type-365ff1bdb412257b.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Add a new variable called meta_value_type to the MetaFieldRanker that allows a user to parse the meta value into the data type specified as along as the meta value is a string. + The supported values for meta_value_type are '"float"', '"int"', '"date"', or 'None'. If None is passed then no parsing is done. + For example, if we specified meta_value_type="date" then for the meta value "date": "2015-02-01" we would parse the string into a datetime object. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/named-entity-extractor-component-8fd647ee748892ca.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/named-entity-extractor-component-8fd647ee748892ca.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2d9adfead0088bc7c922b3db37eda34306323ad5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/named-entity-extractor-serde-improvements-28b594be5a38f175.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/named-entity-extractor-serde-improvements-28b594be5a38f175.yaml new file mode 100644 index 0000000000000000000000000000000000000000..af37a9c369117bc034727995f2772d6b131f66f9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/new-document-f7072e3f6d93e10f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/new-document-f7072e3f6d93e10f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..66774e25f16e424643af6819556c09f65f118c72 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/nltk-document-splitting-enhancement-6ef6f59bc277662c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/nltk-document-splitting-enhancement-6ef6f59bc277662c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d97027b30b97a854fc342d589409b97a8d0ed699 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/nltk-document-splitting-enhancement-6ef6f59bc277662c.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Introduced a new NLTK document splitting component, enhancing document preprocessing capabilities. This feature allows for fine-grained control over the splitting of documents into smaller parts based on configurable criteria such as word count, sentence boundaries, and page breaks. It supports multiple languages and offers options for handling sentence boundaries and abbreviations, facilitating better handling of various document types for further processing tasks. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/openai-document-embedder-d2f59ba1f21babcb.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/openai-document-embedder-d2f59ba1f21babcb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eaf44199c6d9a21685f8bb43304cfc9de989d3ea --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/openapi-service-connector-enhancements-21a2bc0a9aab8966.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/openapi-service-connector-enhancements-21a2bc0a9aab8966.yaml new file mode 100644 index 0000000000000000000000000000000000000000..85d82ddfb7166df4b58c1e7b9a092a6a75c62997 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/openapi-service-connector-enhancements-21a2bc0a9aab8966.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Enhanced OpenAPI service connector to better handle method invocation with support for security schemes, refined handling of method arguments including URL/query parameters and request body, alongside improved error validation for method calls. This update enables more versatile interactions with OpenAPI services, ensuring compatibility with a wide range of API specifications. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/optimize-pinecone-document-store.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/optimize-pinecone-document-store.yaml new file mode 100644 index 0000000000000000000000000000000000000000..664e789a9b86c12b7d872724a36ffd43797f4603 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pass-id-to-doc-init-c6b44d30978f2d9f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pass-id-to-doc-init-c6b44d30978f2d9f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b8318be9f8b2952a057fe09a5c06d7d795fce413 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pip-test-dep-b797879f1d73b3eb.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pip-test-dep-b797879f1d73b3eb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..25e874dbd9f9ff12d22c218d7e5ce50e799fa98f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pip-test-dep-b797879f1d73b3eb.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Add `pip` to test dependencies: `mypy` needs it to install missing stub packages. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipe-disable-autoshow-dbbafd2bfdcce7a4.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipe-disable-autoshow-dbbafd2bfdcce7a4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3acc6c69328becf8ac017a5f021a8d40ca4f93de --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipe-disable-autoshow-dbbafd2bfdcce7a4.yaml @@ -0,0 +1,7 @@ +--- +enhancements: + - | + In Jupyter notebooks, the image of the Pipeline will no longer be displayed automatically. + The textual representation of the Pipeline will be displayed. + + To display the Pipeline image, use the `show` method of the Pipeline object. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-hierarchy-b980efcf8ac6b122.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pipeline-hierarchy-b980efcf8ac6b122.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7b0fd4a2e133b52b9733f3c6fbeef9775bb5c3b9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pptx-file-converter-3e494d2747637eb2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pptx-file-converter-3e494d2747637eb2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6090da6d44e77e21263283974e29eaee2fe1a2fb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pptx-import-edc6b8d6274e4023.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pptx-import-edc6b8d6274e4023.yaml new file mode 100644 index 0000000000000000000000000000000000000000..51458eb6fdfed651829fa870234636fe8abeeb74 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pptx-import-edc6b8d6274e4023.yaml @@ -0,0 +1,4 @@ +--- + fixes: + - | + Correctly expose `PPTXToDocument` component in `haystack` namespace. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/prompt-builder-d22954ef9c4a2a7b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/prompt-builder-d22954ef9c4a2a7b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e9561c44e876dc88da6eb08cdff2c431224cb51 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/prompt-builder-d22954ef9c4a2a7b.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Add PromptBuilder component to render prompts from template strings diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-refactoring-de869c91b42ce5b6.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-refactoring-de869c91b42ce5b6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..464528b64a5dc564310fdb9d86231d1f47b8e929 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-refactoring-de869c91b42ce5b6.yaml @@ -0,0 +1,12 @@ +--- +enhancements: + - | + Refactor `PyPDFToDocument` to simplify support for custom PDF converters. + PDF converters are classes that implement the `PyPDFConverter` protocol and have 3 methods: + `convert`, `to_dict` and `from_dict`. + The `DefaultConverter` class is provided as a default implementation. +deprecations: + - | + Using the `converter_name` parameter in the `PyPDFToDocument` component is deprecated. + It will be removed in the 2.3.0 release. + Use the `converter` parameter instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-serde-fixes-f33c29830508ee01.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-serde-fixes-f33c29830508ee01.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ba923793778b64341d476f4b9a44f2c71e17b405 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/pypdf-serde-fixes-f33c29830508ee01.yaml @@ -0,0 +1,7 @@ +--- +deprecations: + - | + The `DefaultConverter` class used by the `PyPDFToDocument` component has been deprecated. Its functionality will be merged into the component in 2.7.0. +fixes: + - | + Fix the serialization of `PyPDFToDocument` component to prevent the default converter from being serialized unnecessarily. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rag-e2e-test-rename-3e2c7265dbb6ba9e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rag-e2e-test-rename-3e2c7265dbb6ba9e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8b741ae61dee5af056316be29cee24ada29d4841 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rag_pipeline-4e9dfc82a4402935.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rag_pipeline-4e9dfc82a4402935.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aa9049a2e2d6def65d9db122db31ee150f1023cc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rag_pipeline-4e9dfc82a4402935.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add a `build_rag_pipeline` utility function diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/ranker-prefix-bfaf09cd7da0852d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/ranker-prefix-bfaf09cd7da0852d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9431fda1bbad3f58e0f68532bc18d5195a392c40 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/ranker-prefix-bfaf09cd7da0852d.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Add query and document prefix options for the TransformerSimilarityRanker diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-document-store-namespace-33f4433a2b121efc.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-document-store-namespace-33f4433a2b121efc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e003254d764f27e51a1d74dbe7aa6ef417e217a8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-document-store-namespace-33f4433a2b121efc.yaml @@ -0,0 +1,17 @@ +--- +upgrade: + - | + Change the imports for in_memory document store and retrievers from: + + from haystack.document_stores import InMemoryDocumentStore + from haystack.components.retrievers import InMemoryEmbeddingRetriever + + to: + + from haystack.document_stores.in_memory import InMemoryDocumentStore + from haystack.components.retrievers.in_memory import InMemoryBM25Retriever + +enhancements: + - | + Stop exposing `in_memory` package symbols in the `haystack.document_store` and + `haystack.components.retrievers` root namespaces. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-openai-document-embedder.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-openai-document-embedder.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e3c337c89ce23d80f452aee4908b365394a4abe7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-pinecone-document-store.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-pinecone-document-store.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b8145ac50b89b9850053733e27e9c3131009ec12 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-sentense-transformers-document-embedder-f4ed8d10aaccd08c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/refactor-sentense-transformers-document-embedder-f4ed8d10aaccd08c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..325a7f8951f0f1a998aa0457ff9901bf84168505 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/release-note-2b603a123cd36214.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/release-note-2b603a123cd36214.yaml new file mode 100644 index 0000000000000000000000000000000000000000..91db94a58aa5acf2c1887d253e0ba50d06f3a664 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/release-note-2b603a123cd36214.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Add `truncate_dim` parameter to Sentence Transformers Embedders, which allows truncating + embeddings. Especially useful for models trained with Matryoshka Representation Learning. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remotetranscriber-input-type-aae9a255435a3507.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remotetranscriber-input-type-aae9a255435a3507.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3ca8b5bcd19af8eb4c5ab18b784a7154c54b3488 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-canals-mentions-eac7f95df99d39b9.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-canals-mentions-eac7f95df99d39b9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a5651352324c7fc36ecb1acb8fbfb4310a6b5fad --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-debug-path-68e9b2e41d7d43fd.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-debug-path-68e9b2e41d7d43fd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..046a4ece02da289399273f90573ef1828c107cb4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-debug-path-68e9b2e41d7d43fd.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + Removed `Pipeline` init argument `debug_path`. We do not support this anymore. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-default-from-dict-reimplementation-2db4c32153c1e7af.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-default-from-dict-reimplementation-2db4c32153c1e7af.yaml new file mode 100644 index 0000000000000000000000000000000000000000..852eaa8f0b31a0857d745a4429f363338b22bd2f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-deprecated-multiplexer-1f948f1f9b811195.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-deprecated-multiplexer-1f948f1f9b811195.yaml new file mode 100644 index 0000000000000000000000000000000000000000..87f92d21c05c3da489090134b39f51c2ade9bb18 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-deprecated-multiplexer-1f948f1f9b811195.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + `Multiplexer` is removed and users should switch to `BranchJoiner` instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-deprecated-pipeline-run-debug-eab0c31ea0ce513d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-deprecated-pipeline-run-debug-eab0c31ea0ce513d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..45704def4cb19c37692ad10f3f6357703a6cb566 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-deprecated-pipeline-run-debug-eab0c31ea0ce513d.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + Remove unused `debug` parameter from `Pipeline.run` method. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-document-array-fe70fd2cbb269add.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-document-array-fe70fd2cbb269add.yaml new file mode 100644 index 0000000000000000000000000000000000000000..64a326e21d55e613df1cb1e87d892395aa553c08 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-document-array-fe70fd2cbb269add.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Remove `array` field from `Document` dataclass. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-gptgenerator-8eced280d3b720d3.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-gptgenerator-8eced280d3b720d3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..694db015eb86fba773edaac486d1692405600d81 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-gptgenerator-8eced280d3b720d3.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + Removed the deprecated GPTGenerator and GPTChatGenerator components. Use OpenAIGenerator and OpenAIChatGeneratornotes instead. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-id-hash-document-93e4a589b3fd2aad.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-id-hash-document-93e4a589b3fd2aad.yaml new file mode 100644 index 0000000000000000000000000000000000000000..707b8f642a3957abbeae8fceadee2fc21aa6b5fc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-image-from-debug-c83d61db92bcbfc2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-image-from-debug-c83d61db92bcbfc2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6c817bd84238967effcf9fb5ec8d1154b82c18a4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-legacy-filters-ff89cd0a00a64ce9.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-legacy-filters-ff89cd0a00a64ce9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..da33cd069d77c02c1c9d9742273fa77a77aa2bef --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-legacy-filters-ff89cd0a00a64ce9.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + The legacy filter syntax support has been completely removed. Users need to use the new filter syntax. See the [docs](https://docs.haystack.deepset.ai/docs/metadata-filtering) for more details. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-pipeline-c02067516c387f0b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-pipeline-c02067516c387f0b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8be791c6ffda8813ba18d0d5e46b6eab74701762 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-pipeline-c02067516c387f0b.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Remove Pipeline specialisation to support DocumentStores. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-sklearnqueryclassifier-a95382808d99cb58.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/remove-sklearnqueryclassifier-a95382808d99cb58.yaml new file mode 100644 index 0000000000000000000000000000000000000000..016449275babf957ac77a3cc9507c27d4747a237 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-connect-arguments-2d99d9d5cbe9ab4c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-connect-arguments-2d99d9d5cbe9ab4c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8d242c5b6cb04e63b4dbd5445dc7ec4e5fbf79e0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-connect-arguments-2d99d9d5cbe9ab4c.yaml @@ -0,0 +1,10 @@ +--- +upgrade: + - | + `Pipeline.connect()` arguments have renamed for clarity. This is a breaking change if `connect` was called + with keyword arguments only. + `connect_from` and `connect_to` arguments have been renamed respectively to `sender` and `receiver`. + The behaviour of `Pipeline.connect()` is not changed. +features: + - | + Rename `Pipeline.connect()` arguments for clarity diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-gpt-generators-f25011d251fafd6d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-gpt-generators-f25011d251fafd6d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..72f40559fe0cabe0edada881820d6484d717093b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-model-param-ner-dce7536f2e7866fe.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-model-param-ner-dce7536f2e7866fe.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ae6e36ed0ac15cf64b7326e594f059f47c459e8e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-model-param-reader-b8cbb0d638e3b8c2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-model-param-reader-b8cbb0d638e3b8c2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6a5bd3eef63155987b2ce92f8266299478907957 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-sentence-window-retrieval-be4cd6e1d18ef10e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-sentence-window-retrieval-be4cd6e1d18ef10e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..098f6a58c992bd271c726307e60b6574f88e1809 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rename-sentence-window-retrieval-be4cd6e1d18ef10e.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + `SentenceWindowRetrieval` component has been renamed to `SenetenceWindowRetriever`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/restrict-openai-supports-method-fb126583e4beb057.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/restrict-openai-supports-method-fb126583e4beb057.yaml new file mode 100644 index 0000000000000000000000000000000000000000..88e17d0ab273e3c9c34e65c139b8e501a12ab541 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/retrievers-filter-policy-enhancement-af52d026c346e9c0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/retrievers-filter-policy-enhancement-af52d026c346e9c0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5f9b023339fb2693d278df353f9f9d9af77b3f36 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/review-all-extras-42d5a3a3d61f5393.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/review-all-extras-42d5a3a3d61f5393.yaml new file mode 100644 index 0000000000000000000000000000000000000000..80a9fcddc1d1cb6066ca16fb78237b50d97be9d7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rework-filters-1bb103d196a1912b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rework-filters-1bb103d196a1912b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..57509ec3342fc34ee9c8989eb8d02896921ee2ce --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rework-memory-retriever-73c5d3221bd96759.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/rework-memory-retriever-73c5d3221bd96759.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0824e17a7c2f1b11703706aa850e97d6d953869f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/route-meta-to-converters-ed85acc43b5aa96a.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/route-meta-to-converters-ed85acc43b5aa96a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..73f67d99b4ac0d5ca3aa654bb6f541604abd08b2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/run-greedy-fix-6d4559126e7739ce.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/run-greedy-fix-6d4559126e7739ce.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d597121f7c91f986b49a47c4cf1e218fa2e3c6fe --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/run-greedy-fix-6d4559126e7739ce.yaml @@ -0,0 +1,6 @@ +--- +fixes: + - | + Fix `Pipeline.run()` mistakenly running a Component before it should. + This can happen when a greedy variadic Component must be executed before a + Component with default inputs. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/scale-score-similarity-ranker-2deacff999265b9e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/scale-score-similarity-ranker-2deacff999265b9e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8b7f26d2922193d00a5ec664ff2d95fa933d556a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/self-correcting-rag-2e77ac94b89dfe5b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/self-correcting-rag-2e77ac94b89dfe5b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f0d3c1f92b4c12a264fd43567447611f6e1e288c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/self-correcting-rag-2e77ac94b89dfe5b.yaml @@ -0,0 +1,2 @@ +enhancements: + - Add RAG self correction loop example diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformer-doc-embedder-config_kwargs-d7d254c6b94887c4.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformer-doc-embedder-config_kwargs-d7d254c6b94887c4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8693b75a5083cbd9f082649c56ee5fb6ed411ebd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformer-doc-embedder-config_kwargs-d7d254c6b94887c4.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + SentenceTransformersDocumentEmbedder now supports config_kwargs for additional parameters when loading the model configuration diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformers-text-embedder-config_kwargs-11f10429e25a3a6e.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformers-text-embedder-config_kwargs-11f10429e25a3a6e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9409b09e6d51f489db378e71c14a2ddd213b5a2d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sentence-transformers-text-embedder-config_kwargs-11f10429e25a3a6e.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + SentenceTransformersTextEmbedder now supports config_kwargs for additional parameters when loading the model configuration diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/serialization-tuple-support-ffe176417e7099f5.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/serialization-tuple-support-ffe176417e7099f5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a3053ee6f2c2827c3523e6ff8bbe759c0301cb32 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/serperdev-more-robust-229ba25c8fc9306d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/serperdev-more-robust-229ba25c8fc9306d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9717400095a1f328497cd656594fb75fb0f5686a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/ship-boilerpy3-0bffbd7955c89dd4.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/ship-boilerpy3-0bffbd7955c89dd4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b9349165ca6eeaa5d421945b67cc09384b1ff56f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/ship-boilerpy3-0bffbd7955c89dd4.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Include 'boilerpy3' in the 'haystack-ai' dependencies. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-tikaconverter-89b454c451a2ed93.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-tikaconverter-89b454c451a2ed93.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fcd1671ad5368b8f7d9ea095e0697e50da44fa6d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-meta-in-tikaconverter-89b454c451a2ed93.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Adds support for single metadata dictionary input in `TikaDocumentConverter`. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-metadata-txt-converter-a02bf90c60262701.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/single-metadata-txt-converter-a02bf90c60262701.yaml new file mode 100644 index 0000000000000000000000000000000000000000..68c90c59cbd3f2837cb657f931f95ca5b4beca1b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sparse-embedding-fd55b670437492be.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sparse-embedding-fd55b670437492be.yaml new file mode 100644 index 0000000000000000000000000000000000000000..455647b550e6063a8e258aedef7a28b401726402 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/sparse-embedding-fd55b670437492be.yaml @@ -0,0 +1,7 @@ +--- +features: + - | + Introduce a new `SparseEmbedding` class which can be used to store a sparse + vector representation of a Document. + It will be instrumental to support Sparse Embedding Retrieval with + the subsequent introduction of Sparse Embedders and Sparse Embedding Retrievers. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/speedup-import-b542f7a8323ef376.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/speedup-import-b542f7a8323ef376.yaml new file mode 100644 index 0000000000000000000000000000000000000000..80ddc299a86b87834f067a7f35b582695f70dea6 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/stop-using-canals-bfc26ad25e472652.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/stop-using-canals-bfc26ad25e472652.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c7f4cd8fbf33f3c16b32bdb9733ccfe81f34f439 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/structlog-contextvars-c13bb3c59a6a92c7.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/structlog-contextvars-c13bb3c59a6a92c7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..053d1f3cd78368602f1855a8a8283b4d3bd5b1ab --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-azure-3.5-gpt-16k-model-ece0cfe03260748c.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/support-azure-3.5-gpt-16k-model-ece0cfe03260748c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9fc499418cb96f2a6a60db660355fe9b58c213f9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/switch-bm25-dep-9b9d1c596f5ff4d0.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/switch-bm25-dep-9b9d1c596f5ff4d0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3abeffa5a3081732fb3a44f76bc6b4f7720849a4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/switch-bm25-dep-9b9d1c596f5ff4d0.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Depend on our own rank_bm25 fork. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/telemetry-2.0-92c34c81563ff0e1.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/telemetry-2.0-92c34c81563ff0e1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..31fddfdf42008a7f71e699999cf619ceb586935d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/telemetry-2.0-92c34c81563ff0e1.yaml @@ -0,0 +1,3 @@ + +preview: + - Add basic telemetry to Haystack 2.0 pipelines diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/text-cleaner-eee0eecbdec21427.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/text-cleaner-eee0eecbdec21427.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3e28b27ca5423cf0227e92db2f157efe16092ca7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/text-document-cleaner-8afce831a2ac31ae.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/text-document-cleaner-8afce831a2ac31ae.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cde155a938da6bde15f1413abb14a4391d8ea564 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/text-language-classifier-0d1e1a97f1bb8ac6.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/text-language-classifier-0d1e1a97f1bb8ac6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..84430525e21b40ceeffcbd96fd8597a4ca3e4506 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/textfile-to-document-v2-341987623765ec95.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/textfile-to-document-v2-341987623765ec95.yaml new file mode 100644 index 0000000000000000000000000000000000000000..41fd5150412ba607c38114e4ffd7e3abd417025f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/trafilatura-html-conversion-e9b9044d31fec794.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/trafilatura-html-conversion-e9b9044d31fec794.yaml new file mode 100644 index 0000000000000000000000000000000000000000..903e0d15cd123be7a14430fe0a3cc6beab9aec15 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/transformers-similarity-update-53a840b31bac4c3d.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/transformers-similarity-update-53a840b31bac4c3d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..92d61c48855119ddab959f49f83a51566d9b6072 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-crawler-selenium-4.11-30fec9f6e345834f.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-crawler-selenium-4.11-30fec9f6e345834f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5db8222cc0f1f175a3d394117fea14b7566756de --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-max-seq-lenght-st-1dc3d7a9c9a3bdcd.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-max-seq-lenght-st-1dc3d7a9c9a3bdcd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3a5595ee6cfbc73c86710024bc5aa4e1307d5667 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-max-seq-lenght-st-1dc3d7a9c9a3bdcd.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Updates SentenceTransformersDocumentEmbedder and SentenceTransformersTextEmbedder so model_max_length passed through tokenizer_kwargs also updates the max_seq_length of the underly SentenceTransformer model. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-secret-management-extractive-reader-4a8ce8df1f2705f8.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-secret-management-extractive-reader-4a8ce8df1f2705f8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a3d06cd88d934e94d8e4a46ae5293376ec1f7c76 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-secret-management-extractive-reader-4a8ce8df1f2705f8.yaml @@ -0,0 +1,7 @@ +--- +upgrade: + - | + Update secret handling for the `ExtractiveReader` component using the `Secret` type. + + The default init parameter `token` is now required to either use a token or the environment `HF_API_TOKEN` variable + if authentication is required - The on-disk local token file is no longer supported. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-sentence-transformers-3-3bca4e3f3ad3e7ba.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-sentence-transformers-3-3bca4e3f3ad3e7ba.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c86d952f9362b5b16b13e086ebe00bed88dba000 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-sentence-transformers-3-3bca4e3f3ad3e7ba.yaml @@ -0,0 +1,6 @@ +--- +fixes: + - | + Starting from `haystack-ai==2.4.0`, Haystack is compatible with `sentence-transformers>=3.0.0`; + earlier versions of `sentence-transformers` are not supported. + We are updating the test dependency and the LazyImport messages to reflect that. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-sentence-transformers-import-error-msg-895b8ed2355ae2fe.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/update-sentence-transformers-import-error-msg-895b8ed2355ae2fe.yaml new file mode 100644 index 0000000000000000000000000000000000000000..89932da9a4fbd4033fbf900a73a2cd76156d3ddb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/updated-ranking-mode-in-meta-field-ranker-d1f1304cc422b202.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/updated-ranking-mode-in-meta-field-ranker-d1f1304cc422b202.yaml new file mode 100644 index 0000000000000000000000000000000000000000..965110ae1de49ed74273525f650bb08f040e5b23 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/updated-ranking-mode-in-meta-field-ranker-d1f1304cc422b202.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Fixed a bug in the `MetaFieldRanker`: when the `ranking_mode` parameter was overridden in the `run` method, + the component was incorrectly using the `ranking_mode` parameter set in the `__init__` method. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-canals-0-9-0-2bed4670885e998b.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-canals-0-9-0-2bed4670885e998b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6888127caf9e6c53f9bd192cc197b05d7c2a402d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-huggingface-hub-dependency-9b8a89d50eb88fea.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-huggingface-hub-dependency-9b8a89d50eb88fea.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4113e2e91797aebbeac316a8099cfeb717d24a4e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-tgi-to-new-hf-hub-51fcb3b6122fe020.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-tgi-to-new-hf-hub-51fcb3b6122fe020.yaml new file mode 100644 index 0000000000000000000000000000000000000000..82dba924fb8ceddd26aab6112aed00f360986b6f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-tgi-to-new-hf-hub-51fcb3b6122fe020.yaml @@ -0,0 +1,11 @@ +--- +upgrade: + - | + The `HuggingFaceTGIGenerator` and `HuggingFaceTGIChatGenerator` components have been modified to be compatible with + `huggingface_hub>=0.22.0`. + + If you use these components, you may need to upgrade the `huggingface_hub` library. + To do this, run the following command in your environment: + ```bash + pip install "huggingface_hub>=0.22.0" + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-tiktoken-0.5.1-3cea9bf90fddb2f2.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/upgrade-tiktoken-0.5.1-3cea9bf90fddb2f2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f371e5f58c7b3c41ab6f5e35ad91e74f8095241f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/web-retriever-allow-custom-link-content-fetcher-8728141d81d7a5e5.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/web-retriever-allow-custom-link-content-fetcher-8728141d81d7a5e5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fff5904a143a7e2d7bdef03f44c9c98a6eb41447 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/whisper-loc-new-devices-0665a24cd92ee4b6.yaml b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/whisper-loc-new-devices-0665a24cd92ee4b6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..709529ced188604312ee2f05b31b1c48838872f3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/whisper-loc-new-devices-0665a24cd92ee4b6.yaml @@ -0,0 +1,23 @@ +--- +upgrade: + - | + Adopt the new framework-agnostic device management in Local Whisper Transcriber. + + Before this change: + ```python + from haystack.components.audio import LocalWhisperTranscriber + + transcriber = LocalWhisperTranscriber(device="cuda:0") + ``` + + After this change: + ```python + from haystack.utils.device import ComponentDevice, Device + from haystack.components.audio import LocalWhisperTranscriber + + device = ComponentDevice.from_single(Device.gpu(id=0)) + # or + # device = ComponentDevice.from_str("cuda:0") + + transcriber = LocalWhisperTranscriber(device=device) + ``` diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/components/audio/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/audio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/audio/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/components/audio/test_whisper_local.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/audio/test_whisper_local.py new file mode 100644 index 0000000000000000000000000000000000000000..28463c4ce6575f881722ba371e2dea7d15177e12 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/audio/test_whisper_remote.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/audio/test_whisper_remote.py new file mode 100644 index 0000000000000000000000000000000000000000..8f18018e87799202ffc740590463333614fb2fbd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/audio/test_whisper_remote.py @@ -0,0 +1,212 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os +import pytest + +from haystack import Pipeline +from haystack.components.audio.whisper_remote import RemoteWhisperTranscriber +from haystack.components.fetchers import LinkContentFetcher +from haystack.dataclasses import ByteStream +from haystack.utils import Secret + + +class TestRemoteWhisperTranscriber: + def test_init_no_key(self, monkeypatch): + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + RemoteWhisperTranscriber() + + def test_init_key_env_var(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test_api_key") + t = RemoteWhisperTranscriber() + assert t.client.api_key == "test_api_key" + + def test_init_key_module_env_and_global_var(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test_api_key_2") + t = RemoteWhisperTranscriber() + assert t.client.api_key == "test_api_key_2" + + def test_init_default(self): + transcriber = RemoteWhisperTranscriber(api_key=Secret.from_token("test_api_key")) + assert transcriber.client.api_key == "test_api_key" + assert transcriber.model == "whisper-1" + assert transcriber.organization is None + assert transcriber.whisper_params == {"response_format": "json"} + + def test_init_custom_parameters(self): + transcriber = RemoteWhisperTranscriber( + api_key=Secret.from_token("test_api_key"), + model="whisper-1", + organization="test-org", + api_base_url="test_api_url", + language="en", + prompt="test-prompt", + response_format="json", + temperature="0.5", + ) + + assert transcriber.model == "whisper-1" + assert transcriber.api_key == Secret.from_token("test_api_key") + assert transcriber.organization == "test-org" + assert transcriber.api_base_url == "test_api_url" + assert transcriber.whisper_params == { + "language": "en", + "prompt": "test-prompt", + "response_format": "json", + "temperature": "0.5", + } + + def test_to_dict_default_parameters(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test_api_key") + transcriber = RemoteWhisperTranscriber() + data = transcriber.to_dict() + assert data == { + "type": "haystack.components.audio.whisper_remote.RemoteWhisperTranscriber", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "model": "whisper-1", + "api_base_url": None, + "organization": None, + "response_format": "json", + }, + } + + def test_to_dict_with_custom_init_parameters(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test_api_key") + transcriber = RemoteWhisperTranscriber( + api_key=Secret.from_env_var("ENV_VAR", strict=False), + model="whisper-1", + organization="test-org", + api_base_url="test_api_url", + language="en", + prompt="test-prompt", + response_format="json", + temperature="0.5", + ) + data = transcriber.to_dict() + assert data == { + "type": "haystack.components.audio.whisper_remote.RemoteWhisperTranscriber", + "init_parameters": { + "api_key": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "model": "whisper-1", + "organization": "test-org", + "api_base_url": "test_api_url", + "language": "en", + "prompt": "test-prompt", + "response_format": "json", + "temperature": "0.5", + }, + } + + def test_from_dict_with_default_parameters(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test_api_key") + + data = { + "type": "haystack.components.audio.whisper_remote.RemoteWhisperTranscriber", + "init_parameters": { + "model": "whisper-1", + "api_base_url": "https://api.openai.com/v1", + "organization": None, + "response_format": "json", + }, + } + + transcriber = RemoteWhisperTranscriber.from_dict(data) + + assert transcriber.model == "whisper-1" + assert transcriber.organization is None + assert transcriber.api_base_url == "https://api.openai.com/v1" + assert transcriber.whisper_params == {"response_format": "json"} + + def test_from_dict_with_custom_init_parameters(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test_api_key") + + data = { + "type": "haystack.components.audio.whisper_remote.RemoteWhisperTranscriber", + "init_parameters": { + "model": "whisper-1", + "organization": "test-org", + "api_base_url": "test_api_url", + "language": "en", + "prompt": "test-prompt", + "response_format": "json", + "temperature": "0.5", + }, + } + transcriber = RemoteWhisperTranscriber.from_dict(data) + + assert transcriber.model == "whisper-1" + assert transcriber.organization == "test-org" + assert transcriber.api_base_url == "test_api_url" + assert transcriber.whisper_params == { + "language": "en", + "prompt": "test-prompt", + "response_format": "json", + "temperature": "0.5", + } + + def test_from_dict_with_default_parameters_no_env_var(self, monkeypatch): + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + + data = { + "type": "haystack.components.audio.whisper_remote.RemoteWhisperTranscriber", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "model": "whisper-1", + "api_base_url": "https://api.openai.com/v1", + "organization": None, + "response_format": "json", + }, + } + + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + RemoteWhisperTranscriber.from_dict(data) + + @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_whisper_remote_transcriber(self, test_files_path): + transcriber = RemoteWhisperTranscriber() + + paths = [ + 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"), + ByteStream.from_file_path(test_files_path / "audio" / "answer.wav"), + ] + + output = transcriber.run(sources=paths) + + docs = output["documents"] + assert len(docs) == 3 + assert docs[0].content.strip().lower() == "this is the content of the document." + assert test_files_path / "audio" / "this is the content of the document.wav" == docs[0].meta["file_path"] + + assert docs[1].content.strip().lower() == "the context for this answer is here." + assert str(test_files_path / "audio" / "the context for this answer is here.wav") == docs[1].meta["file_path"] + + assert docs[2].content.strip().lower() == "answer." + + @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_whisper_remote_transcriber_pipeline_and_url_source(self): + pipe = Pipeline() + pipe.add_component("fetcher", LinkContentFetcher()) + pipe.add_component("transcriber", RemoteWhisperTranscriber()) + + 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/SPFsmartGATE/LIVE/TMP/haystack/test/components/builders/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/builders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/builders/test_answer_builder.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/builders/test_answer_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..46c40e3422a23085f8c210459fe44f10fb046733 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/builders/test_chat_prompt_builder.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/builders/test_chat_prompt_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..e40b47b5081e666a89b8e5c18635b4a0f82b11ed --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/builders/test_prompt_builder.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/builders/test_prompt_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..7461327f4ea3a0002df9de94046252231b2bb0f0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/caching/test_url_cache_checker.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/caching/test_url_cache_checker.py new file mode 100644 index 0000000000000000000000000000000000000000..60b72ff8966b844025697f088ec4baff7dd534ce --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/classifiers/test_document_language_classifier.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/classifiers/test_document_language_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..9204b308807d3c79f1cd780cdd47dc0a806b8242 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/classifiers/test_zero_shot_document_classifier.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/classifiers/test_zero_shot_document_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..7d679e3d21d523256739d5a3f5d41534d40a433a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/classifiers/test_zero_shot_document_classifier.py @@ -0,0 +1,165 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import pytest + +from unittest.mock import patch + +from haystack import Document, Pipeline +from haystack.components.classifiers import TransformersZeroShotDocumentClassifier +from haystack.components.retrievers import InMemoryBM25Retriever +from haystack.document_stores.in_memory import InMemoryDocumentStore +from haystack.utils import ComponentDevice, Secret + + +class TestTransformersZeroShotDocumentClassifier: + def test_init(self): + component = TransformersZeroShotDocumentClassifier( + model="cross-encoder/nli-deberta-v3-xsmall", labels=["positive", "negative"] + ) + assert component.labels == ["positive", "negative"] + assert component.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert component.multi_label is False + assert component.pipeline is None + assert component.classification_field is None + + def test_to_dict(self): + component = TransformersZeroShotDocumentClassifier( + model="cross-encoder/nli-deberta-v3-xsmall", labels=["positive", "negative"] + ) + component_dict = component.to_dict() + assert component_dict == { + "type": "haystack.components.classifiers.zero_shot_document_classifier.TransformersZeroShotDocumentClassifier", + "init_parameters": { + "model": "cross-encoder/nli-deberta-v3-xsmall", + "labels": ["positive", "negative"], + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "huggingface_pipeline_kwargs": { + "model": "cross-encoder/nli-deberta-v3-xsmall", + "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.classifiers.zero_shot_document_classifier.TransformersZeroShotDocumentClassifier", + "init_parameters": { + "model": "cross-encoder/nli-deberta-v3-xsmall", + "labels": ["positive", "negative"], + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "huggingface_pipeline_kwargs": { + "model": "cross-encoder/nli-deberta-v3-xsmall", + "device": ComponentDevice.resolve_device(None).to_hf(), + "task": "zero-shot-classification", + }, + }, + } + component = TransformersZeroShotDocumentClassifier.from_dict(data) + assert component.labels == ["positive", "negative"] + 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": "cross-encoder/nli-deberta-v3-xsmall", + "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.classifiers.zero_shot_document_classifier.TransformersZeroShotDocumentClassifier", + "init_parameters": {"model": "cross-encoder/nli-deberta-v3-xsmall", "labels": ["positive", "negative"]}, + } + component = TransformersZeroShotDocumentClassifier.from_dict(data) + assert component.labels == ["positive", "negative"] + 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": "cross-encoder/nli-deberta-v3-xsmall", + "device": ComponentDevice.resolve_device(None).to_hf(), + "task": "zero-shot-classification", + "token": None, + } + + @patch("haystack.components.classifiers.zero_shot_document_classifier.pipeline") + def test_warm_up(self, hf_pipeline_mock): + component = TransformersZeroShotDocumentClassifier( + model="cross-encoder/nli-deberta-v3-xsmall", labels=["positive", "negative"] + ) + component.warm_up() + assert component.pipeline is not None + + def test_run_fails_without_warm_up(self): + component = TransformersZeroShotDocumentClassifier( + model="cross-encoder/nli-deberta-v3-xsmall", labels=["positive", "negative"] + ) + positive_documents = [Document(content="That's good. I like it.")] + with pytest.raises(RuntimeError): + component.run(documents=positive_documents) + + @patch("haystack.components.classifiers.zero_shot_document_classifier.pipeline") + def test_run_fails_with_non_document_input(self, hf_pipeline_mock): + hf_pipeline_mock.return_value = " " + component = TransformersZeroShotDocumentClassifier( + model="cross-encoder/nli-deberta-v3-xsmall", labels=["positive", "negative"] + ) + component.warm_up() + text_list = ["That's good. I like it.", "That's bad. I don't like it."] + with pytest.raises(TypeError): + component.run(documents=text_list) + + @patch("haystack.components.classifiers.zero_shot_document_classifier.pipeline") + def test_run_unit(self, hf_pipeline_mock): + hf_pipeline_mock.return_value = [ + {"sequence": "That's good. I like it.", "labels": ["positive", "negative"], "scores": [0.99, 0.01]}, + {"sequence": "That's bad. I don't like it.", "labels": ["negative", "positive"], "scores": [0.99, 0.01]}, + ] + component = TransformersZeroShotDocumentClassifier( + model="cross-encoder/nli-deberta-v3-xsmall", labels=["positive", "negative"] + ) + component.pipeline = hf_pipeline_mock + positive_document = Document(content="That's good. I like it.") + negative_document = Document(content="That's bad. I don't like it.") + result = component.run(documents=[positive_document, negative_document]) + assert component.pipeline is not None + assert result["documents"][0].to_dict()["classification"]["label"] == "positive" + assert result["documents"][1].to_dict()["classification"]["label"] == "negative" + + @pytest.mark.integration + def test_run(self): + component = TransformersZeroShotDocumentClassifier( + model="cross-encoder/nli-deberta-v3-xsmall", labels=["positive", "negative"] + ) + component.warm_up() + positive_document = Document(content="That's good. I like it. " * 1000) + negative_document = Document(content="That's bad. I don't like it.") + result = component.run(documents=[positive_document, negative_document]) + assert component.pipeline is not None + assert result["documents"][0].to_dict()["classification"]["label"] == "positive" + assert result["documents"][1].to_dict()["classification"]["label"] == "negative" + + def test_serialization_and_deserialization_pipeline(self): + pipeline = Pipeline() + document_store = InMemoryDocumentStore() + retriever = InMemoryBM25Retriever(document_store=document_store) + document_classifier = TransformersZeroShotDocumentClassifier( + model="cross-encoder/nli-deberta-v3-xsmall", labels=["positive", "negative"] + ) + + pipeline.add_component(instance=retriever, name="retriever") + pipeline.add_component(instance=document_classifier, name="document_classifier") + pipeline.connect("retriever", "document_classifier") + pipeline_dump = pipeline.dumps() + + new_pipeline = Pipeline.loads(pipeline_dump) + + assert new_pipeline == pipeline diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/components/connectors/test_openapi_service.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/connectors/test_openapi_service.py new file mode 100644 index 0000000000000000000000000000000000000000..82340bdd766fe1000d289f765dd7fd1f86e39c64 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_azure_ocr_doc_converter.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_azure_ocr_doc_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..1ba7d33f5a60df96a9ed87cac314d50f0304db5c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_csv_to_document.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_csv_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..c8f0bac0f1e7aa75dc21c39c70e2e28a7db9be66 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_csv_to_document.py @@ -0,0 +1,86 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +from unittest.mock import patch +import pandas as pd +from pathlib import Path + +import pytest + +from haystack.dataclasses import ByteStream +from haystack.components.converters.csv import CSVToDocument + + +@pytest.fixture +def csv_converter(): + return CSVToDocument() + + +class TestCSVToDocument: + def test_init(self, csv_converter): + assert isinstance(csv_converter, CSVToDocument) + + def test_run(self, test_files_path): + """ + Test if the component runs correctly. + """ + bytestream = ByteStream.from_file_path(test_files_path / "csv" / "sample_1.csv") + bytestream.meta["file_path"] = str(test_files_path / "csv" / "sample_1.csv") + bytestream.meta["key"] = "value" + files = [bytestream, test_files_path / "csv" / "sample_2.csv", test_files_path / "csv" / "sample_3.csv"] + converter = CSVToDocument() + output = converter.run(sources=files) + docs = output["documents"] + assert len(docs) == 3 + assert "Name,Age\r\nJohn Doe,27\r\nJane Smith,37\r\nMike Johnson,47\r\n" == docs[0].content + assert isinstance(docs[0].content, str) + assert docs[0].meta == bytestream.meta + assert docs[1].meta["file_path"] == str(files[1]) + assert docs[2].meta["file_path"] == str(files[2]) + + def test_run_error_handling(self, test_files_path, caplog): + """ + Test if the component correctly handles errors. + """ + paths = [ + test_files_path / "csv" / "sample_2.csv", + "non_existing_file.csv", + test_files_path / "csv" / "sample_3.csv", + ] + converter = CSVToDocument() + with caplog.at_level(logging.WARNING): + output = converter.run(sources=paths) + assert "non_existing_file.csv" in caplog.text + docs = output["documents"] + assert len(docs) == 2 + assert docs[0].meta["file_path"] == str(paths[0]) + + def test_encoding_override(self, test_files_path, caplog): + """ + Test if the encoding metadata field is used properly + """ + bytestream = ByteStream.from_file_path(test_files_path / "csv" / "sample_1.csv") + bytestream.meta["key"] = "value" + + converter = CSVToDocument(encoding="utf-16-le") + output = converter.run(sources=[bytestream]) + with caplog.at_level(logging.ERROR): + output = converter.run(sources=[bytestream]) + assert "codec can't decode" in caplog.text + + converter = CSVToDocument(encoding="utf-8") + output = converter.run(sources=[bytestream]) + assert "Name,Age\r\n" in output["documents"][0].content + + def test_run_with_meta(self): + bytestream = ByteStream( + data=b"Name,Age,City\r\nAlice,30,New York\r\nBob,25,Los Angeles\r\nCharlie,35,Chicago\r\n", + meta={"name": "test_name", "language": "en"}, + ) + converter = CSVToDocument() + 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 == {"name": "test_name", "language": "it"} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_docx_file_to_document.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_docx_file_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..d529f2a06d24cdeb513753934cb5bd1ef8badaf5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_docx_file_to_document.py @@ -0,0 +1,169 @@ +import logging +import json + +import pytest + +from haystack.dataclasses import ByteStream +from haystack import Document +from haystack.components.converters.docx import DOCXToDocument, DOCXMetadata + + +@pytest.fixture +def docx_converter(): + return DOCXToDocument() + + +class TestDOCXToDocument: + def test_init(self, docx_converter): + assert isinstance(docx_converter, DOCXToDocument) + + 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_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/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_html_to_document.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_html_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..85c0ffd710ab576f04b382a3cd59ae7858afcac9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_json.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_json.py new file mode 100644 index 0000000000000000000000000000000000000000..fe43044f749dc63943ccfdd418d9c75957e6658e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_markdown_to_document.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_markdown_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..302cc10434a0e4e7406ffdc6ec4aca36916d2ce4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_openapi_functions.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_openapi_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..e154059038ccbc3552bcfd84aeef15f4f8f33a1c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_output_adapter.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_output_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..547ce433e68bd56dc3b8e274e5d4ca38db1d07ae --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_pdfminer_to_document.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_pdfminer_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..0cd47df8f325edef17e2e38800c8cdf965c8455f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_pdfminer_to_document.py @@ -0,0 +1,128 @@ +# 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"] == [] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_pptx_to_document.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_pptx_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0c314e33743383f46807b7c0a51332411f4c26 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_pypdf_to_document.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_pypdf_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..3c8744fb6836268cbf6f0bf7317ebf3a015d41b4 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_pypdf_to_document.py @@ -0,0 +1,172 @@ +# 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, DefaultConverter +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_custom_converter(self): + pypdf_converter = PyPDFToDocument(converter=CustomConverter()) + data = pypdf_converter.to_dict() + 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) + + def test_from_dict_pre_2_6_0(self): + data = { + "type": "haystack.components.converters.pypdf.PyPDFToDocument", + "init_parameters": {"converter": {"type": "haystack.components.converters.pypdf.DefaultConverter"}}, + } + instance = PyPDFToDocument.from_dict(data) + assert isinstance(instance, PyPDFToDocument) + assert isinstance(instance.converter, DefaultConverter) + + @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 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_textfile_to_document.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_textfile_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..ba3bdec101242eae8224194c455781615a6c2550 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_tika_doc_converter.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_tika_doc_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..42ba3ebe1d90f979067045f438b31cf5e1e827fd --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_utils.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/converters/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..296533491d5dc2b10a28d1d6c3f42047c7c10cff --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/embedders/test_azure_document_embedder.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/embedders/test_azure_document_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..354f35a0fc1150e784c1e2e6b15eb2cc91a6b7db --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/embedders/test_azure_text_embedder.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/embedders/test_azure_text_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1f82e3d8208eaf5cf99df3b6bc89bfe3b3d3c0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/embedders/test_openai_text_embedder.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/embedders/test_openai_text_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..31a0360555c7cfa2ddcbd0dd78008111c0a6735c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/embedders/test_sentence_transformers_embedding_backend.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/embedders/test_sentence_transformers_embedding_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..55014183b2371d625277079aa503b44080c18ffc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_answer_exact_match.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_answer_exact_match.py new file mode 100644 index 0000000000000000000000000000000000000000..0c123f0d3a6d0e0ca96273136cf769f28cbacfd3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_context_relevance_evaluator.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_context_relevance_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..dd1e33cc8e7e5cb7329da80eb5ad1f064c09862d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_context_relevance_evaluator.py @@ -0,0 +1,242 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os +from typing import List + +import math + +import pytest + +from haystack import Pipeline +from haystack.components.evaluators import ContextRelevanceEvaluator +from haystack.utils.auth import Secret + + +class TestContextRelevanceEvaluator: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = ContextRelevanceEvaluator() + assert component.api == "openai" + assert component.generator.client.api_key == "test-api-key" + assert component.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: []" + ) + assert component.inputs == [("questions", List[str]), ("contexts", List[List[str]])] + assert component.outputs == ["relevant_statements"] + assert component.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."]}, + }, + ] + + 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"): + ContextRelevanceEvaluator() + + def test_init_with_parameters(self): + component = ContextRelevanceEvaluator( + api_key=Secret.from_token("test-api-key"), + api="openai", + examples=[ + {"inputs": {"questions": "Damn, this is straight outta hell!!!"}, "outputs": {"custom_score": 1}}, + {"inputs": {"questions": "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": {"questions": "Damn, this is straight outta hell!!!"}, "outputs": {"custom_score": 1}}, + {"inputs": {"questions": "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 = ContextRelevanceEvaluator( + api="openai", + api_key=Secret.from_env_var("ENV_VAR"), + examples=[{"inputs": {"questions": "What is football?"}, "outputs": {"score": 0}}], + raise_on_failure=False, + progress_bar=False, + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.evaluators.context_relevance.ContextRelevanceEvaluator", + "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": {"questions": "What is football?"}, "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.context_relevance.ContextRelevanceEvaluator", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "api": "openai", + "examples": [{"inputs": {"questions": "What is football?"}, "outputs": {"score": 0}}], + }, + } + component = ContextRelevanceEvaluator.from_dict(data) + assert component.api == "openai" + assert component.generator.client.api_key == "test-api-key" + assert component.examples == [{"inputs": {"questions": "What is football?"}, "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 = ContextRelevanceEvaluator() + + def generator_run(self, *args, **kwargs): + if "Football" in kwargs["prompt"]: + return {"replies": ['{"relevant_statements": ["a", "b"], "score": 1}']} + else: + return {"replies": ['{"relevant_statements": [], "score": 0}']} + + 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 is 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." + ], + ] + results = component.run(questions=questions, contexts=contexts) + + print(results) + + assert results == { + "results": [{"score": 1, "relevant_statements": ["a", "b"]}, {"score": 0, "relevant_statements": []}], + "score": 0.5, + "meta": None, + "individual_scores": [1, 0], + } + + def test_run_no_statements_extracted(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = ContextRelevanceEvaluator() + + def generator_run(self, *args, **kwargs): + if "Football" in kwargs["prompt"]: + return {"replies": ['{"relevant_statements": ["a", "b"], "score": 1}']} + else: + return {"replies": ['{"relevant_statements": [], "score": 0}']} + + 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." + ], + [], + ] + results = component.run(questions=questions, contexts=contexts) + assert results == { + "results": [{"score": 1, "relevant_statements": ["a", "b"]}, {"score": 0, "relevant_statements": []}], + "score": 0.5, + "meta": None, + "individual_scores": [1, 0], + } + + def test_run_missing_parameters(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = ContextRelevanceEvaluator() + 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 = ContextRelevanceEvaluator(raise_on_failure=False) + + def generator_run(self, *args, **kwargs): + if "Python" in kwargs["prompt"]: + raise Exception("OpenAI API request failed.") + else: + return {"replies": ['{"relevant_statements": ["c", "d"], "score": 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." + ], + ] + results = component.run(questions=questions, contexts=contexts) + + assert math.isnan(results["score"]) + assert results["results"][0] == {"relevant_statements": ["c", "d"], "score": 1} + assert results["results"][1]["relevant_statements"] == [] + 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 = ["Who created the Python language?"] + contexts = [["Python, created by Guido van Rossum, is a high-level general-purpose programming language."]] + + evaluator = ContextRelevanceEvaluator() + result = evaluator.run(questions=questions, contexts=contexts) + + required_fields = {"results"} + assert all(field in result for field in required_fields) + nested_required_fields = {"score", "relevant_statements"} + assert all(field in result["results"][0] for field in nested_required_fields) + + 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/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_document_map.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_document_map.py new file mode 100644 index 0000000000000000000000000000000000000000..7c7b26c0892215368b22719d5a64556a8b20c986 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_document_mrr.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_document_mrr.py new file mode 100644 index 0000000000000000000000000000000000000000..88700eed087ac001f69d44238d6ddfca15e24979 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_document_mrr.py @@ -0,0 +1,85 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack import Document +from haystack.components.evaluators.document_mrr import DocumentMRREvaluator + + +def test_run_with_all_matching(): + evaluator = DocumentMRREvaluator() + 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 = DocumentMRREvaluator() + 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 = DocumentMRREvaluator() + 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 = DocumentMRREvaluator() + 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="10th century"), Document(content="9th century"), Document(content="9th")], + [Document(content="rock music"), Document(content="dubstep"), Document(content="classical")], + [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, 0.5, 0.3333333333333333, 0.5, 0.0, 1.0], + "score": pytest.approx(0.555555555555555), + } + + +def test_run_with_different_lengths(): + with pytest.raises(ValueError): + evaluator = DocumentMRREvaluator() + evaluator.run( + ground_truth_documents=[[Document(content="Berlin")]], + retrieved_documents=[[Document(content="Berlin")], [Document(content="London")]], + ) + + with pytest.raises(ValueError): + evaluator = DocumentMRREvaluator() + evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Berlin")]], + ) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_document_ndcg.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_document_ndcg.py new file mode 100644 index 0000000000000000000000000000000000000000..3924855f720a215dcccd77f58e1e535df668fe58 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_document_recall.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_document_recall.py new file mode 100644 index 0000000000000000000000000000000000000000..2c438441ccd082091f7d333080129024ecbddd04 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_faithfulness_evaluator.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_faithfulness_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..de92388ece08266f3482206a6d4b8b6314194763 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_llm_evaluator.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_llm_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..e0feb6c0f43e58d08360ca9ceaea39b92e78b558 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_sas_evaluator.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/evaluators/test_sas_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..d1dad15151537f954df31befb90461db0858b994 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/extractors/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/extractors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/extractors/test_named_entity_extractor.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/extractors/test_named_entity_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..a4826c1e9517486534fe7a3be10594b659052ec1 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/fetchers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/fetchers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/fetchers/test_link_content_fetcher.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/fetchers/test_link_content_fetcher.py new file mode 100644 index 0000000000000000000000000000000000000000..35cbd5e40cc8cdf94a568c614290c9f2ee8abc43 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/chat/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/chat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/chat/conftest.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/chat/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..842e447b562781304b0172cca3b6f939f10bc056 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/chat/test_azure.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/chat/test_azure.py new file mode 100644 index 0000000000000000000000000000000000000000..fdafec682d4ebcc4cc14af6f76f01fc5012a66cc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/chat/test_hugging_face_api.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/chat/test_hugging_face_api.py new file mode 100644 index 0000000000000000000000000000000000000000..3d7fd617c09101dbc736f696a8b7e281a9a39d60 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/chat/test_hugging_face_local.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/chat/test_hugging_face_local.py new file mode 100644 index 0000000000000000000000000000000000000000..3f4dbdd06a115529d0b9657c1c057cbf85f1f21f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/chat/test_openai.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/chat/test_openai.py new file mode 100644 index 0000000000000000000000000000000000000000..c3332aae97009f35ce040e0c4d35ed1dc771e490 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/chat/test_openai.py @@ -0,0 +1,322 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +import os + +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 + + def test_run_with_streaming_callback_in_run_method(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")) + 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 + + 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/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/conftest.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..92ed8feb3a89cec8463266f2a0c49ba483d72ee3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/test_azure.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/test_azure.py new file mode 100644 index 0000000000000000000000000000000000000000..d3e524f602f01fc06698b876f17d5bad70660a09 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/test_hf_utils.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/test_hf_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..22e2e1cac076a729e35f324264a56ca20e57c940 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/test_hugging_face_api.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/test_hugging_face_api.py new file mode 100644 index 0000000000000000000000000000000000000000..ce6c7ecd2234815273c8acfe70e1a3e4a0d0c0e1 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/test_hugging_face_api.py @@ -0,0 +1,307 @@ +# 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"], + "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": [], "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/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/test_hugging_face_local_generator.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/test_hugging_face_local_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..5c3b162a314549956dbb19649dbb58ffcf172dd2 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/test_openai.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/test_openai.py new file mode 100644 index 0000000000000000000000000000000000000000..047299b199c362382ad2398a35bc3183ab31af95 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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] + + 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" in result["replies"][0] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/test_openai_utils.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/generators/test_openai_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..226b32f811b4294456dfba2a4d43c5f274133802 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/joiners/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/joiners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/joiners/test_answer_joiner.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/joiners/test_answer_joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..9c0a1be2befe522035ec51365ab8bee50b040b6e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/joiners/test_branch_joiner.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/joiners/test_branch_joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..05d30ad6d380928d38f7cad96058e062480335c5 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/joiners/test_document_joiner.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/joiners/test_document_joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..56bdfb64438aab0e1a377b163f6775f2ce974146 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/preprocessors/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/preprocessors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/preprocessors/test_document_cleaner.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/preprocessors/test_document_cleaner.py new file mode 100644 index 0000000000000000000000000000000000000000..2c84d5b12dc8187050448d91054a5ff74fd49308 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/preprocessors/test_document_splitter.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/preprocessors/test_document_splitter.py new file mode 100644 index 0000000000000000000000000000000000000000..7c942ab4ccd75e24ee27a419f7312cab0fb32ed7 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/preprocessors/test_document_splitter.py @@ -0,0 +1,447 @@ +# 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()]) + + 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"] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/components/preprocessors/test_nltk_document_splitter.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/preprocessors/test_nltk_document_splitter.py new file mode 100644 index 0000000000000000000000000000000000000000..4819dc602d50ccdecb8d363939c068f916842fea --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/preprocessors/test_text_cleaner.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/preprocessors/test_text_cleaner.py new file mode 100644 index 0000000000000000000000000000000000000000..38cd8ade57a42291f47fc198e7867022daaf99ac --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/rankers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/rankers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/rankers/test_lost_in_the_middle.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/rankers/test_lost_in_the_middle.py new file mode 100644 index 0000000000000000000000000000000000000000..edbe13a897c272e0bb2aa914106c406542529e2d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/rankers/test_metafield.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/rankers/test_metafield.py new file mode 100644 index 0000000000000000000000000000000000000000..87366e27c5b060b8eec80d5efbc0d06dfc45196d --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/rankers/test_sentence_transformers_diversity.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/rankers/test_sentence_transformers_diversity.py new file mode 100644 index 0000000000000000000000000000000000000000..ba3b10ae5c2bc9b38e73c3f4cea8416183a9ce31 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/rankers/test_transformers_similarity.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/rankers/test_transformers_similarity.py new file mode 100644 index 0000000000000000000000000000000000000000..6031d85e15195ea0d846f7ec92cae5170edd89f3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/readers/test_extractive.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/readers/test_extractive.py new file mode 100644 index 0000000000000000000000000000000000000000..9c42c44254eae3a4797f4d44bb86062fcbd05125 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/retrievers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/retrievers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/retrievers/test_filter_retriever.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/retrievers/test_filter_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..bef09e7a7701fbc059dc297b0576169f45894b75 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/retrievers/test_in_memory_bm25_retriever.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/retrievers/test_in_memory_bm25_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..ed1ba1887cf2a6cc726b332d39c4d0e69f47fcb8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/retrievers/test_in_memory_embedding_retriever.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/retrievers/test_in_memory_embedding_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..366fd17b320921e3100a00d74ea6b83bbaaafc06 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/retrievers/test_sentence_window_retriever.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/retrievers/test_sentence_window_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..786d278dd6234bf7b9c44d2aafb135c30b2aad02 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_conditional_router.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_conditional_router.py new file mode 100644 index 0000000000000000000000000000000000000000..461c58f9680b07260afb4f12300a0fa124bdad5a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_conditional_router.py @@ -0,0 +1,360 @@ +# 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: + @pytest.fixture + def routes(self): + return [ + {"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", + }, + ] + + @pytest.fixture + def router(self, routes): + return ConditionalRouter(routes) + + 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): + 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, router): + # 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} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_file_router.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_file_router.py new file mode 100644 index 0000000000000000000000000000000000000000..32d1e99dd162e6cc2469d36775b6b0190d0a055a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_file_router.py @@ -0,0 +1,188 @@ +# 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.dataclasses import ByteStream + + +@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_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_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" diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_metadata_router.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_metadata_router.py new file mode 100644 index 0000000000000000000000000000000000000000..d9e8ce9875983cf6923423f4331a855ca7618446 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_text_language_router.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_text_language_router.py new file mode 100644 index 0000000000000000000000000000000000000000..c72e55323836f48e0259ed1ff7581dfc8d0a3e60 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_transformers_text_router.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_transformers_text_router.py new file mode 100644 index 0000000000000000000000000000000000000000..8a0dca8d63e2aa4545f7adbeaed823fa3db0a997 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_zero_shot_text_router.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/routers/test_zero_shot_text_router.py new file mode 100644 index 0000000000000000000000000000000000000000..8e9759f361d2403bf36630237f1c87d9b1286255 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/samplers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/samplers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/samplers/test_top_p.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/samplers/test_top_p.py new file mode 100644 index 0000000000000000000000000000000000000000..49317fb8317a918ec4456fbf905a780b23790670 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/validators/test_json_schema.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/validators/test_json_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..39e9c785871f53419505d69a1e600fdc4288d607 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/writers/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/writers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/components/writers/test_document_writer.py b/SPFsmartGATE/LIVE/TMP/haystack/test/components/writers/test_document_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..44a4f40d268d7e925c525cd2d36498f8b1624cdb --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/core/component/test_component.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/component/test_component.py new file mode 100644 index 0000000000000000000000000000000000000000..49d3a8bd5309813c827036cce78b308fc38a00d8 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/component/test_component.py @@ -0,0 +1,547 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +from functools import partial +from typing import Any + +import pytest + +from haystack.core.component import Component, InputSocket, OutputSocket, component +from haystack.core.component.component import _hook_component_init +from haystack.core.component.types import Variadic +from haystack.core.errors import ComponentError +from haystack.core.pipeline import Pipeline + + +def test_correct_declaration(): + @component + class MockComponent: + def to_dict(self): + return {} + + @classmethod + def from_dict(cls, data): + return cls() + + @component.output_types(output_value=int) + def run(self, input_value: int): + return {"output_value": input_value} + + # Verifies also instantiation works with no issues + assert MockComponent() + assert component.registry["test_component.MockComponent"] == MockComponent + assert isinstance(MockComponent(), Component) + assert MockComponent().__haystack_supports_async__ is False + + +def test_correct_declaration_with_async(): + @component + class MockComponent: + def to_dict(self): + return {} + + @classmethod + def from_dict(cls, data): + return cls() + + @component.output_types(output_value=int) + def run(self, input_value: int): + return {"output_value": input_value} + + @component.output_types(output_value=int) + async def run_async(self, input_value: int): + return {"output_value": input_value} + + # Verifies also instantiation works with no issues + assert MockComponent() + assert component.registry["test_component.MockComponent"] == MockComponent + assert isinstance(MockComponent(), Component) + assert MockComponent().__haystack_supports_async__ is True + + +def test_correct_declaration_with_additional_readonly_property(): + @component + class MockComponent: + @property + def store(self): + return "test_store" + + def to_dict(self): + return {} + + @classmethod + def from_dict(cls, data): + return cls() + + @component.output_types(output_value=int) + def run(self, input_value: int): + return {"output_value": input_value} + + # Verifies that instantiation works with no issues + assert MockComponent() + assert component.registry["test_component.MockComponent"] == MockComponent + assert MockComponent().store == "test_store" + + +def test_correct_declaration_with_additional_writable_property(): + @component + class MockComponent: + @property + def store(self): + return "test_store" + + @store.setter + def store(self, value): + self._store = value + + def to_dict(self): + return {} + + @classmethod + def from_dict(cls, data): + return cls() + + @component.output_types(output_value=int) + def run(self, input_value: int): + return {"output_value": input_value} + + # Verifies that instantiation works with no issues + assert component.registry["test_component.MockComponent"] == MockComponent + comp = MockComponent() + comp.store = "test_store" + assert comp.store == "test_store" + + +def test_missing_run(): + with pytest.raises(ComponentError, match=r"must have a 'run\(\)' method"): + + @component + class MockComponent: + def another_method(self, input_value: int): + return {"output_value": input_value} + + +def test_async_run_not_async(): + @component + class MockComponent: + @component.output_types(value=int) + def run(self, value: int): + return {"value": 1} + + @component.output_types(value=int) + def run_async(self, value: int): + return {"value": 1} + + with pytest.raises(ComponentError, match=r"must be a coroutine"): + comp = MockComponent() + + +def test_async_run_not_coroutine(): + @component + class MockComponent: + @component.output_types(value=int) + def run(self, value: int): + return {"value": 1} + + @component.output_types(value=int) + async def run_async(self, value: int): + yield {"value": 1} + + with pytest.raises(ComponentError, match=r"must be a coroutine"): + comp = MockComponent() + + +def test_parameters_mismatch_run_and_async_run(): + err_msg = r"Parameters of 'run' and 'run_async' methods must be the same" + + @component + class MockComponentMismatchingInputTypes: + @component.output_types(value=int) + def run(self, value: int): + return {"value": 1} + + @component.output_types(value=int) + async def run_async(self, value: str): + return {"value": "1"} + + with pytest.raises(ComponentError, match=err_msg): + comp = MockComponentMismatchingInputTypes() + + @component + class MockComponentMismatchingInputs: + @component.output_types(value=int) + def run(self, value: int, **kwargs): + return {"value": 1} + + @component.output_types(value=int) + async def run_async(self, value: int): + return {"value": "1"} + + with pytest.raises(ComponentError, match=err_msg): + comp = MockComponentMismatchingInputs() + + @component + class MockComponentMismatchingInputOrder: + @component.output_types(value=int) + def run(self, value: int, another: str): + return {"value": 1} + + @component.output_types(value=int) + async def run_async(self, another: str, value: int): + return {"value": "1"} + + with pytest.raises(ComponentError, match=err_msg): + comp = MockComponentMismatchingInputOrder() + + +def test_set_input_types(): + @component + class MockComponent: + def __init__(self, flag: bool): + component.set_input_types(self, value=Any) + if flag: + component.set_input_type(self, name="another", type=str) + + @component.output_types(value=int) + def run(self, **kwargs): + return {"value": 1} + + comp = MockComponent(False) + assert comp.__haystack_input__._sockets_dict == {"value": InputSocket("value", Any)} + assert comp.run() == {"value": 1} + + comp = MockComponent(True) + assert comp.__haystack_input__._sockets_dict == { + "value": InputSocket("value", Any), + "another": InputSocket("another", str), + } + assert comp.run() == {"value": 1} + + +def test_set_input_types_no_kwarg(): + @component + class MockComponent: + def __init__(self, flag: bool): + if flag: + component.set_input_type(self, name="another", type=str) + else: + component.set_input_types(self, value=Any) + + @component.output_types(value=int) + def run(self, fini: bool): + return {"value": 1} + + with pytest.raises(ComponentError, match=r"doesn't have a kwargs parameter"): + comp = MockComponent(False) + + with pytest.raises(ComponentError, match=r"doesn't have a kwargs parameter"): + comp = MockComponent(True) + + +def test_set_input_types_overrides_run(): + @component + class MockComponent: + def __init__(self, state: bool): + if state: + component.set_input_type(self, name="fini", type=str) + else: + component.set_input_types(self, fini=Any) + + @component.output_types(value=int) + def run(self, fini: bool, **kwargs): + return {"value": 1} + + err_msg = "cannot override the parameters of the 'run' method" + with pytest.raises(ComponentError, match=err_msg): + comp = MockComponent(False) + + with pytest.raises(ComponentError, match=err_msg): + comp = MockComponent(True) + + +def test_set_output_types(): + @component + class MockComponent: + def __init__(self): + component.set_output_types(self, value=int) + + def to_dict(self): + return {} + + @classmethod + def from_dict(cls, data): + return cls() + + def run(self, value: int): + return {"value": 1} + + comp = MockComponent() + assert comp.__haystack_output__._sockets_dict == {"value": OutputSocket("value", int)} + + +def test_output_types_decorator_with_compatible_type(): + @component + class MockComponent: + @component.output_types(value=int) + def run(self, value: int): + return {"value": 1} + + def to_dict(self): + return {} + + @classmethod + def from_dict(cls, data): + return cls() + + comp = MockComponent() + assert comp.__haystack_output__._sockets_dict == {"value": OutputSocket("value", int)} + + +def test_output_types_decorator_wrong_method(): + with pytest.raises(ComponentError): + + @component + class MockComponent: + def run(self, value: int): + return {"value": 1} + + @component.output_types(value=int) + def to_dict(self): + return {} + + @classmethod + def from_dict(cls, data): + return cls() + + +def test_output_types_decorator_and_set_output_types(): + @component + class MockComponent: + def __init__(self) -> None: + component.set_output_types(self, value=int) + + @component.output_types(value=int) + def run(self, value: int): + return {"value": 1} + + with pytest.raises(ComponentError, match="Cannot call `set_output_types`"): + comp = MockComponent() + + +def test_output_types_decorator_mismatch_run_async_run(): + @component + class MockComponent: + @component.output_types(value=int) + def run(self, value: int): + return {"value": 1} + + @component.output_types(value=str) + async def run_async(self, value: int): + return {"value": "1"} + + with pytest.raises(ComponentError, match=r"Output type specifications .* must be the same"): + comp = MockComponent() + + +def test_output_types_decorator_missing_async_run(): + @component + class MockComponent: + @component.output_types(value=int) + def run(self, value: int): + return {"value": 1} + + async def run_async(self, value: int): + return {"value": "1"} + + with pytest.raises(ComponentError, match=r"Output type specifications .* must be the same"): + comp = MockComponent() + + +def test_component_decorator_set_it_as_component(): + @component + class MockComponent: + @component.output_types(value=int) + def run(self, value: int): + return {"value": 1} + + def to_dict(self): + return {} + + @classmethod + def from_dict(cls, data): + return cls() + + comp = MockComponent() + assert isinstance(comp, Component) + + +def test_input_has_default_value(): + @component + class MockComponent: + @component.output_types(value=int) + def run(self, value: int = 42): + return {"value": value} + + comp = MockComponent() + assert comp.__haystack_input__._sockets_dict["value"].default_value == 42 + assert not comp.__haystack_input__._sockets_dict["value"].is_mandatory + + +def test_keyword_only_args(): + @component + class MockComponent: + def __init__(self): + component.set_output_types(self, value=int) + + def run(self, *, arg: int): + return {"value": arg} + + comp = MockComponent() + component_inputs = {name: {"type": socket.type} for name, socket in comp.__haystack_input__._sockets_dict.items()} + assert component_inputs == {"arg": {"type": int}} + + +def test_repr(): + @component + class MockComponent: + def __init__(self): + component.set_output_types(self, value=int) + + def run(self, value: int): + return {"value": value} + + comp = MockComponent() + assert repr(comp) == f"{object.__repr__(comp)}\nInputs:\n - value: int\nOutputs:\n - value: int" + + +def test_repr_added_to_pipeline(): + @component + class MockComponent: + def __init__(self): + component.set_output_types(self, value=int) + + def run(self, value: int): + return {"value": value} + + pipe = Pipeline() + comp = MockComponent() + pipe.add_component("my_component", comp) + assert repr(comp) == f"{object.__repr__(comp)}\nmy_component\nInputs:\n - value: int\nOutputs:\n - value: int" + + +def test_pre_init_hooking(): + @component + class MockComponent: + def __init__(self, pos_arg1, pos_arg2, pos_arg3=None, *, kwarg1=1, kwarg2="string"): + self.pos_arg1 = pos_arg1 + self.pos_arg2 = pos_arg2 + self.pos_arg3 = pos_arg3 + self.kwarg1 = kwarg1 + self.kwarg2 = kwarg2 + + @component.output_types(output_value=int) + def run(self, input_value: int): + return {"output_value": input_value} + + def pre_init_hook(component_class, init_params, expected_params): + assert component_class == MockComponent + assert init_params == expected_params + + def pre_init_hook_modify(component_class, init_params, expected_params): + assert component_class == MockComponent + assert init_params == expected_params + + init_params["pos_arg1"] = 2 + init_params["pos_arg2"] = 0 + init_params["pos_arg3"] = "modified" + init_params["kwarg2"] = "modified string" + + with _hook_component_init(partial(pre_init_hook, expected_params={"pos_arg1": 1, "pos_arg2": 2, "kwarg1": None})): + _ = MockComponent(1, 2, kwarg1=None) + + with _hook_component_init(partial(pre_init_hook, expected_params={"pos_arg1": 1, "pos_arg2": 2, "pos_arg3": 0.01})): + _ = MockComponent(pos_arg1=1, pos_arg2=2, pos_arg3=0.01) + + with _hook_component_init( + partial(pre_init_hook_modify, expected_params={"pos_arg1": 0, "pos_arg2": 1, "pos_arg3": 0.01, "kwarg1": 0}) + ): + c = MockComponent(0, 1, pos_arg3=0.01, kwarg1=0) + + assert c.pos_arg1 == 2 + assert c.pos_arg2 == 0 + assert c.pos_arg3 == "modified" + assert c.kwarg1 == 0 + assert c.kwarg2 == "modified string" + + +def test_pre_init_hooking_variadic_positional_args(): + @component + class MockComponent: + def __init__(self, *args, kwarg1=1, kwarg2="string"): + self.args = args + self.kwarg1 = kwarg1 + self.kwarg2 = kwarg2 + + @component.output_types(output_value=int) + def run(self, input_value: int): + return {"output_value": input_value} + + def pre_init_hook(component_class, init_params, expected_params): + assert component_class == MockComponent + assert init_params == expected_params + + c = MockComponent(1, 2, 3, kwarg1=None) + assert c.args == (1, 2, 3) + assert c.kwarg1 is None + assert c.kwarg2 == "string" + + with pytest.raises(ComponentError), _hook_component_init( + partial(pre_init_hook, expected_params={"args": (1, 2), "kwarg1": None}) + ): + _ = MockComponent(1, 2, kwarg1=None) + + +def test_pre_init_hooking_variadic_kwargs(): + @component + class MockComponent: + def __init__(self, pos_arg1, pos_arg2=None, **kwargs): + self.pos_arg1 = pos_arg1 + self.pos_arg2 = pos_arg2 + self.kwargs = kwargs + + @component.output_types(output_value=int) + def run(self, input_value: int): + return {"output_value": input_value} + + def pre_init_hook(component_class, init_params, expected_params): + assert component_class == MockComponent + assert init_params == expected_params + + with _hook_component_init( + partial(pre_init_hook, expected_params={"pos_arg1": 1, "kwarg1": None, "kwarg2": 10, "kwarg3": "string"}) + ): + c = MockComponent(1, kwarg1=None, kwarg2=10, kwarg3="string") + assert c.pos_arg1 == 1 + assert c.pos_arg2 is None + assert c.kwargs == {"kwarg1": None, "kwarg2": 10, "kwarg3": "string"} + + def pre_init_hook_modify(component_class, init_params, expected_params): + assert component_class == MockComponent + assert init_params == expected_params + + init_params["pos_arg1"] = 2 + init_params["pos_arg2"] = 0 + init_params["some_kwarg"] = "modified string" + + with _hook_component_init( + partial( + pre_init_hook_modify, + expected_params={"pos_arg1": 0, "pos_arg2": 1, "kwarg1": 999, "some_kwarg": "some_value"}, + ) + ): + c = MockComponent(0, 1, kwarg1=999, some_kwarg="some_value") + + assert c.pos_arg1 == 2 + assert c.pos_arg2 == 0 + assert c.kwargs == {"kwarg1": 999, "some_kwarg": "modified string"} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/component/test_sockets.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/component/test_sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..14f3b7f1f40c27b785ab3f1c98c06f799259bf8a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/__init__.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/features/README.md b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/features/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4d3c362cce667fa3f64e897811e2456574bdde17 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/features/conftest.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/features/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..16c7be35ea9d707fc5247a44cbf56e707c342302 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/features/conftest.py @@ -0,0 +1,94 @@ +from dataclasses import dataclass, field +from typing import Tuple, List, Dict, Any, Set, Union +from pathlib import Path +import re + +from pytest_bdd import when, then, parsers + +from haystack import Pipeline + +PIPELINE_NAME_REGEX = re.compile(r"\[(.*)\]") + + +@dataclass +class PipelineRunData: + """ + Holds the inputs and expected outputs for a single Pipeline run. + """ + + inputs: Dict[str, Any] + include_outputs_from: Set[str] = field(default_factory=set) + expected_outputs: Dict[str, Any] = field(default_factory=dict) + expected_run_order: List[str] = field(default_factory=list) + + +@dataclass +class _PipelineResult: + """ + Holds the outputs and the run order of a single Pipeline run. + """ + + outputs: Dict[str, Any] + run_order: List[str] + + +@when("I run the Pipeline", target_fixture="pipeline_result") +def run_pipeline( + pipeline_data: Tuple[Pipeline, List[PipelineRunData]], spying_tracer +) -> Union[List[Tuple[_PipelineResult, PipelineRunData]], Exception]: + """ + Attempts to run a pipeline with the given inputs. + `pipeline_data` is a tuple that must contain: + * A Pipeline instance + * The data to run the pipeline with + + If successful returns a tuple of the run outputs and the expected outputs. + In case an exceptions is raised returns that. + """ + pipeline, pipeline_run_data = pipeline_data[0], pipeline_data[1] + + results: List[_PipelineResult] = [] + + for data in pipeline_run_data: + try: + outputs = pipeline.run(data=data.inputs, include_outputs_from=data.include_outputs_from) + run_order = [ + span.tags["haystack.component.name"] + for span in spying_tracer.spans + if "haystack.component.name" in span.tags + ] + results.append(_PipelineResult(outputs=outputs, run_order=run_order)) + spying_tracer.spans.clear() + except Exception as e: + return e + return [e for e in zip(results, pipeline_run_data)] + + +@then("draw it to file") +def draw_pipeline(pipeline_data: Tuple[Pipeline, List[PipelineRunData]], request): + """ + Draw the pipeline to a file with the same name as the test. + """ + if m := PIPELINE_NAME_REGEX.search(request.node.name): + name = m.group(1).replace(" ", "_") + pipeline = pipeline_data[0] + graphs_dir = Path(request.config.rootpath) / "test_pipeline_graphs" + graphs_dir.mkdir(exist_ok=True) + pipeline.draw(graphs_dir / f"{name}.png") + + +@then("it should return the expected result") +def check_pipeline_result(pipeline_result: List[Tuple[_PipelineResult, PipelineRunData]]): + for res, data in pipeline_result: + assert res.outputs == data.expected_outputs + + +@then("components ran in the expected order") +def check_pipeline_run_order(pipeline_result: List[Tuple[_PipelineResult, PipelineRunData]]): + for res, data in pipeline_result: + assert res.run_order == data.expected_run_order + + +@then(parsers.parse("it must have raised {exception_class_name}")) +def check_pipeline_raised(pipeline_result: Exception, exception_class_name: str): + assert pipeline_result.__class__.__name__ == exception_class_name diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/features/pipeline_run.feature b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/features/pipeline_run.feature new file mode 100644 index 0000000000000000000000000000000000000000..bdb6d8f30dc0abac2ac06b5cb58d31ebda40fb3b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/features/pipeline_run.feature @@ -0,0 +1,51 @@ +Feature: Pipeline running + + Scenario Outline: Running a correct Pipeline + Given a pipeline + When I run the Pipeline + Then it should return the expected result + And components ran in the expected order + + Examples: + | kind | + | that has no components | + | that is linear | + | that is really complex with lots of components, forks, and loops | + | that has a single component with a default input | + | that has two loops of identical lengths | + | that has two loops of different lengths | + | that has a single loop with two conditional branches | + | that has a component with dynamic inputs defined in init | + | that has two branches that don't merge | + | that has three branches that don't merge | + | that has two branches that merge | + | that has different combinations of branches that merge and do not merge | + | that has two branches, one of which loops back | + | that has a component with mutable input | + | that has a component with mutable output sent to multiple inputs | + | that has a greedy and variadic component after a component with default input | + | that has components added in a different order from the order of execution | + | that has a component with only default inputs | + | that has a component with only default inputs as first to run | + | that has multiple branches that merge into a component with a single variadic input | + | that has multiple branches of different lengths that merge into a component with a single variadic input | + | that is linear and returns intermediate outputs | + | that has a loop and returns intermediate outputs from it | + | that is linear and returns intermediate outputs from multiple sockets | + | that has a component with default inputs that doesn't receive anything from its sender | + | that has a component with default inputs that doesn't receive anything from its sender but receives input from user | + | that has a loop and a component with default inputs that doesn't receive anything from its sender but receives input from user | + | that has multiple components with only default inputs and are added in a different order from the order of execution | + | that is linear with conditional branching and multiple joins | + | that has a variadic component that receives partial inputs | + | that has an answer joiner variadic component | + + 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 | PipelineMaxComponentRuns | + | that has a component that doesn't return a dictionary | PipelineRuntimeError | diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/features/test_run.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/features/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..36c9d844349ea1d6aa176a2b3c6eb1a465b053ba --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/features/test_run.py @@ -0,0 +1,1629 @@ +from typing import List, Optional, Dict, Any + +from pytest_bdd import scenarios, given +import pytest + +from haystack import Pipeline, Document, component +from haystack.dataclasses import ChatMessage, GeneratedAnswer +from haystack.components.routers import ConditionalRouter +from haystack.components.builders import PromptBuilder, AnswerBuilder +from haystack.components.retrievers.in_memory import InMemoryBM25Retriever +from haystack.document_stores.in_memory import InMemoryDocumentStore +from haystack.components.joiners import BranchJoiner, DocumentJoiner, AnswerJoiner +from haystack.testing.sample_components import ( + Accumulate, + AddFixedValue, + Double, + Greet, + Parity, + Repeat, + Subtract, + Sum, + Threshold, + Remainder, + FString, + Hello, + TextSplitter, + StringListJoiner, + SelfLoop, +) +from haystack.testing.factory import component_class + +from test.core.pipeline.features.conftest import PipelineRunData + +pytestmark = pytest.mark.integration + +scenarios("pipeline_run.feature") + + +@given("a pipeline that has no components", target_fixture="pipeline_data") +def pipeline_that_has_no_components(): + pipeline = Pipeline(max_runs_per_component=1) + inputs = {} + expected_outputs = {} + return pipeline, [PipelineRunData(inputs=inputs, expected_outputs=expected_outputs)] + + +@given("a pipeline that is linear", target_fixture="pipeline_data") +def pipeline_that_is_linear(): + pipeline = Pipeline(max_runs_per_component=1) + 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"], + ) + ], + ) + + +@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 = Pipeline(max_runs_per_component=1) + 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}})] + + +@given("a pipeline that is really complex with lots of components, forks, and loops", target_fixture="pipeline_data") +def pipeline_complex(): + pipeline = Pipeline(max_runs_per_component=2) + pipeline.add_component("greet_first", Greet(message="Hello, the value is {value}.")) + pipeline.add_component("accumulate_1", Accumulate()) + pipeline.add_component("add_two", AddFixedValue(add=2)) + pipeline.add_component("parity", Parity()) + pipeline.add_component("add_one", AddFixedValue(add=1)) + pipeline.add_component("accumulate_2", Accumulate()) + + pipeline.add_component("branch_joiner", BranchJoiner(type_=int)) + pipeline.add_component("below_10", Threshold(threshold=10)) + pipeline.add_component("double", Double()) + + pipeline.add_component("greet_again", Greet(message="Hello again, now the value is {value}.")) + pipeline.add_component("sum", Sum()) + + pipeline.add_component("greet_enumerator", Greet(message="Hello from enumerator, here the value became {value}.")) + pipeline.add_component("enumerate", Repeat(outputs=["first", "second"])) + pipeline.add_component("add_three", AddFixedValue(add=3)) + + pipeline.add_component("diff", Subtract()) + pipeline.add_component("greet_one_last_time", Greet(message="Bye bye! The value here is {value}!")) + pipeline.add_component("replicate", Repeat(outputs=["first", "second"])) + pipeline.add_component("add_five", AddFixedValue(add=5)) + pipeline.add_component("add_four", AddFixedValue(add=4)) + pipeline.add_component("accumulate_3", Accumulate()) + + pipeline.connect("greet_first", "accumulate_1") + pipeline.connect("accumulate_1", "add_two") + pipeline.connect("add_two", "parity") + + pipeline.connect("parity.even", "greet_again") + pipeline.connect("greet_again", "sum.values") + pipeline.connect("sum", "diff.first_value") + pipeline.connect("diff", "greet_one_last_time") + pipeline.connect("greet_one_last_time", "replicate") + pipeline.connect("replicate.first", "add_five.value") + pipeline.connect("replicate.second", "add_four.value") + pipeline.connect("add_four", "accumulate_3") + + pipeline.connect("parity.odd", "add_one.value") + pipeline.connect("add_one", "branch_joiner.value") + pipeline.connect("branch_joiner", "below_10") + + pipeline.connect("below_10.below", "double") + pipeline.connect("double", "branch_joiner.value") + + pipeline.connect("below_10.above", "accumulate_2") + pipeline.connect("accumulate_2", "diff.second_value") + + pipeline.connect("greet_enumerator", "enumerate") + pipeline.connect("enumerate.second", "sum.values") + + pipeline.connect("enumerate.first", "add_three.value") + pipeline.connect("add_three", "sum.values") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"greet_first": {"value": 1}, "greet_enumerator": {"value": 1}}, + expected_outputs={"accumulate_3": {"value": -7}, "add_five": {"result": -6}}, + expected_run_order=[ + "greet_first", + "accumulate_1", + "add_two", + "parity", + "add_one", + "branch_joiner", + "below_10", + "double", + "branch_joiner", + "below_10", + "double", + "branch_joiner", + "below_10", + "accumulate_2", + "greet_enumerator", + "enumerate", + "add_three", + "sum", + "diff", + "greet_one_last_time", + "replicate", + "add_five", + "add_four", + "accumulate_3", + ], + ) + ], + ) + + +@given("a pipeline that has a single component with a default input", target_fixture="pipeline_data") +def pipeline_that_has_a_single_component_with_a_default_input(): + @component + class WithDefault: + @component.output_types(b=int) + def run(self, a: int, b: int = 2): + return {"c": a + b} + + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("with_defaults", WithDefault()) + + return ( + pipeline, + [ + PipelineRunData( + inputs={"with_defaults": {"a": 40, "b": 30}}, + expected_outputs={"with_defaults": {"c": 70}}, + expected_run_order=["with_defaults"], + ), + PipelineRunData( + inputs={"with_defaults": {"a": 40}}, + expected_outputs={"with_defaults": {"c": 42}}, + expected_run_order=["with_defaults"], + ), + ], + ) + + +@given("a pipeline that has two loops of identical lengths", target_fixture="pipeline_data") +def pipeline_that_has_two_loops_of_identical_lengths(): + pipeline = Pipeline(max_runs_per_component=10) + pipeline.add_component("branch_joiner", BranchJoiner(type_=int)) + pipeline.add_component("remainder", Remainder(divisor=3)) + pipeline.add_component("add_one", AddFixedValue(add=1)) + pipeline.add_component("add_two", AddFixedValue(add=2)) + + pipeline.connect("branch_joiner.value", "remainder.value") + pipeline.connect("remainder.remainder_is_1", "add_two.value") + pipeline.connect("remainder.remainder_is_2", "add_one.value") + pipeline.connect("add_two", "branch_joiner.value") + pipeline.connect("add_one", "branch_joiner.value") + return ( + pipeline, + [ + PipelineRunData( + inputs={"branch_joiner": {"value": 0}}, + expected_outputs={"remainder": {"remainder_is_0": 0}}, + expected_run_order=["branch_joiner", "remainder"], + ), + PipelineRunData( + inputs={"branch_joiner": {"value": 3}}, + expected_outputs={"remainder": {"remainder_is_0": 3}}, + expected_run_order=["branch_joiner", "remainder"], + ), + PipelineRunData( + inputs={"branch_joiner": {"value": 4}}, + expected_outputs={"remainder": {"remainder_is_0": 6}}, + expected_run_order=["branch_joiner", "remainder", "add_two", "branch_joiner", "remainder"], + ), + PipelineRunData( + inputs={"branch_joiner": {"value": 5}}, + expected_outputs={"remainder": {"remainder_is_0": 6}}, + expected_run_order=["branch_joiner", "remainder", "add_one", "branch_joiner", "remainder"], + ), + PipelineRunData( + inputs={"branch_joiner": {"value": 6}}, + expected_outputs={"remainder": {"remainder_is_0": 6}}, + expected_run_order=["branch_joiner", "remainder"], + ), + ], + ) + + +@given("a pipeline that has two loops of different lengths", target_fixture="pipeline_data") +def pipeline_that_has_two_loops_of_different_lengths(): + pipeline = Pipeline(max_runs_per_component=10) + pipeline.add_component("branch_joiner", BranchJoiner(type_=int)) + pipeline.add_component("remainder", Remainder(divisor=3)) + pipeline.add_component("add_one", AddFixedValue(add=1)) + pipeline.add_component("add_two_1", AddFixedValue(add=1)) + pipeline.add_component("add_two_2", AddFixedValue(add=1)) + + pipeline.connect("branch_joiner.value", "remainder.value") + pipeline.connect("remainder.remainder_is_1", "add_two_1.value") + pipeline.connect("add_two_1", "add_two_2.value") + pipeline.connect("add_two_2", "branch_joiner") + pipeline.connect("remainder.remainder_is_2", "add_one.value") + pipeline.connect("add_one", "branch_joiner") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"branch_joiner": {"value": 0}}, + expected_outputs={"remainder": {"remainder_is_0": 0}}, + expected_run_order=["branch_joiner", "remainder"], + ), + PipelineRunData( + inputs={"branch_joiner": {"value": 3}}, + expected_outputs={"remainder": {"remainder_is_0": 3}}, + expected_run_order=["branch_joiner", "remainder"], + ), + PipelineRunData( + inputs={"branch_joiner": {"value": 4}}, + expected_outputs={"remainder": {"remainder_is_0": 6}}, + expected_run_order=[ + "branch_joiner", + "remainder", + "add_two_1", + "add_two_2", + "branch_joiner", + "remainder", + ], + ), + PipelineRunData( + inputs={"branch_joiner": {"value": 5}}, + expected_outputs={"remainder": {"remainder_is_0": 6}}, + expected_run_order=["branch_joiner", "remainder", "add_one", "branch_joiner", "remainder"], + ), + PipelineRunData( + inputs={"branch_joiner": {"value": 6}}, + expected_outputs={"remainder": {"remainder_is_0": 6}}, + expected_run_order=["branch_joiner", "remainder"], + ), + ], + ) + + +@given("a pipeline that has a single loop with two conditional branches", target_fixture="pipeline_data") +def pipeline_that_has_a_single_loop_with_two_conditional_branches(): + accumulator = Accumulate() + pipeline = Pipeline(max_runs_per_component=10) + + pipeline.add_component("add_one", AddFixedValue(add=1)) + pipeline.add_component("branch_joiner", BranchJoiner(type_=int)) + pipeline.add_component("below_10", Threshold(threshold=10)) + pipeline.add_component("below_5", Threshold(threshold=5)) + pipeline.add_component("add_three", AddFixedValue(add=3)) + pipeline.add_component("accumulator", accumulator) + pipeline.add_component("add_two", AddFixedValue(add=2)) + + pipeline.connect("add_one.result", "branch_joiner") + pipeline.connect("branch_joiner.value", "below_10.value") + pipeline.connect("below_10.below", "accumulator.value") + pipeline.connect("accumulator.value", "below_5.value") + pipeline.connect("below_5.above", "add_three.value") + pipeline.connect("below_5.below", "branch_joiner") + pipeline.connect("add_three.result", "branch_joiner") + pipeline.connect("below_10.above", "add_two.value") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"add_one": {"value": 3}}, + expected_outputs={"add_two": {"result": 13}}, + expected_run_order=[ + "add_one", + "branch_joiner", + "below_10", + "accumulator", + "below_5", + "branch_joiner", + "below_10", + "accumulator", + "below_5", + "add_three", + "branch_joiner", + "below_10", + "add_two", + ], + ) + ], + ) + + +@given("a pipeline that has a component with dynamic inputs defined in init", target_fixture="pipeline_data") +def pipeline_that_has_a_component_with_dynamic_inputs_defined_in_init(): + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("hello", Hello()) + pipeline.add_component("fstring", FString(template="This is the greeting: {greeting}!", variables=["greeting"])) + pipeline.add_component("splitter", TextSplitter()) + pipeline.connect("hello.output", "fstring.greeting") + pipeline.connect("fstring.string", "splitter.sentence") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"hello": {"word": "Alice"}}, + expected_outputs={"splitter": {"output": ["This", "is", "the", "greeting:", "Hello,", "Alice!!"]}}, + expected_run_order=["hello", "fstring", "splitter"], + ), + PipelineRunData( + inputs={"hello": {"word": "Alice"}, "fstring": {"template": "Received: {greeting}"}}, + expected_outputs={"splitter": {"output": ["Received:", "Hello,", "Alice!"]}}, + expected_run_order=["hello", "fstring", "splitter"], + ), + ], + ) + + +@given("a pipeline that has two branches that don't merge", target_fixture="pipeline_data") +def pipeline_that_has_two_branches_that_dont_merge(): + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("add_one", AddFixedValue(add=1)) + pipeline.add_component("parity", Parity()) + pipeline.add_component("add_ten", AddFixedValue(add=10)) + pipeline.add_component("double", Double()) + pipeline.add_component("add_three", AddFixedValue(add=3)) + + pipeline.connect("add_one.result", "parity.value") + pipeline.connect("parity.even", "add_ten.value") + pipeline.connect("parity.odd", "double.value") + pipeline.connect("add_ten.result", "add_three.value") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"add_one": {"value": 1}}, + expected_outputs={"add_three": {"result": 15}}, + expected_run_order=["add_one", "parity", "add_ten", "add_three"], + ), + PipelineRunData( + inputs={"add_one": {"value": 2}}, + expected_outputs={"double": {"value": 6}}, + expected_run_order=["add_one", "parity", "double"], + ), + ], + ) + + +@given("a pipeline that has three branches that don't merge", target_fixture="pipeline_data") +def pipeline_that_has_three_branches_that_dont_merge(): + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("add_one", AddFixedValue(add=1)) + pipeline.add_component("repeat", Repeat(outputs=["first", "second"])) + pipeline.add_component("add_ten", AddFixedValue(add=10)) + pipeline.add_component("double", Double()) + pipeline.add_component("add_three", AddFixedValue(add=3)) + pipeline.add_component("add_one_again", AddFixedValue(add=1)) + + pipeline.connect("add_one.result", "repeat.value") + pipeline.connect("repeat.first", "add_ten.value") + pipeline.connect("repeat.second", "double.value") + pipeline.connect("repeat.second", "add_three.value") + pipeline.connect("add_three.result", "add_one_again.value") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"add_one": {"value": 1}}, + expected_outputs={"add_one_again": {"result": 6}, "add_ten": {"result": 12}, "double": {"value": 4}}, + expected_run_order=["add_one", "repeat", "add_ten", "double", "add_three", "add_one_again"], + ) + ], + ) + + +@given("a pipeline that has two branches that merge", target_fixture="pipeline_data") +def pipeline_that_has_two_branches_that_merge(): + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("first_addition", AddFixedValue(add=2)) + pipeline.add_component("second_addition", AddFixedValue(add=2)) + pipeline.add_component("third_addition", AddFixedValue(add=2)) + pipeline.add_component("diff", Subtract()) + pipeline.add_component("fourth_addition", AddFixedValue(add=1)) + + pipeline.connect("first_addition.result", "second_addition.value") + pipeline.connect("second_addition.result", "diff.first_value") + pipeline.connect("third_addition.result", "diff.second_value") + pipeline.connect("diff", "fourth_addition.value") + return ( + pipeline, + [ + PipelineRunData( + inputs={"first_addition": {"value": 1}, "third_addition": {"value": 1}}, + expected_outputs={"fourth_addition": {"result": 3}}, + expected_run_order=["first_addition", "third_addition", "second_addition", "diff", "fourth_addition"], + ) + ], + ) + + +@given( + "a pipeline that has different combinations of branches that merge and do not merge", target_fixture="pipeline_data" +) +def pipeline_that_has_different_combinations_of_branches_that_merge_and_do_not_merge(): + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("add_one", AddFixedValue()) + pipeline.add_component("parity", Parity()) + pipeline.add_component("add_ten", AddFixedValue(add=10)) + pipeline.add_component("double", Double()) + pipeline.add_component("add_four", AddFixedValue(add=4)) + pipeline.add_component("add_two", AddFixedValue()) + pipeline.add_component("add_two_as_well", AddFixedValue()) + pipeline.add_component("diff", Subtract()) + + pipeline.connect("add_one.result", "parity.value") + pipeline.connect("parity.even", "add_four.value") + pipeline.connect("parity.odd", "double.value") + pipeline.connect("add_ten.result", "diff.first_value") + pipeline.connect("double.value", "diff.second_value") + pipeline.connect("parity.odd", "add_ten.value") + pipeline.connect("add_four.result", "add_two.value") + pipeline.connect("add_four.result", "add_two_as_well.value") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"add_one": {"value": 1}, "add_two": {"add": 2}, "add_two_as_well": {"add": 2}}, + expected_outputs={"add_two": {"result": 8}, "add_two_as_well": {"result": 8}}, + expected_run_order=["add_one", "parity", "add_four", "add_two", "add_two_as_well"], + ), + PipelineRunData( + inputs={"add_one": {"value": 2}, "add_two": {"add": 2}, "add_two_as_well": {"add": 2}}, + expected_outputs={"diff": {"difference": 7}}, + expected_run_order=["add_one", "parity", "double", "add_ten", "diff"], + ), + ], + ) + + +@given("a pipeline that has two branches, one of which loops back", target_fixture="pipeline_data") +def pipeline_that_has_two_branches_one_of_which_loops_back(): + pipeline = Pipeline(max_runs_per_component=10) + pipeline.add_component("add_zero", AddFixedValue(add=0)) + pipeline.add_component("branch_joiner", BranchJoiner(type_=int)) + pipeline.add_component("sum", Sum()) + pipeline.add_component("below_10", Threshold(threshold=10)) + pipeline.add_component("add_one", AddFixedValue(add=1)) + pipeline.add_component("counter", Accumulate()) + pipeline.add_component("add_two", AddFixedValue(add=2)) + + pipeline.connect("add_zero", "branch_joiner.value") + pipeline.connect("branch_joiner", "below_10.value") + pipeline.connect("below_10.below", "add_one.value") + pipeline.connect("add_one.result", "counter.value") + pipeline.connect("counter.value", "branch_joiner.value") + pipeline.connect("below_10.above", "add_two.value") + pipeline.connect("add_two.result", "sum.values") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"add_zero": {"value": 8}, "sum": {"values": 2}}, + expected_outputs={"sum": {"total": 23}}, + expected_run_order=[ + "add_zero", + "branch_joiner", + "below_10", + "add_one", + "counter", + "branch_joiner", + "below_10", + "add_one", + "counter", + "branch_joiner", + "below_10", + "add_two", + "sum", + ], + ) + ], + ) + + +@given("a pipeline that has a component with mutable input", target_fixture="pipeline_data") +def pipeline_that_has_a_component_with_mutable_input(): + @component + class InputMangler: + @component.output_types(mangled_list=List[str]) + def run(self, input_list: List[str]): + input_list.append("extra_item") + return {"mangled_list": input_list} + + pipe = Pipeline(max_runs_per_component=1) + pipe.add_component("mangler1", InputMangler()) + pipe.add_component("mangler2", InputMangler()) + pipe.add_component("concat1", StringListJoiner()) + pipe.add_component("concat2", StringListJoiner()) + pipe.connect("mangler1", "concat1") + pipe.connect("mangler2", "concat2") + + input_list = ["foo", "bar"] + + return ( + pipe, + [ + PipelineRunData( + inputs={"mangler1": {"input_list": input_list}, "mangler2": {"input_list": input_list}}, + expected_outputs={ + "concat1": {"output": ["foo", "bar", "extra_item"]}, + "concat2": {"output": ["foo", "bar", "extra_item"]}, + }, + expected_run_order=["mangler1", "mangler2", "concat1", "concat2"], + ) + ], + ) + + +@given("a pipeline that has a component with mutable output sent to multiple inputs", target_fixture="pipeline_data") +def pipeline_that_has_a_component_with_mutable_output_sent_to_multiple_inputs(): + @component + class PassThroughPromptBuilder: + # This is a pass-through component that returns the same input + @component.output_types(prompt=List[ChatMessage]) + def run(self, prompt_source: List[ChatMessage]): + return {"prompt": prompt_source} + + @component + class MessageMerger: + @component.output_types(merged_message=str) + def run(self, messages: List[ChatMessage], metadata: dict = None): + return {"merged_message": "\n".join(t.content for t in messages)} + + @component + class FakeGenerator: + # This component is a fake generator that always returns the same message + @component.output_types(replies=List[ChatMessage]) + def run(self, messages: List[ChatMessage]): + return {"replies": [ChatMessage.from_assistant("Fake message")]} + + prompt_builder = PassThroughPromptBuilder() + llm = FakeGenerator() + mm1 = MessageMerger() + mm2 = MessageMerger() + + pipe = Pipeline(max_runs_per_component=1) + pipe.add_component("prompt_builder", prompt_builder) + pipe.add_component("llm", llm) + pipe.add_component("mm1", mm1) + pipe.add_component("mm2", mm2) + + pipe.connect("prompt_builder.prompt", "llm.messages") + pipe.connect("prompt_builder.prompt", "mm1") + pipe.connect("llm.replies", "mm2") + + messages = [ + ChatMessage.from_system("Always respond in English even if some input data is in other languages."), + ChatMessage.from_user("Tell me about Berlin"), + ] + params = {"metadata": {"metadata_key": "metadata_value", "meta2": "value2"}} + + return ( + pipe, + [ + PipelineRunData( + inputs={"mm1": params, "mm2": params, "prompt_builder": {"prompt_source": messages}}, + expected_outputs={ + "mm1": { + "merged_message": "Always respond " + "in English even " + "if some input " + "data is in other " + "languages.\n" + "Tell me about " + "Berlin" + }, + "mm2": {"merged_message": "Fake message"}, + }, + expected_run_order=["prompt_builder", "llm", "mm1", "mm2"], + ) + ], + ) + + +@given( + "a pipeline that has a greedy and variadic component after a component with default input", + target_fixture="pipeline_data", +) +def pipeline_that_has_a_greedy_and_variadic_component_after_a_component_with_default_input(): + """ + This test verifies that `Pipeline.run()` executes the components in the correct order when + there's a greedy Component with variadic input right before a Component with at least one default input. + + We use the `spying_tracer` fixture to simplify the code to verify the order of execution. + This creates some coupling between this test and how we trace the Pipeline execution. + A worthy tradeoff in my opinion, we will notice right away if we change either the run logic or + the tracing logic. + """ + document_store = InMemoryDocumentStore() + document_store.write_documents([Document(content="This is a simple document")]) + + pipeline = Pipeline(max_runs_per_component=1) + template = "Given this documents: {{ documents|join(', ', attribute='content') }} Answer this question: {{ query }}" + pipeline.add_component("retriever", InMemoryBM25Retriever(document_store=document_store)) + pipeline.add_component("prompt_builder", PromptBuilder(template=template)) + pipeline.add_component("branch_joiner", BranchJoiner(List[Document])) + + pipeline.connect("retriever", "branch_joiner") + pipeline.connect("branch_joiner", "prompt_builder.documents") + return ( + pipeline, + [ + PipelineRunData( + inputs={"query": "This is my question"}, + expected_outputs={ + "prompt_builder": { + "prompt": "Given this " + "documents: " + "This is a " + "simple " + "document " + "Answer this " + "question: " + "This is my " + "question" + } + }, + expected_run_order=["retriever", "branch_joiner", "prompt_builder"], + ) + ], + ) + + +@given("a pipeline that has a component that doesn't return a dictionary", target_fixture="pipeline_data") +def pipeline_that_has_a_component_that_doesnt_return_a_dictionary(): + BrokenComponent = component_class( + "BrokenComponent", + input_types={"a": int}, + output_types={"b": int}, + output=1, # type:ignore + ) + + pipe = Pipeline(max_runs_per_component=10) + pipe.add_component("comp", BrokenComponent()) + return pipe, [PipelineRunData({"comp": {"a": 1}})] + + +@given( + "a pipeline that has components added in a different order from the order of execution", + target_fixture="pipeline_data", +) +def pipeline_that_has_components_added_in_a_different_order_from_the_order_of_execution(): + """ + We enqueue the Components in internal `to_run` data structure at the start of `Pipeline.run()` using the order + they are added in the Pipeline with `Pipeline.add_component()`. + 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 it could run instead before. + + This test verifies that the order of execution is correct. + """ + docs = [Document(content="Rome is the capital of Italy"), Document(content="Paris is the capital of France")] + doc_store = InMemoryDocumentStore() + doc_store.write_documents(docs) + template = ( + "Given the following information, answer the question.\n" + "Context:\n" + "{% for document in documents %}" + " {{ document.content }}\n" + "{% endfor %}" + "Question: {{ query }}" + ) + + pipe = Pipeline(max_runs_per_component=1) + + # The order of this addition is important for the test + # Do not edit them. + pipe.add_component("prompt_builder", PromptBuilder(template=template)) + pipe.add_component("retriever", InMemoryBM25Retriever(document_store=doc_store)) + pipe.connect("retriever", "prompt_builder.documents") + + query = "What is the capital of France?" + return ( + pipe, + [ + PipelineRunData( + inputs={"prompt_builder": {"query": query}, "retriever": {"query": query}}, + expected_outputs={ + "prompt_builder": { + "prompt": "Given the " + "following " + "information, " + "answer the " + "question.\n" + "Context:\n" + " Paris is " + "the capital " + "of France\n" + " Rome is " + "the capital " + "of Italy\n" + "Question: " + "What is the " + "capital of " + "France?" + } + }, + expected_run_order=["retriever", "prompt_builder"], + ) + ], + ) + + +@given("a pipeline that has a component with only default inputs", target_fixture="pipeline_data") +def pipeline_that_has_a_component_with_only_default_inputs(): + FakeGenerator = component_class( + "FakeGenerator", input_types={"prompt": str}, output_types={"replies": List[str]}, output={"replies": ["Paris"]} + ) + docs = [Document(content="Rome is the capital of Italy"), Document(content="Paris is the capital of France")] + doc_store = InMemoryDocumentStore() + doc_store.write_documents(docs) + template = ( + "Given the following information, answer the question.\n" + "Context:\n" + "{% for document in documents %}" + " {{ document.content }}\n" + "{% endfor %}" + "Question: {{ query }}" + ) + + pipe = Pipeline(max_runs_per_component=1) + + pipe.add_component("retriever", InMemoryBM25Retriever(document_store=doc_store)) + pipe.add_component("prompt_builder", PromptBuilder(template=template)) + pipe.add_component("generator", FakeGenerator()) + pipe.add_component("answer_builder", AnswerBuilder()) + + pipe.connect("retriever", "prompt_builder.documents") + pipe.connect("prompt_builder.prompt", "generator.prompt") + pipe.connect("generator.replies", "answer_builder.replies") + pipe.connect("retriever.documents", "answer_builder.documents") + + return ( + pipe, + [ + PipelineRunData( + inputs={"query": "What is the capital of France?"}, + expected_outputs={ + "answer_builder": { + "answers": [ + GeneratedAnswer( + data="Paris", + query="What " "is " "the " "capital " "of " "France?", + documents=[ + Document( + id="413dccdf51a54cca75b7ed2eddac04e6e58560bd2f0caf4106a3efc023fe3651", + content="Paris is the capital of France", + score=1.600237583702734, + ), + Document( + id="a4a874fc2ef75015da7924d709fbdd2430e46a8e94add6e0f26cd32c1c03435d", + content="Rome is the capital of Italy", + score=1.2536639934227616, + ), + ], + meta={}, + ) + ] + } + }, + expected_run_order=["retriever", "prompt_builder", "generator", "answer_builder"], + ) + ], + ) + + +@given("a pipeline that has a component with only default inputs as first to run", target_fixture="pipeline_data") +def pipeline_that_has_a_component_with_only_default_inputs_as_first_to_run(): + """ + This tests verifies that a Pipeline doesn't get stuck running in a loop if + it has all the following characterics: + - The first Component has all defaults for its inputs + - The first Component receives one input from the user + - The first Component receives one input from a loop in the Pipeline + - The second Component has at least one default input + """ + + def fake_generator_run(self, generation_kwargs: Optional[Dict[str, Any]] = None, **kwargs): + # Simple hack to simulate a model returning a different reply after the + # the first time it's called + if getattr(fake_generator_run, "called", False): + return {"replies": ["Rome"]} + fake_generator_run.called = True + return {"replies": ["Paris"]} + + FakeGenerator = component_class( + "FakeGenerator", + input_types={"prompt": str}, + output_types={"replies": List[str]}, + extra_fields={"run": fake_generator_run}, + ) + template = ( + "Answer the following question.\n" + "{% if previous_replies %}\n" + "Previously you replied incorrectly this:\n" + "{% for reply in previous_replies %}\n" + " - {{ reply }}\n" + "{% endfor %}\n" + "{% endif %}\n" + "Question: {{ query }}" + ) + router = ConditionalRouter( + routes=[ + { + "condition": "{{ replies == ['Rome'] }}", + "output": "{{ replies }}", + "output_name": "correct_replies", + "output_type": List[int], + }, + { + "condition": "{{ replies == ['Paris'] }}", + "output": "{{ replies }}", + "output_name": "incorrect_replies", + "output_type": List[int], + }, + ] + ) + + pipe = Pipeline(max_runs_per_component=1) + + pipe.add_component("prompt_builder", PromptBuilder(template=template)) + pipe.add_component("generator", FakeGenerator()) + pipe.add_component("router", router) + + pipe.connect("prompt_builder.prompt", "generator.prompt") + pipe.connect("generator.replies", "router.replies") + pipe.connect("router.incorrect_replies", "prompt_builder.previous_replies") + + return ( + pipe, + [ + PipelineRunData( + inputs={"prompt_builder": {"query": "What is the capital of " "Italy?"}}, + expected_outputs={"router": {"correct_replies": ["Rome"]}}, + expected_run_order=["prompt_builder", "generator", "router", "prompt_builder", "generator", "router"], + ) + ], + ) + + +@given( + "a pipeline that has multiple branches that merge into a component with a single variadic input", + target_fixture="pipeline_data", +) +def pipeline_that_has_multiple_branches_that_merge_into_a_component_with_a_single_variadic_input(): + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("add_one", AddFixedValue()) + pipeline.add_component("parity", Remainder(divisor=2)) + pipeline.add_component("add_ten", AddFixedValue(add=10)) + pipeline.add_component("double", Double()) + pipeline.add_component("add_four", AddFixedValue(add=4)) + pipeline.add_component("add_one_again", AddFixedValue()) + pipeline.add_component("sum", Sum()) + + pipeline.connect("add_one.result", "parity.value") + pipeline.connect("parity.remainder_is_0", "add_ten.value") + pipeline.connect("parity.remainder_is_1", "double.value") + pipeline.connect("add_one.result", "sum.values") + pipeline.connect("add_ten.result", "sum.values") + pipeline.connect("double.value", "sum.values") + pipeline.connect("parity.remainder_is_1", "add_four.value") + pipeline.connect("add_four.result", "add_one_again.value") + pipeline.connect("add_one_again.result", "sum.values") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"add_one": {"value": 1}}, + expected_outputs={"sum": {"total": 14}}, + expected_run_order=["add_one", "parity", "add_ten", "sum"], + ), + PipelineRunData( + inputs={"add_one": {"value": 2}}, + expected_outputs={"sum": {"total": 17}}, + expected_run_order=["add_one", "parity", "double", "add_four", "add_one_again", "sum"], + ), + ], + ) + + +@given( + "a pipeline that has multiple branches of different lengths that merge into a component with a single variadic input", + target_fixture="pipeline_data", +) +def pipeline_that_has_multiple_branches_of_different_lengths_that_merge_into_a_component_with_a_single_variadic_input(): + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("first_addition", AddFixedValue(add=2)) + pipeline.add_component("second_addition", AddFixedValue(add=2)) + pipeline.add_component("third_addition", AddFixedValue(add=2)) + pipeline.add_component("sum", Sum()) + pipeline.add_component("fourth_addition", AddFixedValue(add=1)) + + pipeline.connect("first_addition.result", "second_addition.value") + pipeline.connect("first_addition.result", "sum.values") + pipeline.connect("second_addition.result", "sum.values") + pipeline.connect("third_addition.result", "sum.values") + pipeline.connect("sum.total", "fourth_addition.value") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"first_addition": {"value": 1}, "third_addition": {"value": 1}}, + expected_outputs={"fourth_addition": {"result": 12}}, + expected_run_order=["first_addition", "third_addition", "second_addition", "sum", "fourth_addition"], + ) + ], + ) + + +@given("a pipeline that is linear and returns intermediate outputs", target_fixture="pipeline_data") +def pipeline_that_is_linear_and_returns_intermediate_outputs(): + pipeline = Pipeline(max_runs_per_component=1) + 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={"second_addition", "double", "first_addition"}, + expected_outputs={ + "double": {"value": 6}, + "first_addition": {"result": 3}, + "second_addition": {"result": 7}, + }, + expected_run_order=["first_addition", "double", "second_addition"], + ), + PipelineRunData( + inputs={"first_addition": {"value": 1}}, + include_outputs_from={"double"}, + expected_outputs={"double": {"value": 6}, "second_addition": {"result": 7}}, + expected_run_order=["first_addition", "double", "second_addition"], + ), + ], + ) + + +@given("a pipeline that has a loop and returns intermediate outputs from it", target_fixture="pipeline_data") +def pipeline_that_has_a_loop_and_returns_intermediate_outputs_from_it(): + pipeline = Pipeline(max_runs_per_component=10) + pipeline.add_component("add_one", AddFixedValue(add=1)) + pipeline.add_component("branch_joiner", BranchJoiner(type_=int)) + pipeline.add_component("below_10", Threshold(threshold=10)) + pipeline.add_component("below_5", Threshold(threshold=5)) + pipeline.add_component("add_three", AddFixedValue(add=3)) + pipeline.add_component("accumulator", Accumulate()) + pipeline.add_component("add_two", AddFixedValue(add=2)) + + pipeline.connect("add_one.result", "branch_joiner") + pipeline.connect("branch_joiner.value", "below_10.value") + pipeline.connect("below_10.below", "accumulator.value") + pipeline.connect("accumulator.value", "below_5.value") + pipeline.connect("below_5.above", "add_three.value") + pipeline.connect("below_5.below", "branch_joiner") + pipeline.connect("add_three.result", "branch_joiner") + pipeline.connect("below_10.above", "add_two.value") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"add_one": {"value": 3}}, + include_outputs_from={ + "add_two", + "add_one", + "branch_joiner", + "below_10", + "accumulator", + "below_5", + "add_three", + }, + expected_outputs={ + "add_two": {"result": 13}, + "add_one": {"result": 4}, + "branch_joiner": {"value": 11}, + "below_10": {"above": 11}, + "accumulator": {"value": 8}, + "below_5": {"above": 8}, + "add_three": {"result": 11}, + }, + expected_run_order=[ + "add_one", + "branch_joiner", + "below_10", + "accumulator", + "below_5", + "branch_joiner", + "below_10", + "accumulator", + "below_5", + "add_three", + "branch_joiner", + "below_10", + "add_two", + ], + ) + ], + ) + + +@given( + "a pipeline that is linear and returns intermediate outputs from multiple sockets", target_fixture="pipeline_data" +) +def pipeline_that_is_linear_and_returns_intermediate_outputs_from_multiple_sockets(): + @component + class DoubleWithOriginal: + """ + Doubles the input value and returns the original value as well. + """ + + @component.output_types(value=int, original=int) + def run(self, value: int): + return {"value": value * 2, "original": value} + + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("first_addition", AddFixedValue(add=2)) + pipeline.add_component("second_addition", AddFixedValue()) + pipeline.add_component("double", DoubleWithOriginal()) + pipeline.connect("first_addition", "double") + pipeline.connect("double.value", "second_addition") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"first_addition": {"value": 1}}, + include_outputs_from={"second_addition", "double", "first_addition"}, + expected_outputs={ + "double": {"original": 3, "value": 6}, + "first_addition": {"result": 3}, + "second_addition": {"result": 7}, + }, + expected_run_order=["first_addition", "double", "second_addition"], + ), + PipelineRunData( + inputs={"first_addition": {"value": 1}}, + include_outputs_from={"double"}, + expected_outputs={"double": {"original": 3, "value": 6}, "second_addition": {"result": 7}}, + expected_run_order=["first_addition", "double", "second_addition"], + ), + ], + ) + + +@given( + "a pipeline that has a component with default inputs that doesn't receive anything from its sender", + target_fixture="pipeline_data", +) +def pipeline_that_has_a_component_with_default_inputs_that_doesnt_receive_anything_from_its_sender(): + routes = [ + {"condition": "{{'reisen' in sentence}}", "output": "German", "output_name": "language_1", "output_type": str}, + {"condition": "{{'viajar' in sentence}}", "output": "Spanish", "output_name": "language_2", "output_type": str}, + ] + router = ConditionalRouter(routes) + + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("router", router) + pipeline.add_component("pb", PromptBuilder(template="Ok, I know, that's {{language}}")) + pipeline.connect("router.language_2", "pb.language") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"router": {"sentence": "Wir mussen reisen"}}, + expected_outputs={"router": {"language_1": "German"}}, + expected_run_order=["router"], + ), + PipelineRunData( + inputs={"router": {"sentence": "Yo tengo que viajar"}}, + expected_outputs={"pb": {"prompt": "Ok, I know, that's Spanish"}}, + expected_run_order=["router", "pb"], + ), + ], + ) + + +@given( + "a pipeline that has a component with default inputs that doesn't receive anything from its sender but receives input from user", + target_fixture="pipeline_data", +) +def pipeline_that_has_a_component_with_default_inputs_that_doesnt_receive_anything_from_its_sender_but_receives_input_from_user(): + prompt = PromptBuilder( + template="""Please generate an SQL query. The query should answer the following Question: {{ question }}; + If the question cannot be answered given the provided table and columns, return 'no_answer' + The query is to be answered for the table is called 'absenteeism' with the following + Columns: {{ columns }}; + Answer:""" + ) + + @component + class FakeGenerator: + @component.output_types(replies=List[str]) + def run(self, prompt: str): + if "no_answer" in prompt: + return {"replies": ["There's simply no_answer to this question"]} + return {"replies": ["Some SQL query"]} + + @component + class FakeSQLQuerier: + @component.output_types(results=str) + def run(self, query: str): + return {"results": "This is the query result", "query": query} + + llm = FakeGenerator() + sql_querier = FakeSQLQuerier() + + routes = [ + { + "condition": "{{'no_answer' not in replies[0]}}", + "output": "{{replies[0]}}", + "output_name": "sql", + "output_type": str, + }, + { + "condition": "{{'no_answer' in replies[0]}}", + "output": "{{question}}", + "output_name": "go_to_fallback", + "output_type": str, + }, + ] + + router = ConditionalRouter(routes) + + fallback_prompt = PromptBuilder( + template="""User entered a query that cannot be answered with the given table. + The query was: {{ question }} and the table had columns: {{ columns }}. + Let the user know why the question cannot be answered""" + ) + fallback_llm = FakeGenerator() + + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("prompt", prompt) + pipeline.add_component("llm", llm) + pipeline.add_component("router", router) + pipeline.add_component("fallback_prompt", fallback_prompt) + pipeline.add_component("fallback_llm", fallback_llm) + pipeline.add_component("sql_querier", sql_querier) + + pipeline.connect("prompt", "llm") + pipeline.connect("llm.replies", "router.replies") + pipeline.connect("router.sql", "sql_querier.query") + pipeline.connect("router.go_to_fallback", "fallback_prompt.question") + pipeline.connect("fallback_prompt", "fallback_llm") + + columns = "Age, Absenteeism_time_in_hours, Days, Disciplinary_failure" + return ( + pipeline, + [ + PipelineRunData( + inputs={ + "prompt": {"question": "This is a question with no_answer", "columns": columns}, + "router": {"question": "This is a question with no_answer"}, + }, + expected_outputs={"fallback_llm": {"replies": ["There's simply no_answer to this question"]}}, + expected_run_order=["prompt", "llm", "router", "fallback_prompt", "fallback_llm"], + ) + ], + [ + PipelineRunData( + inputs={ + "prompt": {"question": "This is a question that has an answer", "columns": columns}, + "router": {"question": "This is a question that has an answer"}, + }, + expected_outputs={"sql_querier": {"results": "This is the query result", "query": "Some SQL query"}}, + expected_run_order=["prompt", "llm", "router", "sql_querier"], + ) + ], + ) + + +@given( + "a pipeline that has a loop and a component with default inputs that doesn't receive anything from its sender but receives input from user", + target_fixture="pipeline_data", +) +def pipeline_that_has_a_loop_and_a_component_with_default_inputs_that_doesnt_receive_anything_from_its_sender_but_receives_input_from_user(): + template = """ + You are an experienced and accurate Turkish CX speacialist that classifies customer comments into pre-defined categories below:\n + Negative experience labels: + - Late delivery + - Rotten/spoilt item + - Bad Courier behavior + + Positive experience labels: + - Good courier behavior + - Thanks & appreciation + - Love message to courier + - Fast delivery + - Quality of products + + Create a JSON object as a response. The fields are: 'positive_experience', 'negative_experience'. + Assign at least one of the pre-defined labels to the given customer comment under positive and negative experience fields. + If the comment has a positive experience, list the label under 'positive_experience' field. + If the comments has a negative_experience, list it under the 'negative_experience' field. + Here is the comment:\n{{ comment }}\n. Just return the category names in the list. If there aren't any, return an empty list. + + {% if invalid_replies and error_message %} + You already created the following output in a previous attempt: {{ invalid_replies }} + However, this doesn't comply with the format requirements from above and triggered this Python exception: {{ error_message }} + Correct the output and try again. Just return the corrected output without any extra explanations. + {% endif %} + """ + prompt_builder = PromptBuilder(template=template) + + @component + class FakeOutputValidator: + @component.output_types( + valid_replies=List[str], invalid_replies=Optional[List[str]], error_message=Optional[str] + ) + def run(self, replies: List[str]): + if not getattr(self, "called", False): + self.called = True + return {"invalid_replies": ["This is an invalid reply"], "error_message": "this is an error message"} + return {"valid_replies": replies} + + @component + class FakeGenerator: + @component.output_types(replies=List[str]) + def run(self, prompt: str): + return {"replies": ["This is a valid reply"]} + + llm = FakeGenerator() + validator = FakeOutputValidator() + + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("prompt_builder", prompt_builder) + + pipeline.add_component("llm", llm) + pipeline.add_component("output_validator", validator) + + pipeline.connect("prompt_builder.prompt", "llm.prompt") + pipeline.connect("llm.replies", "output_validator.replies") + pipeline.connect("output_validator.invalid_replies", "prompt_builder.invalid_replies") + + pipeline.connect("output_validator.error_message", "prompt_builder.error_message") + + comment = "I loved the quality of the meal but the courier was rude" + return ( + pipeline, + [ + PipelineRunData( + inputs={"prompt_builder": {"template_variables": {"comment": comment}}}, + expected_outputs={"output_validator": {"valid_replies": ["This is a valid reply"]}}, + expected_run_order=[ + "prompt_builder", + "llm", + "output_validator", + "prompt_builder", + "llm", + "output_validator", + ], + ) + ], + ) + + +@given( + "a pipeline that has multiple components with only default inputs and are added in a different order from the order of execution", + target_fixture="pipeline_data", +) +def pipeline_that_has_multiple_components_with_only_default_inputs_and_are_added_in_a_different_order_from_the_order_of_execution(): + prompt_builder1 = PromptBuilder( + template=""" + You are a spellchecking system. Check the given query and fill in the corrected query. + + Question: {{question}} + Corrected question: + """ + ) + prompt_builder2 = PromptBuilder( + template=""" + According to these documents: + + {% for doc in documents %} + {{ doc.content }} + {% endfor %} + + Answer the given question: {{question}} + Answer: + """ + ) + prompt_builder3 = PromptBuilder( + template=""" + {% for ans in replies %} + {{ ans }} + {% endfor %} + """ + ) + + @component + class FakeRetriever: + @component.output_types(documents=List[Document]) + def run( + self, + query: str, + filters: Optional[Dict[str, Any]] = None, + top_k: Optional[int] = None, + scale_score: Optional[bool] = None, + ): + return {"documents": [Document(content="This is a document")]} + + @component + class FakeRanker: + @component.output_types(documents=List[Document]) + def run( + self, + query: str, + documents: List[Document], + top_k: Optional[int] = None, + scale_score: Optional[bool] = None, + calibration_factor: Optional[float] = None, + score_threshold: Optional[float] = None, + ): + return {"documents": documents} + + @component + class FakeGenerator: + @component.output_types(replies=List[str], meta=Dict[str, Any]) + def run(self, prompt: str, generation_kwargs: Optional[Dict[str, Any]] = None): + return {"replies": ["This is a reply"], "meta": {"meta_key": "meta_value"}} + + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component(name="retriever", instance=FakeRetriever()) + pipeline.add_component(name="ranker", instance=FakeRanker()) + pipeline.add_component(name="prompt_builder2", instance=prompt_builder2) + pipeline.add_component(name="prompt_builder1", instance=prompt_builder1) + pipeline.add_component(name="prompt_builder3", instance=prompt_builder3) + pipeline.add_component(name="llm", instance=FakeGenerator()) + pipeline.add_component(name="spellchecker", instance=FakeGenerator()) + + pipeline.connect("prompt_builder1", "spellchecker") + pipeline.connect("spellchecker.replies", "prompt_builder3") + pipeline.connect("prompt_builder3", "retriever.query") + pipeline.connect("prompt_builder3", "ranker.query") + pipeline.connect("retriever.documents", "ranker.documents") + pipeline.connect("ranker.documents", "prompt_builder2.documents") + pipeline.connect("prompt_builder3", "prompt_builder2.question") + pipeline.connect("prompt_builder2", "llm") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"prompt_builder1": {"question": "Wha i Acromegaly?"}}, + expected_outputs={ + "llm": {"replies": ["This is a reply"], "meta": {"meta_key": "meta_value"}}, + "spellchecker": {"meta": {"meta_key": "meta_value"}}, + }, + expected_run_order=[ + "prompt_builder1", + "spellchecker", + "prompt_builder3", + "retriever", + "ranker", + "prompt_builder2", + "llm", + ], + ) + ], + ) + + +@given("a pipeline that is linear with conditional branching and multiple joins", target_fixture="pipeline_data") +def that_is_linear_with_conditional_branching_and_multiple_joins(): + pipeline = Pipeline() + + @component + class FakeRouter: + @component.output_types(LEGIT=str, INJECTION=str) + def run(self, query: str): + if "injection" in query: + return {"INJECTION": query} + return {"LEGIT": query} + + @component + class FakeEmbedder: + @component.output_types(embeddings=List[float]) + def run(self, text: str): + return {"embeddings": [1.0, 2.0, 3.0]} + + @component + class FakeRanker: + @component.output_types(documents=List[Document]) + def run(self, query: str, documents: List[Document]): + return {"documents": documents} + + @component + class FakeRetriever: + @component.output_types(documents=List[Document]) + def run(self, query: str): + if "injection" in query: + return {"documents": []} + return {"documents": [Document(content="This is a document")]} + + @component + class FakeEmbeddingRetriever: + @component.output_types(documents=List[Document]) + def run(self, query_embedding: List[float]): + return {"documents": [Document(content="This is another document")]} + + pipeline.add_component(name="router", instance=FakeRouter()) + pipeline.add_component(name="text_embedder", instance=FakeEmbedder()) + pipeline.add_component(name="retriever", instance=FakeEmbeddingRetriever()) + pipeline.add_component(name="emptyretriever", instance=FakeRetriever()) + pipeline.add_component(name="joinerfinal", instance=DocumentJoiner()) + pipeline.add_component(name="joinerhybrid", instance=DocumentJoiner()) + pipeline.add_component(name="ranker", instance=FakeRanker()) + pipeline.add_component(name="bm25retriever", instance=FakeRetriever()) + + pipeline.connect("router.INJECTION", "emptyretriever.query") + pipeline.connect("router.LEGIT", "text_embedder.text") + pipeline.connect("text_embedder", "retriever.query_embedding") + pipeline.connect("router.LEGIT", "ranker.query") + pipeline.connect("router.LEGIT", "bm25retriever.query") + pipeline.connect("bm25retriever", "joinerhybrid.documents") + pipeline.connect("retriever", "joinerhybrid.documents") + pipeline.connect("joinerhybrid.documents", "ranker.documents") + pipeline.connect("ranker", "joinerfinal.documents") + pipeline.connect("emptyretriever", "joinerfinal.documents") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"router": {"query": "I'm a legit question"}}, + expected_outputs={ + "joinerfinal": { + "documents": [ + Document(content="This is a document"), + Document(content="This is another document"), + ] + } + }, + expected_run_order=[ + "router", + "text_embedder", + "bm25retriever", + "retriever", + "joinerhybrid", + "ranker", + "joinerfinal", + ], + ), + PipelineRunData( + inputs={"router": {"query": "I'm a nasty prompt injection"}}, + expected_outputs={"joinerfinal": {"documents": []}}, + expected_run_order=["router", "emptyretriever", "joinerfinal"], + ), + ], + ) + + +@given("a pipeline that has a variadic component that receives partial inputs", target_fixture="pipeline_data") +def that_has_a_variadic_component_that_receives_partial_inputs(): + @component + class ConditionalDocumentCreator: + def __init__(self, content: str): + self._content = content + + @component.output_types(documents=List[Document], noop=None) + def run(self, create_document: bool = False): + if create_document: + return {"documents": [Document(id=self._content, content=self._content)]} + return {"noop": None} + + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("first_creator", ConditionalDocumentCreator(content="First document")) + pipeline.add_component("second_creator", ConditionalDocumentCreator(content="Second document")) + pipeline.add_component("third_creator", ConditionalDocumentCreator(content="Third document")) + pipeline.add_component("documents_joiner", DocumentJoiner()) + + pipeline.connect("first_creator.documents", "documents_joiner.documents") + pipeline.connect("second_creator.documents", "documents_joiner.documents") + pipeline.connect("third_creator.documents", "documents_joiner.documents") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"first_creator": {"create_document": True}, "third_creator": {"create_document": True}}, + expected_outputs={ + "second_creator": {"noop": None}, + "documents_joiner": { + "documents": [ + Document(id="First document", content="First document"), + Document(id="Third document", content="Third document"), + ] + }, + }, + expected_run_order=["first_creator", "third_creator", "second_creator", "documents_joiner"], + ), + PipelineRunData( + inputs={"first_creator": {"create_document": True}, "second_creator": {"create_document": True}}, + expected_outputs={ + "third_creator": {"noop": None}, + "documents_joiner": { + "documents": [ + Document(id="First document", content="First document"), + Document(id="Second document", content="Second document"), + ] + }, + }, + expected_run_order=["first_creator", "second_creator", "third_creator", "documents_joiner"], + ), + ], + ) + + +@given("a pipeline that has an answer joiner variadic component", target_fixture="pipeline_data") +def that_has_an_answer_joiner_variadic_component(): + query = "What's Natural Language Processing?" + + pipeline = Pipeline(max_runs_per_component=1) + pipeline.add_component("answer_builder_1", AnswerBuilder()) + pipeline.add_component("answer_builder_2", AnswerBuilder()) + pipeline.add_component("answer_joiner", AnswerJoiner()) + + pipeline.connect("answer_builder_1.answers", "answer_joiner") + pipeline.connect("answer_builder_2.answers", "answer_joiner") + + return ( + pipeline, + [ + PipelineRunData( + inputs={ + "answer_builder_1": {"query": query, "replies": ["This is a test answer"]}, + "answer_builder_2": {"query": query, "replies": ["This is a second test answer"]}, + }, + expected_outputs={ + "answer_joiner": { + "answers": [ + GeneratedAnswer( + data="This is a test answer", + query="What's Natural Language Processing?", + documents=[], + meta={}, + ), + GeneratedAnswer( + data="This is a second test answer", + query="What's Natural Language Processing?", + documents=[], + meta={}, + ), + ] + } + }, + expected_run_order=["answer_builder_1", "answer_builder_2", "answer_joiner"], + ) + ], + ) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_draw.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_draw.py new file mode 100644 index 0000000000000000000000000000000000000000..f687f6c587c96c7170a978263fbeb99b428cf160 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_draw.py @@ -0,0 +1,96 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from unittest.mock import MagicMock, patch + +import pytest +import requests + +from haystack.core.errors import PipelineDrawingError +from haystack.core.pipeline import Pipeline +from haystack.core.pipeline.draw import _to_mermaid_image, _to_mermaid_text +from haystack.testing.sample_components import AddFixedValue, Double + + +@pytest.mark.flaky(reruns=5, reruns_delay=5) +@pytest.mark.integration +def test_to_mermaid_image(): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + + image_data = _to_mermaid_image(pipe.graph) + # We just verify we received some data as testing the actual image is not reliable + assert image_data + + +@patch("haystack.core.pipeline.draw.requests") +def test_to_mermaid_image_does_not_edit_graph(mock_requests): + pipe = Pipeline() + pipe.add_component("comp1", AddFixedValue(add=3)) + pipe.add_component("comp2", Double()) + pipe.connect("comp1.result", "comp2.value") + pipe.connect("comp2.value", "comp1.value") + + mock_requests.get.return_value = MagicMock(status_code=200) + expected_pipe = pipe.to_dict() + _to_mermaid_image(pipe.graph) + assert expected_pipe == pipe.to_dict() + + +def test_to_mermaid_image_failing_request(tmp_path): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + pipe.connect("comp2", "comp1") + + with patch("haystack.core.pipeline.draw.requests.get") as mock_get: + + def raise_for_status(self): + raise requests.HTTPError() + + mock_response = MagicMock() + mock_response.status_code = 429 + mock_response.content = '{"error": "too many requests"}' + mock_response.raise_for_status = raise_for_status + mock_get.return_value = mock_response + + with pytest.raises(PipelineDrawingError, match="There was an issue with https://mermaid.ink/"): + _to_mermaid_image(pipe.graph) + + +def test_to_mermaid_text(): + pipe = Pipeline() + pipe.add_component("comp1", AddFixedValue(add=3)) + pipe.add_component("comp2", Double()) + pipe.connect("comp1.result", "comp2.value") + pipe.connect("comp2.value", "comp1.value") + + text = _to_mermaid_text(pipe.graph) + assert ( + text + == """ +%%{ init: {'theme': 'neutral' } }%% + +graph TD; + +comp1["comp1
AddFixedValue

Optional inputs:
  • add (Optional[int])
"]:::component -- "result -> value
int" --> comp2["comp2
Double"]:::component +comp2["comp2
Double"]:::component -- "value -> value
int" --> comp1["comp1
AddFixedValue

Optional inputs:
  • add (Optional[int])
"]:::component + +classDef component text-align:center; +""" + ) + + +def test_to_mermaid_text_does_not_edit_graph(): + pipe = Pipeline() + pipe.add_component("comp1", AddFixedValue(add=3)) + pipe.add_component("comp2", Double()) + pipe.connect("comp1.result", "comp2.value") + pipe.connect("comp2.value", "comp1.value") + + expected_pipe = pipe.to_dict() + _to_mermaid_text(pipe.graph) + assert expected_pipe == pipe.to_dict() diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_pipeline.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..3a07c049fc23854d3b25d0edc28562427d3abaf9 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_pipeline.py @@ -0,0 +1,1526 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +from typing import List, Optional +from unittest.mock import patch + +import pytest + +from haystack import Document +from haystack.components.builders import PromptBuilder, AnswerBuilder +from haystack.components.joiners import BranchJoiner +from haystack.core.component import component +from haystack.core.component.types import InputSocket, OutputSocket, Variadic, GreedyVariadic +from haystack.core.errors import DeserializationError, PipelineConnectError, PipelineDrawingError, PipelineError +from haystack.core.pipeline import Pipeline, PredefinedPipeline +from haystack.core.pipeline.base import ( + _add_missing_input_defaults, + _enqueue_component, + _dequeue_component, + _enqueue_waiting_component, + _dequeue_waiting_component, + _is_lazy_variadic, +) +from haystack.core.serialization import DeserializationCallbacks +from haystack.testing.factory import component_class +from haystack.testing.sample_components import AddFixedValue, Double, Greet + +logging.basicConfig(level=logging.DEBUG) + + +@component +class FakeComponent: + def __init__(self, an_init_param: Optional[str] = None): + pass + + @component.output_types(value=str) + def run(self, input_: str): + return {"value": input_} + + +@component +class FakeComponentSquared: + def __init__(self, an_init_param: Optional[str] = None): + self.an_init_param = an_init_param + self.inner = FakeComponent() + + @component.output_types(value=str) + def run(self, input_: str): + return {"value": input_} + + +class TestPipeline: + """ + This class contains only unit tests for the Pipeline class. + It doesn't test Pipeline.run(), that is done separately in a different way. + """ + + def test_pipeline_dumps(self, test_files_path): + pipeline = Pipeline(max_runs_per_component=99) + pipeline.add_component("Comp1", FakeComponent("Foo")) + pipeline.add_component("Comp2", FakeComponent()) + pipeline.connect("Comp1.value", "Comp2.input_") + result = pipeline.dumps() + with open(f"{test_files_path}/yaml/test_pipeline.yaml", "r") as f: + assert f.read() == result + + def test_pipeline_loads_invalid_data(self): + invalid_yaml = """components: + Comp1: + init_parameters: + an_init_param: null + type: test.core.pipeline.test_pipeline.FakeComponent + Comp2* + init_parameters: + an_init_param: null + type: test.core.pipeline.test_pipeline.FakeComponent + connections: + * receiver: Comp2.input_ + sender: Comp1.value + metadata: + """ + + with pytest.raises(DeserializationError, match="unmarshalling serialized"): + pipeline = Pipeline.loads(invalid_yaml) + + invalid_init_parameter_yaml = """components: + Comp1: + init_parameters: + unknown: null + type: test.core.pipeline.test_pipeline.FakeComponent + Comp2: + init_parameters: + an_init_param: null + type: test.core.pipeline.test_pipeline.FakeComponent + connections: + - receiver: Comp2.input_ + sender: Comp1.value + metadata: {} + """ + + with pytest.raises(DeserializationError, match=".*Comp1.*unknown.*"): + pipeline = Pipeline.loads(invalid_init_parameter_yaml) + + def test_pipeline_dump(self, test_files_path, tmp_path): + pipeline = Pipeline(max_runs_per_component=99) + pipeline.add_component("Comp1", FakeComponent("Foo")) + pipeline.add_component("Comp2", FakeComponent()) + pipeline.connect("Comp1.value", "Comp2.input_") + with open(tmp_path / "out.yaml", "w") as f: + pipeline.dump(f) + # re-open and ensure it's the same data as the test file + with open(f"{test_files_path}/yaml/test_pipeline.yaml", "r") as test_f, open(tmp_path / "out.yaml", "r") as f: + assert f.read() == test_f.read() + + def test_pipeline_load(self, test_files_path): + with open(f"{test_files_path}/yaml/test_pipeline.yaml", "r") as f: + pipeline = Pipeline.load(f) + assert pipeline._max_runs_per_component == 99 + assert isinstance(pipeline.get_component("Comp1"), FakeComponent) + assert isinstance(pipeline.get_component("Comp2"), FakeComponent) + + @patch("haystack.core.pipeline.base._to_mermaid_image") + @patch("haystack.core.pipeline.base.is_in_jupyter") + @patch("IPython.display.Image") + @patch("IPython.display.display") + def test_show_in_notebook( + self, mock_ipython_display, mock_ipython_image, mock_is_in_jupyter, mock_to_mermaid_image + ): + pipe = Pipeline() + + mock_to_mermaid_image.return_value = b"some_image_data" + mock_is_in_jupyter.return_value = True + + pipe.show() + mock_ipython_image.assert_called_once_with(b"some_image_data") + mock_ipython_display.assert_called_once() + + @patch("haystack.core.pipeline.base.is_in_jupyter") + def test_show_not_in_notebook(self, mock_is_in_jupyter): + pipe = Pipeline() + + mock_is_in_jupyter.return_value = False + + with pytest.raises(PipelineDrawingError): + pipe.show() + + @patch("haystack.core.pipeline.base._to_mermaid_image") + def test_draw(self, mock_to_mermaid_image, tmp_path): + pipe = Pipeline() + mock_to_mermaid_image.return_value = b"some_image_data" + + image_path = tmp_path / "test.png" + pipe.draw(path=image_path) + assert image_path.read_bytes() == mock_to_mermaid_image.return_value + + # UNIT + def test_add_component_to_different_pipelines(self): + first_pipe = Pipeline() + second_pipe = Pipeline() + some_component = component_class("Some")() + + assert some_component.__haystack_added_to_pipeline__ is None + first_pipe.add_component("some", some_component) + assert some_component.__haystack_added_to_pipeline__ is first_pipe + + with pytest.raises(PipelineError): + second_pipe.add_component("some", some_component) + + def test_remove_component_raises_if_invalid_component_name(self): + pipe = Pipeline() + component = component_class("Some")() + + pipe.add_component("1", component) + + with pytest.raises(ValueError): + pipe.remove_component("2") + + def test_remove_component_removes_component_and_its_edges(self): + pipe = Pipeline() + component_1 = component_class("Type1")() + component_2 = component_class("Type2")() + component_3 = component_class("Type3")() + component_4 = component_class("Type4")() + + pipe.add_component("1", component_1) + pipe.add_component("2", component_2) + pipe.add_component("3", component_3) + pipe.add_component("4", component_4) + + pipe.connect("1", "2") + pipe.connect("2", "3") + pipe.connect("3", "4") + + pipe.remove_component("2") + + assert ["1", "3", "4"] == sorted(pipe.graph.nodes) + assert [("3", "4")] == sorted([(u, v) for (u, v) in pipe.graph.edges()]) + + def test_remove_component_allows_you_to_reuse_the_component(self): + pipe = Pipeline() + Some = component_class("Some", input_types={"in": int}, output_types={"out": int}) + + pipe.add_component("component_1", Some()) + pipe.add_component("component_2", Some()) + pipe.add_component("component_3", Some()) + pipe.connect("component_1", "component_2") + pipe.connect("component_2", "component_3") + component_2 = pipe.remove_component("component_2") + + assert component_2.__haystack_added_to_pipeline__ is None + assert component_2.__haystack_input__._sockets_dict == {"in": InputSocket(name="in", type=int, senders=[])} + assert component_2.__haystack_output__._sockets_dict == { + "out": OutputSocket(name="out", type=int, receivers=[]) + } + + pipe2 = Pipeline() + pipe2.add_component("component_4", Some()) + pipe2.add_component("component_2", component_2) + pipe2.add_component("component_5", Some()) + + pipe2.connect("component_4", "component_2") + pipe2.connect("component_2", "component_5") + assert component_2.__haystack_added_to_pipeline__ is pipe2 + assert component_2.__haystack_input__._sockets_dict == { + "in": InputSocket(name="in", type=int, senders=["component_4"]) + } + assert component_2.__haystack_output__._sockets_dict == { + "out": OutputSocket(name="out", type=int, receivers=["component_5"]) + } + + # instance = pipe2.get_component("some") + # assert instance == component + + # UNIT + def test_get_component_name(self): + pipe = Pipeline() + some_component = component_class("Some")() + pipe.add_component("some", some_component) + + assert pipe.get_component_name(some_component) == "some" + + # UNIT + def test_get_component_name_not_added_to_pipeline(self): + pipe = Pipeline() + some_component = component_class("Some")() + + assert pipe.get_component_name(some_component) == "" + + # UNIT + def test_repr(self): + pipe = Pipeline(metadata={"test": "test"}) + pipe.add_component("add_two", AddFixedValue(add=2)) + pipe.add_component("add_default", AddFixedValue()) + pipe.add_component("double", Double()) + pipe.connect("add_two", "double") + pipe.connect("double", "add_default") + + expected_repr = ( + f"{object.__repr__(pipe)}\n" + "🧱 Metadata\n" + " - test: test\n" + "🚅 Components\n" + " - add_two: AddFixedValue\n" + " - add_default: AddFixedValue\n" + " - double: Double\n" + "🛤️ Connections\n" + " - add_two.result -> double.value (int)\n" + " - double.value -> add_default.value (int)\n" + ) + + assert repr(pipe) == expected_repr + + # UNIT + def test_to_dict(self): + add_two = AddFixedValue(add=2) + add_default = AddFixedValue() + double = Double() + pipe = Pipeline(metadata={"test": "test"}, max_runs_per_component=42) + pipe.add_component("add_two", add_two) + pipe.add_component("add_default", add_default) + pipe.add_component("double", double) + pipe.connect("add_two", "double") + pipe.connect("double", "add_default") + + res = pipe.to_dict() + expected = { + "metadata": {"test": "test"}, + "max_runs_per_component": 42, + "components": { + "add_two": { + "type": "haystack.testing.sample_components.add_value.AddFixedValue", + "init_parameters": {"add": 2}, + }, + "add_default": { + "type": "haystack.testing.sample_components.add_value.AddFixedValue", + "init_parameters": {"add": 1}, + }, + "double": {"type": "haystack.testing.sample_components.double.Double", "init_parameters": {}}, + }, + "connections": [ + {"sender": "add_two.result", "receiver": "double.value"}, + {"sender": "double.value", "receiver": "add_default.value"}, + ], + } + assert res == expected + + def test_from_dict(self): + data = { + "metadata": {"test": "test"}, + "max_runs_per_component": 101, + "components": { + "add_two": { + "type": "haystack.testing.sample_components.add_value.AddFixedValue", + "init_parameters": {"add": 2}, + }, + "add_default": { + "type": "haystack.testing.sample_components.add_value.AddFixedValue", + "init_parameters": {"add": 1}, + }, + "double": {"type": "haystack.testing.sample_components.double.Double", "init_parameters": {}}, + }, + "connections": [ + {"sender": "add_two.result", "receiver": "double.value"}, + {"sender": "double.value", "receiver": "add_default.value"}, + ], + } + pipe = Pipeline.from_dict(data) + + assert pipe.metadata == {"test": "test"} + assert pipe._max_runs_per_component == 101 + + # Components + assert len(pipe.graph.nodes) == 3 + ## add_two + add_two = pipe.graph.nodes["add_two"] + assert add_two["instance"].add == 2 + assert add_two["input_sockets"] == { + "value": InputSocket(name="value", type=int), + "add": InputSocket(name="add", type=Optional[int], default_value=None), + } + assert add_two["output_sockets"] == {"result": OutputSocket(name="result", type=int, receivers=["double"])} + assert add_two["visits"] == 0 + + ## add_default + add_default = pipe.graph.nodes["add_default"] + assert add_default["instance"].add == 1 + assert add_default["input_sockets"] == { + "value": InputSocket(name="value", type=int, senders=["double"]), + "add": InputSocket(name="add", type=Optional[int], default_value=None), + } + assert add_default["output_sockets"] == {"result": OutputSocket(name="result", type=int)} + assert add_default["visits"] == 0 + + ## double + double = pipe.graph.nodes["double"] + assert double["instance"] + assert double["input_sockets"] == {"value": InputSocket(name="value", type=int, senders=["add_two"])} + assert double["output_sockets"] == {"value": OutputSocket(name="value", type=int, receivers=["add_default"])} + assert double["visits"] == 0 + + # Connections + connections = list(pipe.graph.edges(data=True)) + assert len(connections) == 2 + assert connections[0] == ( + "add_two", + "double", + { + "conn_type": "int", + "from_socket": OutputSocket(name="result", type=int, receivers=["double"]), + "to_socket": InputSocket(name="value", type=int, senders=["add_two"]), + "mandatory": True, + }, + ) + assert connections[1] == ( + "double", + "add_default", + { + "conn_type": "int", + "from_socket": OutputSocket(name="value", type=int, receivers=["add_default"]), + "to_socket": InputSocket(name="value", type=int, senders=["double"]), + "mandatory": True, + }, + ) + + # TODO: Remove this, this should be a component test. + # The pipeline can't handle this in any case nor way. + def test_from_dict_with_callbacks(self): + data = { + "metadata": {"test": "test"}, + "components": { + "add_two": { + "type": "haystack.testing.sample_components.add_value.AddFixedValue", + "init_parameters": {"add": 2}, + }, + "add_default": { + "type": "haystack.testing.sample_components.add_value.AddFixedValue", + "init_parameters": {"add": 1}, + }, + "double": {"type": "haystack.testing.sample_components.double.Double", "init_parameters": {}}, + "greet": { + "type": "haystack.testing.sample_components.greet.Greet", + "init_parameters": {"message": "test"}, + }, + }, + "connections": [ + {"sender": "add_two.result", "receiver": "double.value"}, + {"sender": "double.value", "receiver": "add_default.value"}, + ], + } + + components_seen_in_callback = [] + + def component_pre_init_callback(name, component_cls, init_params): + assert name in ["add_two", "add_default", "double", "greet"] + assert component_cls in [AddFixedValue, Double, Greet] + + if name == "add_two": + assert init_params == {"add": 2} + elif name == "add_default": + assert init_params == {"add": 1} + elif name == "greet": + assert init_params == {"message": "test"} + + components_seen_in_callback.append(name) + + pipe = Pipeline.from_dict( + data, callbacks=DeserializationCallbacks(component_pre_init=component_pre_init_callback) + ) + assert components_seen_in_callback == ["add_two", "add_default", "double", "greet"] + add_two = pipe.graph.nodes["add_two"]["instance"] + assert add_two.add == 2 + add_default = pipe.graph.nodes["add_default"]["instance"] + assert add_default.add == 1 + greet = pipe.graph.nodes["greet"]["instance"] + assert greet.message == "test" + assert greet.log_level == "INFO" + + def component_pre_init_callback_modify(name, component_cls, init_params): + assert name in ["add_two", "add_default", "double", "greet"] + assert component_cls in [AddFixedValue, Double, Greet] + + if name == "add_two": + init_params["add"] = 3 + elif name == "add_default": + init_params["add"] = 0 + elif name == "greet": + init_params["message"] = "modified test" + init_params["log_level"] = "DEBUG" + + pipe = Pipeline.from_dict( + data, callbacks=DeserializationCallbacks(component_pre_init=component_pre_init_callback_modify) + ) + add_two = pipe.graph.nodes["add_two"]["instance"] + assert add_two.add == 3 + add_default = pipe.graph.nodes["add_default"]["instance"] + assert add_default.add == 0 + greet = pipe.graph.nodes["greet"]["instance"] + assert greet.message == "modified test" + assert greet.log_level == "DEBUG" + + # Test with a component that internally instantiates another component + def component_pre_init_callback_check_class(name, component_cls, init_params): + assert name == "fake_component_squared" + assert component_cls == FakeComponentSquared + + pipe = Pipeline() + pipe.add_component("fake_component_squared", FakeComponentSquared()) + pipe = Pipeline.from_dict( + pipe.to_dict(), + callbacks=DeserializationCallbacks(component_pre_init=component_pre_init_callback_check_class), + ) + assert type(pipe.graph.nodes["fake_component_squared"]["instance"].inner) == FakeComponent + + # UNIT + def test_from_dict_with_empty_dict(self): + assert Pipeline() == Pipeline.from_dict({}) + + # TODO: UNIT, consider deprecating this argument + def test_from_dict_with_components_instances(self): + add_two = AddFixedValue(add=2) + add_default = AddFixedValue() + components = {"add_two": add_two, "add_default": add_default} + data = { + "metadata": {"test": "test"}, + "components": { + "add_two": {}, + "add_default": {}, + "double": {"type": "haystack.testing.sample_components.double.Double", "init_parameters": {}}, + }, + "connections": [ + {"sender": "add_two.result", "receiver": "double.value"}, + {"sender": "double.value", "receiver": "add_default.value"}, + ], + } + pipe = Pipeline.from_dict(data, components=components) + assert pipe.metadata == {"test": "test"} + + # Components + assert len(pipe.graph.nodes) == 3 + ## add_two + add_two_data = pipe.graph.nodes["add_two"] + assert add_two_data["instance"] is add_two + assert add_two_data["instance"].add == 2 + assert add_two_data["input_sockets"] == { + "value": InputSocket(name="value", type=int), + "add": InputSocket(name="add", type=Optional[int], default_value=None), + } + assert add_two_data["output_sockets"] == {"result": OutputSocket(name="result", type=int, receivers=["double"])} + assert add_two_data["visits"] == 0 + + ## add_default + add_default_data = pipe.graph.nodes["add_default"] + assert add_default_data["instance"] is add_default + assert add_default_data["instance"].add == 1 + assert add_default_data["input_sockets"] == { + "value": InputSocket(name="value", type=int, senders=["double"]), + "add": InputSocket(name="add", type=Optional[int], default_value=None), + } + assert add_default_data["output_sockets"] == {"result": OutputSocket(name="result", type=int, receivers=[])} + assert add_default_data["visits"] == 0 + + ## double + double = pipe.graph.nodes["double"] + assert double["instance"] + assert double["input_sockets"] == {"value": InputSocket(name="value", type=int, senders=["add_two"])} + assert double["output_sockets"] == {"value": OutputSocket(name="value", type=int, receivers=["add_default"])} + assert double["visits"] == 0 + + # Connections + connections = list(pipe.graph.edges(data=True)) + assert len(connections) == 2 + assert connections[0] == ( + "add_two", + "double", + { + "conn_type": "int", + "from_socket": OutputSocket(name="result", type=int, receivers=["double"]), + "to_socket": InputSocket(name="value", type=int, senders=["add_two"]), + "mandatory": True, + }, + ) + assert connections[1] == ( + "double", + "add_default", + { + "conn_type": "int", + "from_socket": OutputSocket(name="value", type=int, receivers=["add_default"]), + "to_socket": InputSocket(name="value", type=int, senders=["double"]), + "mandatory": True, + }, + ) + + # UNIT + def test_from_dict_without_component_type(self): + data = { + "metadata": {"test": "test"}, + "components": {"add_two": {"init_parameters": {"add": 2}}}, + "connections": [], + } + with pytest.raises(PipelineError) as err: + Pipeline.from_dict(data) + + err.match("Missing 'type' in component 'add_two'") + + # UNIT + def test_from_dict_without_registered_component_type(self, request): + data = { + "metadata": {"test": "test"}, + "components": {"add_two": {"type": "foo.bar.baz", "init_parameters": {"add": 2}}}, + "connections": [], + } + with pytest.raises(PipelineError) as err: + Pipeline.from_dict(data) + + err.match(r"Component .+ not imported.") + + # UNIT + def test_from_dict_without_connection_sender(self): + data = {"metadata": {"test": "test"}, "components": {}, "connections": [{"receiver": "some.receiver"}]} + with pytest.raises(PipelineError) as err: + Pipeline.from_dict(data) + + err.match("Missing sender in connection: {'receiver': 'some.receiver'}") + + # UNIT + def test_from_dict_without_connection_receiver(self): + data = {"metadata": {"test": "test"}, "components": {}, "connections": [{"sender": "some.sender"}]} + with pytest.raises(PipelineError) as err: + Pipeline.from_dict(data) + + err.match("Missing receiver in connection: {'sender': 'some.sender'}") + + def test_describe_input_only_no_inputs_components(self): + A = component_class("A", input_types={}, output={"x": 0}) + B = component_class("B", input_types={}, output={"y": 0}) + C = component_class("C", input_types={"x": int, "y": int}, output={"z": 0}) + p = Pipeline() + p.add_component("a", A()) + p.add_component("b", B()) + p.add_component("c", C()) + p.connect("a.x", "c.x") + p.connect("b.y", "c.y") + assert p.inputs() == {} + assert p.inputs(include_components_with_connected_inputs=True) == { + "c": {"x": {"type": int, "is_mandatory": True}, "y": {"type": int, "is_mandatory": True}} + } + + def test_describe_input_some_components_with_no_inputs(self): + A = component_class("A", input_types={}, output={"x": 0}) + B = component_class("B", input_types={"y": int}, output={"y": 0}) + C = component_class("C", input_types={"x": int, "y": int}, output={"z": 0}) + p = Pipeline() + p.add_component("a", A()) + p.add_component("b", B()) + p.add_component("c", C()) + p.connect("a.x", "c.x") + p.connect("b.y", "c.y") + assert p.inputs() == {"b": {"y": {"type": int, "is_mandatory": True}}} + assert p.inputs(include_components_with_connected_inputs=True) == { + "b": {"y": {"type": int, "is_mandatory": True}}, + "c": {"x": {"type": int, "is_mandatory": True}, "y": {"type": int, "is_mandatory": True}}, + } + + def test_describe_input_all_components_have_inputs(self): + A = component_class("A", input_types={"x": Optional[int]}, output={"x": 0}) + B = component_class("B", input_types={"y": int}, output={"y": 0}) + C = component_class("C", input_types={"x": int, "y": int}, output={"z": 0}) + p = Pipeline() + p.add_component("a", A()) + p.add_component("b", B()) + p.add_component("c", C()) + p.connect("a.x", "c.x") + p.connect("b.y", "c.y") + assert p.inputs() == { + "a": {"x": {"type": Optional[int], "is_mandatory": True}}, + "b": {"y": {"type": int, "is_mandatory": True}}, + } + assert p.inputs(include_components_with_connected_inputs=True) == { + "a": {"x": {"type": Optional[int], "is_mandatory": True}}, + "b": {"y": {"type": int, "is_mandatory": True}}, + "c": {"x": {"type": int, "is_mandatory": True}, "y": {"type": int, "is_mandatory": True}}, + } + + def test_describe_output_multiple_possible(self): + """ + This pipeline has two outputs: + {"b": {"output_b": {"type": str}}, "a": {"output_a": {"type": str}}} + """ + A = component_class("A", input_types={"input_a": str}, output={"output_a": "str", "output_b": "str"}) + B = component_class("B", input_types={"input_b": str}, output={"output_b": "str"}) + + pipe = Pipeline() + pipe.add_component("a", A()) + pipe.add_component("b", B()) + pipe.connect("a.output_b", "b.input_b") + + assert pipe.outputs() == {"b": {"output_b": {"type": str}}, "a": {"output_a": {"type": str}}} + assert pipe.outputs(include_components_with_connected_outputs=True) == { + "a": {"output_a": {"type": str}, "output_b": {"type": str}}, + "b": {"output_b": {"type": str}}, + } + + def test_describe_output_single(self): + """ + This pipeline has one output: + {"c": {"z": {"type": int}}} + """ + A = component_class("A", input_types={"x": Optional[int]}, output={"x": 0}) + B = component_class("B", input_types={"y": int}, output={"y": 0}) + C = component_class("C", input_types={"x": int, "y": int}, output={"z": 0}) + p = Pipeline() + p.add_component("a", A()) + p.add_component("b", B()) + p.add_component("c", C()) + p.connect("a.x", "c.x") + p.connect("b.y", "c.y") + + assert p.outputs() == {"c": {"z": {"type": int}}} + assert p.outputs(include_components_with_connected_outputs=True) == { + "a": {"x": {"type": int}}, + "b": {"y": {"type": int}}, + "c": {"z": {"type": int}}, + } + + def test_describe_no_outputs(self): + """ + This pipeline sets up elaborate connections between three components but in fact it has no outputs: + Check that p.outputs() == {} + """ + A = component_class("A", input_types={"x": Optional[int]}, output={"x": 0}) + B = component_class("B", input_types={"y": int}, output={"y": 0}) + C = component_class("C", input_types={"x": int, "y": int}, output={}) + p = Pipeline() + p.add_component("a", A()) + p.add_component("b", B()) + p.add_component("c", C()) + p.connect("a.x", "c.x") + p.connect("b.y", "c.y") + assert p.outputs() == {} + assert p.outputs(include_components_with_connected_outputs=True) == { + "a": {"x": {"type": int}}, + "b": {"y": {"type": int}}, + } + + def test_from_template(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "fake_key") + pipe = Pipeline.from_template(PredefinedPipeline.INDEXING) + assert pipe.get_component("cleaner") + + def test_walk_pipeline_with_no_cycles(self): + """ + This pipeline has two source nodes, source1 and source2, one hello3 node in between, and one sink node, joiner. + pipeline.walk() should return each component exactly once. The order is not guaranteed. + """ + + @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}!"} + + @component + class Joiner: + @component.output_types(output=str) + def run(self, word1: str, word2: str): + """ + Takes two strings in input and returns "Hello, and !" in output. + """ + return {"output": f"Hello, {word1} and {word2}!"} + + pipeline = Pipeline() + source1 = Hello() + source2 = Hello() + hello3 = Hello() + joiner = Joiner() + pipeline.add_component("source1", source1) + pipeline.add_component("source2", source2) + pipeline.add_component("hello3", hello3) + pipeline.add_component("joiner", joiner) + + pipeline.connect("source1", "joiner.word1") + pipeline.connect("source2", "hello3") + pipeline.connect("hello3", "joiner.word2") + + expected_components = [("source1", source1), ("source2", source2), ("joiner", joiner), ("hello3", hello3)] + assert sorted(expected_components) == sorted(pipeline.walk()) + + def test_walk_pipeline_with_cycles(self): + """ + This pipeline consists of two components, which would run three times in a loop. + pipeline.walk() should return these components exactly once. The order is not guaranteed. + """ + + @component + class Hello: + def __init__(self): + self.iteration_counter = 0 + + @component.output_types(intermediate=str, final=str) + def run(self, word: str, intermediate: Optional[str] = None): + """ + Takes a string in input and returns "Hello, !" in output. + """ + if self.iteration_counter < 3: + self.iteration_counter += 1 + return {"intermediate": f"Hello, {intermediate or word}!"} + return {"final": f"Hello, {intermediate or word}!"} + + pipeline = Pipeline() + hello = Hello() + hello_again = Hello() + pipeline.add_component("hello", hello) + pipeline.add_component("hello_again", hello_again) + pipeline.connect("hello.intermediate", "hello_again.intermediate") + pipeline.connect("hello_again.intermediate", "hello.intermediate") + assert {("hello", hello), ("hello_again", hello_again)} == set(pipeline.walk()) + + def test__init_graph(self): + pipe = Pipeline() + pipe.add_component("greet", Greet()) + pipe.add_component("adder", AddFixedValue()) + pipe.connect("greet", "adder") + pipe._init_graph() + for node in pipe.graph.nodes: + assert pipe.graph.nodes[node]["visits"] == 0 + + def test__init_run_queue(self): + ComponentWithVariadic = component_class( + "ComponentWithVariadic", input_types={"in": Variadic[int]}, output_types={"out": int} + ) + ComponentWithNoInputs = component_class("ComponentWithNoInputs", input_types={}, output_types={"out": int}) + ComponentWithSingleInput = component_class( + "ComponentWithSingleInput", input_types={"in": int}, output_types={"out": int} + ) + ComponentWithMultipleInputs = component_class( + "ComponentWithMultipleInputs", input_types={"in1": int, "in2": int}, output_types={"out": int} + ) + + pipe = Pipeline() + pipe.add_component("with_variadic", ComponentWithVariadic()) + pipe.add_component("with_no_inputs", ComponentWithNoInputs()) + pipe.add_component("with_single_input", ComponentWithSingleInput()) + pipe.add_component("another_with_single_input", ComponentWithSingleInput()) + pipe.add_component("yet_another_with_single_input", ComponentWithSingleInput()) + pipe.add_component("with_multiple_inputs", ComponentWithMultipleInputs()) + + pipe.connect("yet_another_with_single_input.out", "with_variadic.in") + pipe.connect("with_no_inputs.out", "with_variadic.in") + pipe.connect("with_single_input.out", "another_with_single_input.in") + pipe.connect("another_with_single_input.out", "with_multiple_inputs.in1") + pipe.connect("with_multiple_inputs.out", "with_variadic.in") + + data = {"yet_another_with_single_input": {"in": 1}} + run_queue = pipe._init_run_queue(data) + assert len(run_queue) == 6 + assert run_queue[0][0] == "with_no_inputs" + assert run_queue[1][0] == "with_single_input" + assert run_queue[2][0] == "yet_another_with_single_input" + assert run_queue[3][0] == "another_with_single_input" + assert run_queue[4][0] == "with_multiple_inputs" + assert run_queue[5][0] == "with_variadic" + + def test__init_inputs_state(self): + pipe = Pipeline() + template = """ + Answer the following questions: + {{ questions | join("\n") }} + """ + pipe.add_component("prompt_builder", PromptBuilder(template=template)) + pipe.add_component("branch_joiner", BranchJoiner(type_=int)) + questions = ["What is the capital of Italy?", "What is the capital of France?"] + data = { + "prompt_builder": {"questions": questions}, + "branch_joiner": {"value": 1}, + "not_a_component": "some input data", + } + res = pipe._init_inputs_state(data) + assert res == { + "prompt_builder": {"questions": ["What is the capital of Italy?", "What is the capital of France?"]}, + "branch_joiner": {"value": [1]}, + "not_a_component": "some input data", + } + assert id(questions) != id(res["prompt_builder"]["questions"]) + + def test__prepare_component_input_data(self): + MockComponent = component_class("MockComponent", input_types={"x": List[str], "y": str}) + pipe = Pipeline() + pipe.add_component("first_mock", MockComponent()) + pipe.add_component("second_mock", MockComponent()) + + res = pipe._prepare_component_input_data({"x": ["some data"], "y": "some other data"}) + assert res == { + "first_mock": {"x": ["some data"], "y": "some other data"}, + "second_mock": {"x": ["some data"], "y": "some other data"}, + } + assert id(res["first_mock"]["x"]) != id(res["second_mock"]["x"]) + + def test__prepare_component_input_data_with_connected_inputs(self): + MockComponent = component_class( + "MockComponent", input_types={"x": List[str], "y": str}, output_types={"z": str} + ) + pipe = Pipeline() + pipe.add_component("first_mock", MockComponent()) + pipe.add_component("second_mock", MockComponent()) + pipe.connect("first_mock.z", "second_mock.y") + + res = pipe._prepare_component_input_data({"x": ["some data"], "y": "some other data"}) + assert res == {"first_mock": {"x": ["some data"], "y": "some other data"}, "second_mock": {"x": ["some data"]}} + assert id(res["first_mock"]["x"]) != id(res["second_mock"]["x"]) + + def test__prepare_component_input_data_with_non_existing_input(self, caplog): + pipe = Pipeline() + res = pipe._prepare_component_input_data({"input_name": 1}) + assert res == {} + assert ( + "Inputs ['input_name'] were not matched to any component inputs, " + "please check your run parameters." in caplog.text + ) + + def test_connect(self): + comp1 = component_class("Comp1", output_types={"value": int})() + comp2 = component_class("Comp2", input_types={"value": int})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + assert pipe.connect("comp1.value", "comp2.value") is pipe + + assert comp1.__haystack_output__.value.receivers == ["comp2"] + assert comp2.__haystack_input__.value.senders == ["comp1"] + assert list(pipe.graph.edges) == [("comp1", "comp2", "value/value")] + + def test_connect_already_connected(self): + comp1 = component_class("Comp1", output_types={"value": int})() + comp2 = component_class("Comp2", input_types={"value": int})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + pipe.connect("comp1.value", "comp2.value") + pipe.connect("comp1.value", "comp2.value") + + assert comp1.__haystack_output__.value.receivers == ["comp2"] + assert comp2.__haystack_input__.value.senders == ["comp1"] + assert list(pipe.graph.edges) == [("comp1", "comp2", "value/value")] + + def test_connect_with_sender_component_name(self): + comp1 = component_class("Comp1", output_types={"value": int})() + comp2 = component_class("Comp2", input_types={"value": int})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + pipe.connect("comp1", "comp2.value") + + assert comp1.__haystack_output__.value.receivers == ["comp2"] + assert comp2.__haystack_input__.value.senders == ["comp1"] + assert list(pipe.graph.edges) == [("comp1", "comp2", "value/value")] + + def test_connect_with_receiver_component_name(self): + comp1 = component_class("Comp1", output_types={"value": int})() + comp2 = component_class("Comp2", input_types={"value": int})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + pipe.connect("comp1.value", "comp2") + + assert comp1.__haystack_output__.value.receivers == ["comp2"] + assert comp2.__haystack_input__.value.senders == ["comp1"] + assert list(pipe.graph.edges) == [("comp1", "comp2", "value/value")] + + def test_connect_with_sender_and_receiver_component_name(self): + comp1 = component_class("Comp1", output_types={"value": int})() + comp2 = component_class("Comp2", input_types={"value": int})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + pipe.connect("comp1", "comp2") + + assert comp1.__haystack_output__.value.receivers == ["comp2"] + assert comp2.__haystack_input__.value.senders == ["comp1"] + assert list(pipe.graph.edges) == [("comp1", "comp2", "value/value")] + + def test_connect_with_sender_not_in_pipeline(self): + comp2 = component_class("Comp2", input_types={"value": int})() + pipe = Pipeline() + pipe.add_component("comp2", comp2) + with pytest.raises(ValueError): + pipe.connect("comp1.value", "comp2.value") + + def test_connect_with_receiver_not_in_pipeline(self): + comp1 = component_class("Comp1", output_types={"value": int})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + with pytest.raises(ValueError): + pipe.connect("comp1.value", "comp2.value") + + def test_connect_with_sender_socket_name_not_in_pipeline(self): + comp1 = component_class("Comp1", output_types={"value": int})() + comp2 = component_class("Comp2", input_types={"value": int})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + with pytest.raises(PipelineConnectError): + pipe.connect("comp1.non_existing", "comp2.value") + + def test_connect_with_receiver_socket_name_not_in_pipeline(self): + comp1 = component_class("Comp1", output_types={"value": int})() + comp2 = component_class("Comp2", input_types={"value": int})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + with pytest.raises(PipelineConnectError): + pipe.connect("comp1.value", "comp2.non_existing") + + def test_connect_with_no_matching_types_and_same_names(self): + comp1 = component_class("Comp1", output_types={"value": int})() + comp2 = component_class("Comp2", input_types={"value": str})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + with pytest.raises(PipelineConnectError): + pipe.connect("comp1", "comp2") + + def test_connect_with_multiple_sender_connections_with_same_type_and_differing_name(self): + comp1 = component_class("Comp1", output_types={"val1": int, "val2": int})() + comp2 = component_class("Comp2", input_types={"value": int})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + with pytest.raises(PipelineConnectError): + pipe.connect("comp1", "comp2") + + def test_connect_with_multiple_receiver_connections_with_same_type_and_differing_name(self): + comp1 = component_class("Comp1", output_types={"value": int})() + comp2 = component_class("Comp2", input_types={"val1": int, "val2": int})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + with pytest.raises(PipelineConnectError): + pipe.connect("comp1", "comp2") + + def test_connect_with_multiple_sender_connections_with_same_type_and_same_name(self): + comp1 = component_class("Comp1", output_types={"value": int, "other": int})() + comp2 = component_class("Comp2", input_types={"value": int})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + pipe.connect("comp1", "comp2") + + assert comp1.__haystack_output__.value.receivers == ["comp2"] + assert comp2.__haystack_input__.value.senders == ["comp1"] + assert list(pipe.graph.edges) == [("comp1", "comp2", "value/value")] + + def test_connect_with_multiple_receiver_connections_with_same_type_and_same_name(self): + comp1 = component_class("Comp1", output_types={"value": int})() + comp2 = component_class("Comp2", input_types={"value": int, "other": int})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + pipe.connect("comp1", "comp2") + + assert comp1.__haystack_output__.value.receivers == ["comp2"] + assert comp2.__haystack_input__.value.senders == ["comp1"] + assert list(pipe.graph.edges) == [("comp1", "comp2", "value/value")] + + def test_connect_multiple_outputs_to_non_variadic_input(self): + comp1 = component_class("Comp1", output_types={"value": int})() + comp2 = component_class("Comp2", output_types={"value": int})() + comp3 = component_class("Comp3", input_types={"value": int})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + pipe.add_component("comp3", comp3) + pipe.connect("comp1.value", "comp3.value") + with pytest.raises(PipelineConnectError): + pipe.connect("comp2.value", "comp3.value") + + def test_connect_multiple_outputs_to_variadic_input(self): + comp1 = component_class("Comp1", output_types={"value": int})() + comp2 = component_class("Comp2", output_types={"value": int})() + comp3 = component_class("Comp3", input_types={"value": Variadic[int]})() + pipe = Pipeline() + pipe.add_component("comp1", comp1) + pipe.add_component("comp2", comp2) + pipe.add_component("comp3", comp3) + pipe.connect("comp1.value", "comp3.value") + pipe.connect("comp2.value", "comp3.value") + + assert comp1.__haystack_output__.value.receivers == ["comp3"] + assert comp2.__haystack_output__.value.receivers == ["comp3"] + assert comp3.__haystack_input__.value.senders == ["comp1", "comp2"] + assert list(pipe.graph.edges) == [("comp1", "comp3", "value/value"), ("comp2", "comp3", "value/value")] + + def test_connect_same_component_as_sender_and_receiver(self): + """ + This pipeline consists of one component, which would be connected to itself. + Connecting a component to itself is raises PipelineConnectError. + """ + pipe = Pipeline() + single_component = FakeComponent() + pipe.add_component("single_component", single_component) + with pytest.raises(PipelineConnectError): + pipe.connect("single_component.out", "single_component.in") + + def test__run_component(self, spying_tracer, caplog): + caplog.set_level(logging.INFO) + sentence_builder = component_class( + "SentenceBuilder", input_types={"words": List[str]}, output={"text": "some words"} + )() + document_builder = component_class( + "DocumentBuilder", input_types={"text": str}, output={"doc": Document(content="some words")} + )() + document_cleaner = component_class( + "DocumentCleaner", + input_types={"doc": Document}, + output={"cleaned_doc": Document(content="some cleaner words")}, + )() + + pipe = Pipeline() + pipe.add_component("sentence_builder", sentence_builder) + pipe.add_component("document_builder", document_builder) + pipe.add_component("document_cleaner", document_cleaner) + pipe.connect("sentence_builder.text", "document_builder.text") + pipe.connect("document_builder.doc", "document_cleaner.doc") + assert spying_tracer.spans == [] + res = pipe._run_component("document_builder", {"text": "whatever"}) + assert res == {"doc": Document(content="some words")} + + assert len(spying_tracer.spans) == 1 + span = spying_tracer.spans[0] + assert span.operation_name == "haystack.component.run" + assert span.tags == { + "haystack.component.name": "document_builder", + "haystack.component.type": "DocumentBuilder", + "haystack.component.input_types": {"text": "str"}, + "haystack.component.input_spec": {"text": {"type": "str", "senders": ["sentence_builder"]}}, + "haystack.component.output_spec": {"doc": {"type": "Document", "receivers": ["document_cleaner"]}}, + "haystack.component.visits": 1, + } + + assert caplog.messages == ["Running component document_builder"] + + def test__run_component_with_variadic_input(self): + document_joiner = component_class("DocumentJoiner", input_types={"docs": Variadic[Document]})() + + pipe = Pipeline() + pipe.add_component("document_joiner", document_joiner) + inputs = {"docs": [Document(content="doc1"), Document(content="doc2")]} + pipe._run_component("document_joiner", inputs) + assert inputs == {"docs": []} + + def test__component_has_enough_inputs_to_run(self): + sentence_builder = component_class("SentenceBuilder", input_types={"words": List[str]})() + pipe = Pipeline() + pipe.add_component("sentence_builder", sentence_builder) + + assert not pipe._component_has_enough_inputs_to_run("sentence_builder", {}) + assert not pipe._component_has_enough_inputs_to_run( + "sentence_builder", {"sentence_builder": {"wrong_input_name": "blah blah"}} + ) + assert pipe._component_has_enough_inputs_to_run( + "sentence_builder", {"sentence_builder": {"words": ["blah blah"]}} + ) + + def test__find_components_that_will_receive_no_input(self): + sentence_builder = component_class( + "SentenceBuilder", input_types={"words": List[str]}, output_types={"text": str} + )() + document_builder = component_class( + "DocumentBuilder", input_types={"text": str}, output_types={"doc": Document} + )() + conditional_document_builder = component_class( + "ConditionalDocumentBuilder", output_types={"doc": Document, "noop": None} + )() + + document_joiner = component_class("DocumentJoiner", input_types={"docs": Variadic[Document]})() + + pipe = Pipeline() + pipe.add_component("sentence_builder", sentence_builder) + pipe.add_component("document_builder", document_builder) + pipe.add_component("document_joiner", document_joiner) + pipe.add_component("conditional_document_builder", conditional_document_builder) + pipe.connect("sentence_builder.text", "document_builder.text") + pipe.connect("document_builder.doc", "document_joiner.docs") + pipe.connect("conditional_document_builder.doc", "document_joiner.docs") + + res = pipe._find_components_that_will_receive_no_input("sentence_builder", {}, {}) + assert res == {("document_builder", document_builder), ("document_joiner", document_joiner)} + + res = pipe._find_components_that_will_receive_no_input("sentence_builder", {"text": "some text"}, {}) + assert res == set() + + res = pipe._find_components_that_will_receive_no_input("conditional_document_builder", {"noop": None}, {}) + assert res == {("document_joiner", document_joiner)} + + res = pipe._find_components_that_will_receive_no_input( + "conditional_document_builder", {"noop": None}, {"document_joiner": {"docs": []}} + ) + assert res == {("document_joiner", document_joiner)} + + res = pipe._find_components_that_will_receive_no_input( + "conditional_document_builder", {"noop": None}, {"document_joiner": {"docs": [Document("some text")]}} + ) + assert res == set() + + def test__distribute_output(self): + document_builder = component_class( + "DocumentBuilder", input_types={"text": str}, output_types={"doc": Document, "another_doc": Document} + )() + document_cleaner = component_class( + "DocumentCleaner", input_types={"doc": Document}, output_types={"cleaned_doc": Document} + )() + document_joiner = component_class("DocumentJoiner", input_types={"docs": Variadic[Document]})() + + pipe = Pipeline() + pipe.add_component("document_builder", document_builder) + pipe.add_component("document_cleaner", document_cleaner) + pipe.add_component("document_joiner", document_joiner) + pipe.connect("document_builder.doc", "document_cleaner.doc") + pipe.connect("document_builder.another_doc", "document_joiner.docs") + + inputs = {"document_builder": {"text": "some text"}} + run_queue = [] + waiting_queue = [("document_joiner", document_joiner)] + res = pipe._distribute_output( + "document_builder", + {"doc": Document("some text"), "another_doc": Document()}, + inputs, + run_queue, + waiting_queue, + ) + + assert res == {} + assert inputs == { + "document_builder": {"text": "some text"}, + "document_cleaner": {"doc": Document("some text")}, + "document_joiner": {"docs": [Document()]}, + } + assert run_queue == [("document_cleaner", document_cleaner)] + assert waiting_queue == [("document_joiner", document_joiner)] + + def test__find_next_runnable_component(self): + document_builder = component_class( + "DocumentBuilder", input_types={"text": str}, output_types={"doc": Document} + )() + pipe = Pipeline() + components_inputs = {"document_builder": {"text": "some text"}} + waiting_queue = [("document_builder", document_builder)] + pair = pipe._find_next_runnable_component(components_inputs, waiting_queue) + assert pair == ("document_builder", document_builder) + + def test__find_next_runnable_component_without_component_inputs(self): + document_builder = component_class( + "DocumentBuilder", input_types={"text": str}, output_types={"doc": Document} + )() + pipe = Pipeline() + components_inputs = {} + waiting_queue = [("document_builder", document_builder)] + pair = pipe._find_next_runnable_component(components_inputs, waiting_queue) + assert pair == ("document_builder", document_builder) + + def test__find_next_runnable_component_with_component_with_only_variadic_non_greedy_input(self): + document_joiner = component_class("DocumentJoiner", input_types={"docs": Variadic[Document]})() + + pipe = Pipeline() + components_inputs = {} + waiting_queue = [("document_joiner", document_joiner)] + pair = pipe._find_next_runnable_component(components_inputs, waiting_queue) + assert pair == ("document_joiner", document_joiner) + + def test__find_next_runnable_component_with_component_with_only_default_input(self): + prompt_builder = PromptBuilder(template="{{ questions | join('\n') }}") + + pipe = Pipeline() + components_inputs = {} + waiting_queue = [("prompt_builder", prompt_builder)] + pair = pipe._find_next_runnable_component(components_inputs, waiting_queue) + + assert pair == ("prompt_builder", prompt_builder) + + def test__find_next_runnable_component_with_component_with_variadic_non_greedy_and_default_input(self): + document_joiner = component_class("DocumentJoiner", input_types={"docs": Variadic[Document]})() + prompt_builder = PromptBuilder(template="{{ questions | join('\n') }}") + + pipe = Pipeline() + components_inputs = {} + waiting_queue = [("prompt_builder", prompt_builder), ("document_joiner", document_joiner)] + pair = pipe._find_next_runnable_component(components_inputs, waiting_queue) + + assert pair == ("document_joiner", document_joiner) + + def test__find_next_runnable_component_with_different_components_inputs(self): + document_builder = component_class( + "DocumentBuilder", input_types={"text": str}, output_types={"doc": Document} + )() + document_joiner = component_class("DocumentJoiner", input_types={"docs": Variadic[Document]})() + prompt_builder = PromptBuilder(template="{{ questions | join('\n') }}") + + pipe = Pipeline() + components_inputs = {"document_builder": {"text": "some text"}} + waiting_queue = [ + ("prompt_builder", prompt_builder), + ("document_builder", document_builder), + ("document_joiner", document_joiner), + ] + pair = pipe._find_next_runnable_component(components_inputs, waiting_queue) + + assert pair == ("document_builder", document_builder) + + def test__find_next_runnable_component_with_different_components_without_any_input(self): + document_builder = component_class( + "DocumentBuilder", input_types={"text": str}, output_types={"doc": Document} + )() + document_joiner = component_class("DocumentJoiner", input_types={"docs": Variadic[Document]})() + prompt_builder = PromptBuilder(template="{{ questions | join('\n') }}") + + pipe = Pipeline() + components_inputs = {} + waiting_queue = [ + ("prompt_builder", prompt_builder), + ("document_builder", document_builder), + ("document_joiner", document_joiner), + ] + pair = pipe._find_next_runnable_component(components_inputs, waiting_queue) + + assert pair == ("document_builder", document_builder) + + def test__is_stuck_in_a_loop(self): + document_builder = component_class( + "DocumentBuilder", input_types={"text": str}, output_types={"doc": Document} + )() + document_joiner = component_class("DocumentJoiner", input_types={"docs": Variadic[Document]})() + prompt_builder = PromptBuilder(template="{{ questions | join('\n') }}") + + pipe = Pipeline() + + waiting_queue = [("document_builder", document_builder)] + assert pipe._is_stuck_in_a_loop(waiting_queue) + + waiting_queue = [("document_joiner", document_joiner)] + assert pipe._is_stuck_in_a_loop(waiting_queue) + + waiting_queue = [("prompt_builder", prompt_builder)] + assert pipe._is_stuck_in_a_loop(waiting_queue) + + waiting_queue = [("document_joiner", document_joiner), ("prompt_builder", prompt_builder)] + assert not pipe._is_stuck_in_a_loop(waiting_queue) + + waiting_queue = [("document_builder", document_joiner), ("prompt_builder", prompt_builder)] + assert not pipe._is_stuck_in_a_loop(waiting_queue) + + waiting_queue = [("document_builder", document_joiner), ("document_joiner", document_joiner)] + assert not pipe._is_stuck_in_a_loop(waiting_queue) + + def test__enqueue_component(self): + document_builder = component_class( + "DocumentBuilder", input_types={"text": str}, output_types={"doc": Document} + )() + document_joiner = component_class("DocumentJoiner", input_types={"docs": Variadic[Document]})() + + run_queue = [] + waiting_queue = [] + _enqueue_component(("document_builder", document_builder), run_queue, waiting_queue) + assert run_queue == [("document_builder", document_builder)] + assert waiting_queue == [] + + run_queue = [("document_builder", document_builder)] + waiting_queue = [] + _enqueue_component(("document_builder", document_builder), run_queue, waiting_queue) + assert run_queue == [("document_builder", document_builder)] + assert waiting_queue == [] + + run_queue = [] + waiting_queue = [("document_builder", document_builder)] + _enqueue_component(("document_builder", document_builder), run_queue, waiting_queue) + assert run_queue == [("document_builder", document_builder)] + assert waiting_queue == [] + + run_queue = [] + waiting_queue = [("document_joiner", document_joiner)] + _enqueue_component(("document_builder", document_builder), run_queue, waiting_queue) + assert run_queue == [("document_builder", document_builder)] + assert waiting_queue == [("document_joiner", document_joiner)] + + run_queue = [("document_joiner", document_joiner)] + waiting_queue = [] + _enqueue_component(("document_builder", document_builder), run_queue, waiting_queue) + assert run_queue == [("document_joiner", document_joiner), ("document_builder", document_builder)] + assert waiting_queue == [] + + def test__dequeue_component(self): + document_builder = component_class( + "DocumentBuilder", input_types={"text": str}, output_types={"doc": Document} + )() + document_joiner = component_class("DocumentJoiner", input_types={"docs": Variadic[Document]})() + + run_queue = [] + waiting_queue = [] + _dequeue_component(("document_builder", document_builder), run_queue, waiting_queue) + assert run_queue == [] + assert waiting_queue == [] + + run_queue = [("document_builder", document_builder)] + waiting_queue = [] + _dequeue_component(("document_builder", document_builder), run_queue, waiting_queue) + assert run_queue == [] + assert waiting_queue == [] + + run_queue = [] + waiting_queue = [("document_builder", document_builder)] + _dequeue_component(("document_builder", document_builder), run_queue, waiting_queue) + assert run_queue == [] + assert waiting_queue == [] + + run_queue = [("document_builder", document_builder)] + waiting_queue = [("document_builder", document_builder)] + _dequeue_component(("document_builder", document_builder), run_queue, waiting_queue) + assert run_queue == [] + assert waiting_queue == [] + + run_queue = [("document_builder", document_builder)] + waiting_queue = [("document_builder", document_builder)] + _dequeue_component(("document_joiner", document_joiner), run_queue, waiting_queue) + assert run_queue == [("document_builder", document_builder)] + assert waiting_queue == [("document_builder", document_builder)] + + def test__add_missing_input_defaults(self): + name = "prompt_builder" + prompt_builder = PromptBuilder(template="{{ questions | join('\n') }}") + components_inputs = {} + _add_missing_input_defaults(name, prompt_builder, components_inputs) + assert components_inputs == {"prompt_builder": {"questions": "", "template": None, "template_variables": None}} + + name = "answer_builder" + answer_builder = AnswerBuilder() + components_inputs = {"answer_builder": {"query": "What is the answer?"}} + _add_missing_input_defaults(name, answer_builder, components_inputs) + assert components_inputs == { + "answer_builder": { + "query": "What is the answer?", + "meta": None, + "documents": None, + "pattern": None, + "reference_pattern": None, + } + } + + name = "branch_joiner" + branch_joiner = BranchJoiner(int) + components_inputs = {} + _add_missing_input_defaults(name, branch_joiner, components_inputs) + assert components_inputs == {"branch_joiner": {}} + + def test__find_next_runnable_lazy_variadic_or_default_component(self): + document_builder = component_class( + "DocumentBuilder", input_types={"text": str}, output_types={"doc": Document} + )() + document_joiner = component_class("DocumentJoiner", input_types={"docs": Variadic[Document]})() + prompt_builder = PromptBuilder(template="{{ questions | join('\n') }}") + pipe = Pipeline() + + waiting_queue = [("document_builder", document_builder)] + pair = pipe._find_next_runnable_lazy_variadic_or_default_component(waiting_queue) + assert pair == ("document_builder", document_builder) + + waiting_queue = [("document_joiner", document_joiner)] + pair = pipe._find_next_runnable_lazy_variadic_or_default_component(waiting_queue) + assert pair == ("document_joiner", document_joiner) + + waiting_queue = [("prompt_builder", prompt_builder)] + pair = pipe._find_next_runnable_lazy_variadic_or_default_component(waiting_queue) + assert pair == ("prompt_builder", prompt_builder) + + waiting_queue = [ + ("document_builder", document_builder), + ("document_joiner", document_joiner), + ("prompt_builder", prompt_builder), + ] + pair = pipe._find_next_runnable_lazy_variadic_or_default_component(waiting_queue) + assert pair == ("document_joiner", document_joiner) + + waiting_queue = [ + ("prompt_builder", prompt_builder), + ("document_builder", document_builder), + ("document_joiner", document_joiner), + ] + pair = pipe._find_next_runnable_lazy_variadic_or_default_component(waiting_queue) + assert pair == ("prompt_builder", prompt_builder) + + waiting_queue = [ + ("document_builder", document_builder), + ("document_joiner", document_joiner), + ("prompt_builder", prompt_builder), + ] + pair = pipe._find_next_runnable_lazy_variadic_or_default_component(waiting_queue) + assert pair == ("document_joiner", document_joiner) + + waiting_queue = [ + ("document_builder", document_builder), + ("prompt_builder", prompt_builder), + ("document_joiner", document_joiner), + ] + pair = pipe._find_next_runnable_lazy_variadic_or_default_component(waiting_queue) + assert pair == ("prompt_builder", prompt_builder) + + def test__enqueue_waiting_component(self): + document_builder = component_class( + "DocumentBuilder", input_types={"text": str}, output_types={"doc": Document} + )() + document_joiner = component_class("DocumentJoiner", input_types={"docs": Variadic[Document]})() + + waiting_queue = [] + _enqueue_waiting_component(("document_builder", document_builder), waiting_queue) + assert waiting_queue == [("document_builder", document_builder)] + + waiting_queue = [("document_builder", document_builder)] + _enqueue_waiting_component(("document_builder", document_builder), waiting_queue) + assert waiting_queue == [("document_builder", document_builder)] + + waiting_queue = [("document_joiner", document_joiner)] + _enqueue_waiting_component(("document_builder", document_builder), waiting_queue) + assert waiting_queue == [("document_joiner", document_joiner), ("document_builder", document_builder)] + + waiting_queue = [("document_builder", document_builder), ("document_joiner", document_joiner)] + _enqueue_waiting_component(("document_builder", document_builder), waiting_queue) + assert waiting_queue == [("document_builder", document_builder), ("document_joiner", document_joiner)] + + def test__dequeue_waiting_component(self): + document_builder = component_class( + "DocumentBuilder", input_types={"text": str}, output_types={"doc": Document} + )() + document_joiner = component_class("DocumentJoiner", input_types={"docs": Variadic[Document]})() + + waiting_queue = [] + _dequeue_waiting_component(("document_builder", document_builder), waiting_queue) + assert waiting_queue == [] + + waiting_queue = [("document_builder", document_builder)] + _dequeue_waiting_component(("document_builder", document_builder), waiting_queue) + assert waiting_queue == [] + + waiting_queue = [("document_joiner", document_joiner)] + _dequeue_waiting_component(("document_builder", document_builder), waiting_queue) + assert waiting_queue == [("document_joiner", document_joiner)] + + waiting_queue = [("document_builder", document_builder), ("document_joiner", document_joiner)] + _dequeue_waiting_component(("document_builder", document_builder), waiting_queue) + assert waiting_queue == [("document_joiner", document_joiner)] + + def test__is_lazy_variadic(self): + VariadicAndGreedyVariadic = component_class( + "VariadicAndGreedyVariadic", input_types={"variadic": Variadic[int], "greedy_variadic": GreedyVariadic[int]} + ) + NonVariadic = component_class("NonVariadic", input_types={"value": int}) + VariadicNonGreedyVariadic = component_class( + "VariadicNonGreedyVariadic", input_types={"variadic": Variadic[int]} + ) + NonVariadicAndGreedyVariadic = component_class( + "NonVariadicAndGreedyVariadic", input_types={"greedy_variadic": GreedyVariadic[int]} + ) + assert not _is_lazy_variadic(VariadicAndGreedyVariadic()) + assert not _is_lazy_variadic(NonVariadic()) + assert _is_lazy_variadic(VariadicNonGreedyVariadic()) + assert not _is_lazy_variadic(NonVariadicAndGreedyVariadic()) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_templates.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..5e54c241be58318d5c7e5fcf5d1f0096879af79f --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_templates.py @@ -0,0 +1,63 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import tempfile +from unittest import mock + +import pytest + +from haystack import Pipeline +from haystack.core.pipeline.template import PipelineTemplate, PredefinedPipeline + + +@pytest.fixture +def random_valid_template(): + template = """ +components: + generator: + {{ generator | indent }} + + prompt_builder: + {{ prompt_builder | indent }} + +connections: + - receiver: generator.prompt + sender: prompt_builder.prompt +""" + return template + + +class TestPipelineTemplate: + def test_from_str(self): + with pytest.raises(ValueError): + PipelineTemplate("{{ invalid template }") + + assert PipelineTemplate("{{ valid_template }}").template_content == "{{ valid_template }}" + + def test_from_file(self, random_valid_template): + with pytest.raises(FileNotFoundError): + PipelineTemplate.from_file("invalid/path") + + with tempfile.NamedTemporaryFile(mode="w", delete=False) as fp: + fp.write(random_valid_template) + fp.seek(0) + assert PipelineTemplate.from_file(fp.name).template_content == random_valid_template + + def test_from_predefined(self): + tpl = PipelineTemplate.from_predefined(PredefinedPipeline.INDEXING) + assert len(tpl.template_content) + + # Building a pipeline directly using all default components specified in a predefined or custom template. + def test_build_pipeline_with_default_components(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "fake_key") + rendered = PipelineTemplate.from_predefined(PredefinedPipeline.INDEXING).render() + pipeline = Pipeline.loads(rendered) + + # pipeline has components + assert pipeline.get_component("cleaner") + assert pipeline.get_component("writer") + assert pipeline.get_component("embedder") + + # pipeline should have inputs and outputs + assert len(pipeline.inputs()) > 0 + assert len(pipeline.outputs()) > 0 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_tracing.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_tracing.py new file mode 100644 index 0000000000000000000000000000000000000000..83294bcc2c1140faa0c6e14c32c1ce1f15a4f019 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_tracing.py @@ -0,0 +1,139 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from test.tracing.utils import SpyingSpan, SpyingTracer +from typing import Optional +from unittest.mock import ANY + +import pytest +from _pytest.monkeypatch import MonkeyPatch + +from haystack import Pipeline, component +from haystack.tracing.tracer import tracer + + +@component +class Hello: + @component.output_types(output=str) + def run(self, word: Optional[str]): # use optional to spice up the typing tags + """ + Takes a string in input and returns "Hello, !" + in output. + """ + return {"output": f"Hello, {word}!"} + + +@pytest.fixture() +def pipeline() -> Pipeline: + pipeline = Pipeline() + pipeline.add_component("hello", Hello()) + pipeline.add_component("hello2", Hello()) + pipeline.connect("hello.output", "hello2.word") + return pipeline + + +class TestTracing: + def test_with_enabled_tracing(self, pipeline: Pipeline, spying_tracer: SpyingTracer) -> None: + pipeline.run(data={"word": "world"}) + + assert len(spying_tracer.spans) == 3 + + assert spying_tracer.spans == [ + SpyingSpan( + operation_name="haystack.pipeline.run", + tags={ + "haystack.pipeline.input_data": {"hello": {"word": "world"}}, + "haystack.pipeline.output_data": {"hello2": {"output": "Hello, Hello, world!!"}}, + "haystack.pipeline.metadata": {}, + "haystack.pipeline.max_runs_per_component": 100, + }, + trace_id=ANY, + span_id=ANY, + ), + SpyingSpan( + operation_name="haystack.component.run", + tags={ + "haystack.component.name": "hello", + "haystack.component.type": "Hello", + "haystack.component.input_types": {"word": "str"}, + "haystack.component.input_spec": {"word": {"type": ANY, "senders": []}}, + "haystack.component.output_spec": {"output": {"type": "str", "receivers": ["hello2"]}}, + "haystack.component.visits": 1, + }, + trace_id=ANY, + span_id=ANY, + ), + SpyingSpan( + operation_name="haystack.component.run", + tags={ + "haystack.component.name": "hello2", + "haystack.component.type": "Hello", + "haystack.component.input_types": {"word": "str"}, + "haystack.component.input_spec": {"word": {"type": ANY, "senders": ["hello"]}}, + "haystack.component.output_spec": {"output": {"type": "str", "receivers": []}}, + "haystack.component.visits": 1, + }, + trace_id=ANY, + span_id=ANY, + ), + ] + + # We need to check the type of the input_spec because it can be rendered differently + # depending on the Python version 🫠 + assert spying_tracer.spans[1].tags["haystack.component.input_spec"]["word"]["type"] in [ + "typing.Union[str, NoneType]", + "typing.Optional[str]", + ] + + def test_with_enabled_content_tracing( + self, spying_tracer: SpyingTracer, monkeypatch: MonkeyPatch, pipeline: Pipeline + ) -> None: + # Monkeypatch to avoid impact on other tests + monkeypatch.setattr(tracer, "is_content_tracing_enabled", True) + + pipeline.run(data={"word": "world"}) + + assert len(spying_tracer.spans) == 3 + assert spying_tracer.spans == [ + SpyingSpan( + operation_name="haystack.pipeline.run", + tags={ + "haystack.pipeline.metadata": {}, + "haystack.pipeline.max_runs_per_component": 100, + "haystack.pipeline.input_data": {"hello": {"word": "world"}}, + "haystack.pipeline.output_data": {"hello2": {"output": "Hello, Hello, world!!"}}, + }, + trace_id=ANY, + span_id=ANY, + ), + SpyingSpan( + operation_name="haystack.component.run", + tags={ + "haystack.component.name": "hello", + "haystack.component.type": "Hello", + "haystack.component.input_types": {"word": "str"}, + "haystack.component.input_spec": {"word": {"type": ANY, "senders": []}}, + "haystack.component.output_spec": {"output": {"type": "str", "receivers": ["hello2"]}}, + "haystack.component.input": {"word": "world"}, + "haystack.component.visits": 1, + "haystack.component.output": {"output": "Hello, world!"}, + }, + trace_id=ANY, + span_id=ANY, + ), + SpyingSpan( + operation_name="haystack.component.run", + tags={ + "haystack.component.name": "hello2", + "haystack.component.type": "Hello", + "haystack.component.input_types": {"word": "str"}, + "haystack.component.input_spec": {"word": {"type": ANY, "senders": ["hello"]}}, + "haystack.component.output_spec": {"output": {"type": "str", "receivers": []}}, + "haystack.component.input": {"word": "Hello, world!"}, + "haystack.component.visits": 1, + "haystack.component.output": {"output": "Hello, Hello, world!!"}, + }, + trace_id=ANY, + span_id=ANY, + ), + ] diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_type_utils.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_type_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e009853144f36cd63968e07dae95403789858ad3 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_type_utils.py @@ -0,0 +1,329 @@ +# 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, List, Literal, Mapping, Optional, Sequence, Set, Tuple, Union + +import pytest + +from haystack.core.type_utils import _type_name, _types_are_compatible + + +class Class1: + pass + + +class Class2: + pass + + +class Class3(Class1): + pass + + +class Enum1(Enum): + TEST1 = Class1 + TEST2 = Class2 + + +@pytest.mark.parametrize( + "type_,repr", + [ + pytest.param(str, "str", id="primitive-types"), + pytest.param(Any, "Any", id="any"), + pytest.param(Class1, "Class1", id="class"), + pytest.param((Optional[int]), "Optional[int]", id="shallow-optional-with-primitive"), + pytest.param((Optional[Any]), "Optional[Any]", id="shallow-optional-with-any"), + pytest.param((Optional[Class1]), "Optional[Class1]", id="shallow-optional-with-class"), + pytest.param((Union[(bool, Class1)]), "Union[bool, Class1]", id="shallow-union"), + pytest.param((List[str]), "List[str]", id="shallow-sequence-of-primitives"), + pytest.param((List[Set[Sequence[str]]]), "List[Set[Sequence[str]]]", id="nested-sequence-of-primitives"), + pytest.param( + (Optional[List[Set[Sequence[str]]]]), + "Optional[List[Set[Sequence[str]]]]", + id="optional-nested-sequence-of-primitives", + ), + pytest.param( + (List[Set[Sequence[Optional[str]]]]), + "List[Set[Sequence[Optional[str]]]]", + id="nested-optional-sequence-of-primitives", + ), + pytest.param((List[Class1]), "List[Class1]", id="shallow-sequence-of-classes"), + pytest.param((List[Set[Sequence[Class1]]]), "List[Set[Sequence[Class1]]]", id="nested-sequence-of-classes"), + pytest.param((Dict[(str, int)]), "Dict[str, int]", id="shallow-mapping-of-primitives"), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + "Dict[str, Mapping[str, Dict[str, int]]]", + id="nested-mapping-of-primitives", + ), + pytest.param( + (Dict[(str, Mapping[(Any, Dict[(str, int)])])]), + "Dict[str, Mapping[Any, Dict[str, int]]]", + id="nested-mapping-of-primitives-with-any", + ), + pytest.param((Dict[(str, Class1)]), "Dict[str, Class1]", id="shallow-mapping-of-classes"), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, Class1)])])]), + "Dict[str, Mapping[str, Dict[str, Class1]]]", + id="nested-mapping-of-classes", + ), + pytest.param((Literal["a", "b", "c"]), "Literal['a', 'b', 'c']", id="string-literal"), + pytest.param((Literal[1, 2, 3]), "Literal[1, 2, 3]", id="primitive-literal"), + pytest.param((Literal[Enum1.TEST1]), "Literal[Enum1.TEST1]", id="enum-literal"), + pytest.param( + (Tuple[(Optional[Literal["a", "b", "c"]], Union[(Path, Dict[(int, Class1)])])]), + "Tuple[Optional[Literal['a', 'b', 'c']], Union[Path, Dict[int, Class1]]]", + id="deeply-nested-complex-type", + ), + ], +) +def test_type_name(type_, repr): + assert _type_name(type_) == repr + + +@pytest.mark.parametrize( + "sender_type,receiver_type", + [ + pytest.param(str, str, id="same-primitives"), + pytest.param(str, (Optional[str]), id="receiving-primitive-is-optional"), + pytest.param(str, (Union[(int, str)]), id="receiving-type-is-union-of-primitives"), + pytest.param((Union[(int, str)]), (Union[(int, str)]), id="identical-unions"), + pytest.param((Union[(int, str)]), (Union[(int, str, bool)]), id="receiving-union-is-superset-of-sender"), + pytest.param(str, Any, id="primitive-to-any"), + pytest.param(Class1, Class1, id="same-class"), + pytest.param(Class1, (Optional[Class1]), id="receiving-class-is-optional"), + pytest.param(Class1, Class1, id="class-to-any"), + pytest.param(Class3, Class1, id="subclass-to-class"), + pytest.param(Class1, (Union[(int, Class1)]), id="receiving-type-is-union-of-classes"), + pytest.param(Class3, (Union[(int, Class1)]), id="receiving-type-is-union-of-superclasses"), + pytest.param((List[int]), (List[int]), id="same-lists"), + pytest.param((List[int]), (Optional[List[int]]), id="receiving-list-is-optional"), + pytest.param((List[int]), (List[Any]), id="list-of-primitive-to-list-of-any"), + pytest.param((List[Class1]), (List[Class1]), id="list-of-same-classes"), + pytest.param((List[Class3]), (List[Class1]), id="list-of-subclass-to-list-of-class"), + pytest.param((List[Class1]), (List[Any]), id="list-of-classes-to-list-of-any"), + pytest.param( + (List[Set[Sequence[bool]]]), (List[Set[Sequence[bool]]]), id="nested-sequences-of-same-primitives" + ), + pytest.param( + (List[Set[Sequence[bool]]]), + (List[Set[Sequence[Any]]]), + id="nested-sequences-of-primitives-to-nested-sequences-of-any", + ), + pytest.param( + (List[Set[Sequence[Class1]]]), (List[Set[Sequence[Class1]]]), id="nested-sequences-of-same-classes" + ), + pytest.param( + (List[Set[Sequence[Class3]]]), + (List[Set[Sequence[Class1]]]), + id="nested-sequences-of-subclasses-to-nested-sequences-of-classes", + ), + pytest.param( + (List[Set[Sequence[Class1]]]), + (List[Set[Sequence[Any]]]), + id="nested-sequences-of-classes-to-nested-sequences-of-any", + ), + pytest.param((Dict[(str, int)]), (Dict[(str, int)]), id="same-dicts-of-primitives"), + pytest.param((Dict[(str, int)]), (Dict[(Any, int)]), id="dict-of-primitives-to-dict-of-any-keys"), + pytest.param((Dict[(str, int)]), (Dict[(str, Any)]), id="dict-of-primitives-to-dict-of-any-values"), + pytest.param((Dict[(str, int)]), (Dict[(Any, Any)]), id="dict-of-primitives-to-dict-of-any-key-and-values"), + pytest.param((Dict[(str, Class1)]), (Dict[(str, Class1)]), id="same-dicts-of-classes-values"), + pytest.param((Dict[(str, Class3)]), (Dict[(str, Class1)]), id="dict-of-subclasses-to-dict-of-classes"), + pytest.param((Dict[(str, Class1)]), (Dict[(Any, Class1)]), id="dict-of-classes-to-dict-of-any-keys"), + pytest.param((Dict[(str, Class1)]), (Dict[(str, Any)]), id="dict-of-classes-to-dict-of-any-values"), + pytest.param((Dict[(str, Class1)]), (Dict[(Any, Any)]), id="dict-of-classes-to-dict-of-any-key-and-values"), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + id="nested-mappings-of-same-primitives", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + (Dict[(str, Mapping[(str, Dict[(Any, int)])])]), + id="nested-mapping-of-primitives-to-nested-mapping-of-any-keys", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + (Dict[(str, Mapping[(Any, Dict[(str, int)])])]), + id="nested-mapping-of-primitives-to-nested-mapping-of-higher-level-any-keys", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + (Dict[(str, Mapping[(str, Dict[(str, Any)])])]), + id="nested-mapping-of-primitives-to-nested-mapping-of-any-values", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + (Dict[(str, Mapping[(Any, Dict[(Any, Any)])])]), + id="nested-mapping-of-primitives-to-nested-mapping-of-any-keys-and-values", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, Class1)])])]), + (Dict[(str, Mapping[(str, Dict[(str, Class1)])])]), + id="nested-mappings-of-same-classes", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, Class3)])])]), + (Dict[(str, Mapping[(str, Dict[(str, Class1)])])]), + id="nested-mapping-of-subclasses-to-nested-mapping-of-classes", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, Class1)])])]), + (Dict[(str, Mapping[(str, Dict[(Any, Class1)])])]), + id="nested-mapping-of-classes-to-nested-mapping-of-any-keys", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, Class1)])])]), + (Dict[(str, Mapping[(Any, Dict[(str, Class1)])])]), + id="nested-mapping-of-classes-to-nested-mapping-of-higher-level-any-keys", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, Class1)])])]), + (Dict[(str, Mapping[(str, Dict[(str, Any)])])]), + id="nested-mapping-of-classes-to-nested-mapping-of-any-values", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, Class1)])])]), + (Dict[(str, Mapping[(Any, Dict[(Any, Any)])])]), + id="nested-mapping-of-classes-to-nested-mapping-of-any-keys-and-values", + ), + pytest.param((Literal["a", "b", "c"]), (Literal["a", "b", "c"]), id="same-primitive-literal"), + pytest.param((Literal[Enum1.TEST1]), (Literal[Enum1.TEST1]), id="same-enum-literal"), + pytest.param( + (Tuple[(Optional[Literal["a", "b", "c"]], Union[(Path, Dict[(int, Class1)])])]), + (Tuple[(Optional[Literal["a", "b", "c"]], Union[(Path, Dict[(int, Class1)])])]), + id="identical-deeply-nested-complex-type", + ), + ], +) +def test_types_are_compatible(sender_type, receiver_type): + assert _types_are_compatible(sender_type, receiver_type) + + +@pytest.mark.parametrize( + "sender_type,receiver_type", + [ + pytest.param(int, bool, id="different-primitives"), + pytest.param(Class1, Class2, id="different-classes"), + pytest.param(Class1, Class3, id="class-to-subclass"), + pytest.param(Any, int, id="any-to-primitive"), + pytest.param(Any, Class2, id="any-to-class"), + pytest.param((Optional[str]), str, id="sending-primitive-is-optional"), + pytest.param((Optional[Class1]), Class1, id="sending-class-is-optional"), + pytest.param((Optional[List[int]]), (List[int]), id="sending-list-is-optional"), + pytest.param((Union[(int, str)]), str, id="sending-type-is-union"), + pytest.param((Union[(int, str, bool)]), (Union[(int, str)]), id="sending-union-is-superset-of-receiver"), + pytest.param((Union[(int, bool)]), (Union[(int, str)]), id="partially-overlapping-unions-with-primitives"), + pytest.param((Union[(int, Class1)]), (Union[(int, Class2)]), id="partially-overlapping-unions-with-classes"), + pytest.param((List[int]), (List[str]), id="different-lists-of-primitives"), + pytest.param((List[int]), List, id="list-of-primitive-to-bare-list"), + pytest.param((List[int]), list, id="list-of-primitive-to-list-object"), + pytest.param((List[Class1]), (List[Class2]), id="different-lists-of-classes"), + pytest.param((List[Class1]), (List[Class3]), id="lists-of-classes-to-subclasses"), + pytest.param((List[Any]), (List[str]), id="list-of-any-to-list-of-primitives"), + pytest.param((List[Any]), (List[Class2]), id="list-of-any-to-list-of-classes"), + pytest.param( + (List[Set[Sequence[str]]]), (List[Set[Sequence[bool]]]), id="nested-sequences-of-different-primitives" + ), + pytest.param( + (List[Set[Sequence[str]]]), (Set[List[Sequence[str]]]), id="different-nested-sequences-of-same-primitives" + ), + pytest.param( + (List[Set[Sequence[Class1]]]), (List[Set[Sequence[Class2]]]), id="nested-sequences-of-different-classes" + ), + pytest.param( + (List[Set[Sequence[Class1]]]), (List[Set[Sequence[Class3]]]), id="nested-sequences-of-classes-to-subclasses" + ), + pytest.param( + (List[Set[Sequence[Class1]]]), (Set[List[Sequence[Class1]]]), id="different-nested-sequences-of-same-class" + ), + pytest.param( + (List[Set[Sequence[Any]]]), + (List[Set[Sequence[bool]]]), + id="nested-list-of-Any-to-nested-list-of-primitives", + ), + pytest.param( + (List[Set[Sequence[Any]]]), (List[Set[Sequence[Class2]]]), id="nested-list-of-Any-to-nested-list-of-classes" + ), + pytest.param((Dict[(str, int)]), (Dict[(int, int)]), id="different-dict-of-primitive-keys"), + pytest.param((Dict[(str, int)]), (Dict[(str, bool)]), id="different-dict-of-primitive-values"), + pytest.param((Dict[(str, Class1)]), (Dict[(str, Class2)]), id="different-dict-of-class-values"), + pytest.param((Dict[(str, Class1)]), (Dict[(str, Class3)]), id="different-dict-of-class-to-subclass-values"), + pytest.param((Dict[(Any, int)]), (Dict[(int, int)]), id="dict-of-Any-keys-to-dict-of-primitives"), + pytest.param((Dict[(str, Any)]), (Dict[(int, int)]), id="dict-of-Any-values-to-dict-of-primitives"), + pytest.param((Dict[(str, Any)]), (Dict[(int, Class1)]), id="dict-of-Any-values-to-dict-of-classes"), + pytest.param((Dict[(Any, Any)]), (Dict[(int, int)]), id="dict-of-Any-keys-and-values-to-dict-of-primitives"), + pytest.param((Dict[(Any, Any)]), (Dict[(int, Class1)]), id="dict-of-Any-keys-and-values-to-dict-of-classes"), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + (Mapping[(str, Dict[(str, Dict[(str, int)])])]), + id="different-nested-mappings-of-same-primitives", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + (Dict[(str, Mapping[(str, Dict[(int, int)])])]), + id="same-nested-mappings-of-different-primitive-keys", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + (Dict[(str, Mapping[(int, Dict[(str, int)])])]), + id="same-nested-mappings-of-different-higer-level-primitive-keys", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + (Dict[(str, Mapping[(str, Dict[(str, bool)])])]), + id="same-nested-mappings-of-different-primitive-values", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, Class1)])])]), + (Dict[(str, Mapping[(str, Dict[(str, Class2)])])]), + id="same-nested-mappings-of-different-class-values", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, Class1)])])]), + (Dict[(str, Mapping[(str, Dict[(str, Class2)])])]), + id="same-nested-mappings-of-class-to-subclass-values", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(Any, int)])])]), + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + id="nested-mapping-of-Any-keys-to-nested-mapping-of-primitives", + ), + pytest.param( + (Dict[(str, Mapping[(Any, Dict[(Any, int)])])]), + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + id="nested-mapping-of-higher-level-Any-keys-to-nested-mapping-of-primitives", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, Any)])])]), + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + id="nested-mapping-of-Any-values-to-nested-mapping-of-primitives", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(str, Any)])])]), + (Dict[(str, Mapping[(str, Dict[(str, Class1)])])]), + id="nested-mapping-of-Any-values-to-nested-mapping-of-classes", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(Any, Any)])])]), + (Dict[(str, Mapping[(str, Dict[(str, int)])])]), + id="nested-mapping-of-Any-keys-and-values-to-nested-mapping-of-primitives", + ), + pytest.param( + (Dict[(str, Mapping[(str, Dict[(Any, Any)])])]), + (Dict[(str, Mapping[(str, Dict[(str, Class1)])])]), + id="nested-mapping-of-Any-keys-and-values-to-nested-mapping-of-classes", + ), + pytest.param((Literal["a", "b", "c"]), (Literal["x", "y"]), id="different-literal-of-same-primitive"), + pytest.param((Literal["a", "b", "c"]), (Literal["a", "b"]), id="subset-literal"), + pytest.param((Literal[Enum1.TEST1]), (Literal[Enum1.TEST2]), id="different-literal-of-same-enum"), + pytest.param( + (Tuple[(Optional[Literal["a", "b", "c"]], Union[(Path, Dict[(int, Class1)])])]), + (Tuple[(Literal["a", "b", "c"], Union[(Path, Dict[(int, Class1)])])]), + id="deeply-nested-complex-type-is-compatible-but-cannot-be-checked", + ), + ], +) +def test_types_are_not_compatible(sender_type, receiver_type): + assert not _types_are_compatible(sender_type, receiver_type) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_utils.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fcb5734f50230dc38bf0f6caee95c7bb6f389251 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_utils.py @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from haystack.core.pipeline.utils import parse_connect_string + + +def test_parse_connection(): + assert parse_connect_string("foobar") == ("foobar", None) + assert parse_connect_string("foo.bar") == ("foo", "bar") diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_validation_pipeline_io.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_validation_pipeline_io.py new file mode 100644 index 0000000000000000000000000000000000000000..f9160799fec9c97d9ff6b2d8fff4a0bd40700e84 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/pipeline/test_validation_pipeline_io.py @@ -0,0 +1,205 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from typing import Optional + +import pytest + +from haystack.core.component.types import InputSocket, OutputSocket, Variadic +from haystack.core.errors import PipelineValidationError +from haystack.core.pipeline import Pipeline +from haystack.core.pipeline.descriptions import find_pipeline_inputs, find_pipeline_outputs +from haystack.testing.sample_components import AddFixedValue, Double, Parity, Sum + + +def test_find_pipeline_input_no_input(): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + pipe.connect("comp2", "comp1") + + assert find_pipeline_inputs(pipe.graph) == {"comp1": [], "comp2": []} + + +def test_find_pipeline_input_one_input(): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + + assert find_pipeline_inputs(pipe.graph) == {"comp1": [InputSocket(name="value", type=int)], "comp2": []} + + +def test_find_pipeline_input_two_inputs_same_component(): + pipe = Pipeline() + pipe.add_component("comp1", AddFixedValue()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + + assert find_pipeline_inputs(pipe.graph) == { + "comp1": [InputSocket(name="value", type=int), InputSocket(name="add", type=Optional[int], default_value=None)], + "comp2": [], + } + + +def test_find_pipeline_input_some_inputs_different_components(): + pipe = Pipeline() + pipe.add_component("comp1", AddFixedValue()) + pipe.add_component("comp2", Double()) + pipe.add_component("comp3", AddFixedValue()) + pipe.connect("comp1.result", "comp3.value") + pipe.connect("comp2.value", "comp3.add") + + assert find_pipeline_inputs(pipe.graph) == { + "comp1": [InputSocket(name="value", type=int), InputSocket(name="add", type=Optional[int], default_value=None)], + "comp2": [InputSocket(name="value", type=int)], + "comp3": [], + } + + +def test_find_pipeline_variable_input_nodes_in_the_pipeline(): + pipe = Pipeline() + pipe.add_component("comp1", AddFixedValue()) + pipe.add_component("comp2", Double()) + pipe.add_component("comp3", Sum()) + + assert find_pipeline_inputs(pipe.graph) == { + "comp1": [InputSocket(name="value", type=int), InputSocket(name="add", type=Optional[int], default_value=None)], + "comp2": [InputSocket(name="value", type=int)], + "comp3": [InputSocket(name="values", type=Variadic[int])], + } + + +def test_find_pipeline_output_no_output(): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + pipe.connect("comp2", "comp1") + + assert find_pipeline_outputs(pipe.graph) == {"comp1": [], "comp2": []} + + +def test_find_pipeline_output_one_output(): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + + assert find_pipeline_outputs(pipe.graph) == {"comp1": [], "comp2": [OutputSocket(name="value", type=int)]} + + +def test_find_pipeline_some_outputs_same_component(): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Parity()) + pipe.connect("comp1", "comp2") + + assert find_pipeline_outputs(pipe.graph) == { + "comp1": [], + "comp2": [OutputSocket(name="even", type=int), OutputSocket(name="odd", type=int)], + } + + +def test_find_pipeline_some_outputs_different_components(): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Parity()) + pipe.add_component("comp3", Double()) + pipe.connect("comp1", "comp2") + pipe.connect("comp1", "comp3") + + assert find_pipeline_outputs(pipe.graph) == { + "comp1": [], + "comp2": [OutputSocket(name="even", type=int), OutputSocket(name="odd", type=int)], + "comp3": [OutputSocket(name="value", type=int)], + } + + +def test_validate_pipeline_input_pipeline_with_no_inputs(): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + pipe.connect("comp2", "comp1") + res = pipe.run({}) + assert res == {} + + +def test_validate_pipeline_input_unknown_component(): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + with pytest.raises(ValueError): + pipe.run({"test_component": {"value": 1}}) + + +def test_validate_pipeline_input_all_necessary_input_is_present(): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + with pytest.raises(ValueError): + pipe.run({}) + + +def test_validate_pipeline_input_all_necessary_input_is_present_considering_defaults(): + pipe = Pipeline() + pipe.add_component("comp1", AddFixedValue()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + pipe.run({"comp1": {"value": 1}}) + pipe.run({"comp1": {"value": 1, "add": 2}}) + with pytest.raises(ValueError): + pipe.run({"comp1": {"add": 3}}) + + +def test_validate_pipeline_input_only_expected_input_is_present(): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + with pytest.raises(ValueError): + pipe.run({"comp1": {"value": 1}, "comp2": {"value": 2}}) + + +def test_validate_pipeline_input_only_expected_input_is_present_falsy(): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + with pytest.raises(ValueError): + pipe.run({"comp1": {"value": 1}, "comp2": {"value": 0}}) + + +def test_validate_pipeline_falsy_input_present(): + pipe = Pipeline() + pipe.add_component("comp", Double()) + assert pipe.run({"comp": {"value": 0}}) == {"comp": {"value": 0}} + + +def test_validate_pipeline_falsy_input_missing(): + pipe = Pipeline() + pipe.add_component("comp", Double()) + with pytest.raises(ValueError): + pipe.run({"comp": {}}) + + +def test_validate_pipeline_input_only_expected_input_is_present_including_unknown_names(): + pipe = Pipeline() + pipe.add_component("comp1", Double()) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + + with pytest.raises(ValueError): + pipe.run({"comp1": {"value": 1, "add": 2}}) + + +def test_validate_pipeline_input_only_expected_input_is_present_and_defaults_dont_interfere(): + pipe = Pipeline() + pipe.add_component("comp1", AddFixedValue(add=10)) + pipe.add_component("comp2", Double()) + pipe.connect("comp1", "comp2") + assert pipe.run({"comp1": {"value": 1, "add": 5}}) == {"comp2": {"value": 12}} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_accumulate.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_accumulate.py new file mode 100644 index 0000000000000000000000000000000000000000..8e31cc63d7d5d93315fafaeb48a66cc170b0aa66 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_accumulate.py @@ -0,0 +1,73 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from haystack.testing.sample_components.accumulate import Accumulate, _default_function + + +def my_subtract(first, second): + return first - second + + +def test_to_dict(): + accumulate = Accumulate() + res = accumulate.to_dict() + assert res == { + "type": "haystack.testing.sample_components.accumulate.Accumulate", + "init_parameters": {"function": "haystack.testing.sample_components.accumulate._default_function"}, + } + + +def test_to_dict_with_custom_function(): + accumulate = Accumulate(function=my_subtract) + res = accumulate.to_dict() + assert res == { + "type": "haystack.testing.sample_components.accumulate.Accumulate", + "init_parameters": {"function": "test_accumulate.my_subtract"}, + } + + +def test_from_dict(): + data = {"type": "haystack.testing.sample_components.accumulate.Accumulate", "init_parameters": {}} + accumulate = Accumulate.from_dict(data) + assert accumulate.function == _default_function + + +def test_from_dict_with_default_function(): + data = { + "type": "haystack.testing.sample_components.accumulate.Accumulate", + "init_parameters": {"function": "haystack.testing.sample_components.accumulate._default_function"}, + } + accumulate = Accumulate.from_dict(data) + assert accumulate.function == _default_function + + +def test_from_dict_with_custom_function(): + data = { + "type": "haystack.testing.sample_components.accumulate.Accumulate", + "init_parameters": {"function": "test_accumulate.my_subtract"}, + } + accumulate = Accumulate.from_dict(data) + assert accumulate.function == my_subtract + + +def test_accumulate_default(): + component = Accumulate() + results = component.run(value=10) + assert results == {"value": 10} + assert component.state == 10 + + results = component.run(value=1) + assert results == {"value": 11} + assert component.state == 11 + + +def test_accumulate_callable(): + component = Accumulate(function=my_subtract) + + results = component.run(value=10) + assert results == {"value": -10} + assert component.state == -10 + + results = component.run(value=1) + assert results == {"value": -11} + assert component.state == -11 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_add_value.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_add_value.py new file mode 100644 index 0000000000000000000000000000000000000000..229950de60f2060fe7939801273be9eba4b18463 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/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} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_concatenate.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_concatenate.py new file mode 100644 index 0000000000000000000000000000000000000000..af360a61d60dfed4c89d16cbdd8164aa3ddd8b0c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_concatenate.py @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from haystack.testing.sample_components import Concatenate +from haystack.core.serialization import component_to_dict, component_from_dict + + +def test_input_lists(): + component = Concatenate() + res = component.run(first=["This"], second=["That"]) + assert res == {"value": ["This", "That"]} + + +def test_input_strings(): + component = Concatenate() + res = component.run(first="This", second="That") + assert res == {"value": ["This", "That"]} + + +def test_input_first_list_second_string(): + component = Concatenate() + res = component.run(first=["This"], second="That") + assert res == {"value": ["This", "That"]} + + +def test_input_first_string_second_list(): + component = Concatenate() + res = component.run(first="This", second=["That"]) + assert res == {"value": ["This", "That"]} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_double.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_double.py new file mode 100644 index 0000000000000000000000000000000000000000..e9da75246cbdf67707c1fac8c3c4f1f40d33e0dc --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_double.py @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.testing.sample_components import Double +from haystack.core.serialization import component_to_dict, component_from_dict + + +def test_double_default(): + component = Double() + results = component.run(value=10) + assert results == {"value": 20} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_fstring.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_fstring.py new file mode 100644 index 0000000000000000000000000000000000000000..0013d48bda846bcf78f4a55613a3d17fcf9b2143 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_fstring.py @@ -0,0 +1,41 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest +from haystack.testing.sample_components import FString + + +def test_fstring_with_one_var(): + fstring = FString(template="Hello, {name}!", variables=["name"]) + output = fstring.run(name="Alice") + assert output == {"string": "Hello, Alice!"} + + +def test_fstring_with_no_vars(): + fstring = FString(template="No variables in this template.", variables=[]) + output = fstring.run() + assert output == {"string": "No variables in this template."} + + +def test_fstring_with_template_at_runtime(): + fstring = FString(template="Hello {name}", variables=["name"]) + output = fstring.run(template="Goodbye {name}!", name="Alice") + assert output == {"string": "Goodbye Alice!"} + + +def test_fstring_with_vars_mismatch(): + fstring = FString(template="Hello {name}", variables=["name"]) + with pytest.raises(KeyError): + fstring.run(template="Goodbye {person}!", name="Alice") + + +def test_fstring_with_vars_in_excess(): + fstring = FString(template="Hello {name}", variables=["name"]) + output = fstring.run(template="Goodbye!", name="Alice") + assert output == {"string": "Goodbye!"} + + +def test_fstring_with_vars_missing(): + fstring = FString(template="{greeting}, {name}!", variables=["name"]) + with pytest.raises(KeyError): + fstring.run(greeting="Hello") diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_greet.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_greet.py new file mode 100644 index 0000000000000000000000000000000000000000..4c19a2b743d626631596405c39eef5080ac4dfc1 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_greet.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging + +from haystack.testing.sample_components import Greet +from haystack.core.serialization import component_to_dict, component_from_dict + + +def test_greet_message(caplog): + caplog.set_level(logging.WARNING) + component = Greet() + results = component.run(value=10, message="Hello, that's {value}", log_level="WARNING") + assert results == {"value": 10} + assert "Hello, that's 10" in caplog.text diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_parity.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_parity.py new file mode 100644 index 0000000000000000000000000000000000000000..9052ba93ced45c4d35f07841ead03d3fc46d6e54 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_parity.py @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from haystack.testing.sample_components import Parity +from haystack.core.serialization import component_to_dict, component_from_dict + + +def test_parity(): + component = Parity() + results = component.run(value=1) + assert results == {"odd": 1} + results = component.run(value=2) + assert results == {"even": 2} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_remainder.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_remainder.py new file mode 100644 index 0000000000000000000000000000000000000000..95b2052a442efad4837ec9e1eeb5858eaf9daf51 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_remainder.py @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack.testing.sample_components import Remainder +from haystack.core.serialization import component_to_dict, component_from_dict + + +def test_remainder_default(): + component = Remainder() + results = component.run(value=4) + assert results == {"remainder_is_1": 4} + + +def test_remainder_with_divisor(): + component = Remainder(divisor=4) + results = component.run(value=4) + assert results == {"remainder_is_0": 4} + + +def test_remainder_zero(): + with pytest.raises(ValueError): + Remainder(divisor=0) diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_repeat.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_repeat.py new file mode 100644 index 0000000000000000000000000000000000000000..6438601538fc36b15e2a616838776d4d79ae1687 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_repeat.py @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from haystack.testing.sample_components import Repeat +from haystack.core.serialization import component_to_dict, component_from_dict + + +def test_repeat_default(): + component = Repeat(outputs=["one", "two"]) + results = component.run(value=10) + assert results == {"one": 10, "two": 10} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_subtract.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_subtract.py new file mode 100644 index 0000000000000000000000000000000000000000..9f841976491eb4022ae6e6f619f1ee0122c4509a --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_subtract.py @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from haystack.testing.sample_components import Subtract +from haystack.core.serialization import component_to_dict, component_from_dict + + +def test_subtract(): + component = Subtract() + results = component.run(first_value=10, second_value=7) + assert results == {"difference": 3} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_sum.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_sum.py new file mode 100644 index 0000000000000000000000000000000000000000..5d351c8db14bcc826f4b5f82c30f9a8b028ca0e0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_sum.py @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.testing.sample_components import Sum +from haystack.core.serialization import component_to_dict, component_from_dict + + +def test_sum_receives_no_values(): + component = Sum() + results = component.run(values=[]) + assert results == {"total": 0} + + +def test_sum_receives_one_value(): + component = Sum() + assert component.run(values=[10]) == {"total": 10} + + +def test_sum_receives_few_values(): + component = Sum() + assert component.run(values=[10, 2]) == {"total": 12} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_threshold.py b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_threshold.py new file mode 100644 index 0000000000000000000000000000000000000000..b8bedd68e26e0013ce5460cac0efb14f91b8ca62 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/core/sample_components/test_threshold.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from haystack.testing.sample_components import Threshold +from haystack.core.serialization import component_to_dict, component_from_dict + + +def test_threshold(): + component = Threshold() + + results = component.run(value=5, threshold=10) + assert results == {"below": 5} + + results = component.run(value=15, threshold=10) + assert results == {"above": 15} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/csv/sample_1.csv b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/csv/sample_1.csv new file mode 100644 index 0000000000000000000000000000000000000000..d3fc3116b155fe1e9e742232633b816f229b9b47 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/csv/sample_1.csv @@ -0,0 +1,4 @@ +Name,Age +John Doe,27 +Jane Smith,37 +Mike Johnson,47 diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/csv/sample_2.csv b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/csv/sample_2.csv new file mode 100644 index 0000000000000000000000000000000000000000..3e23848a71582772d530ea75bf8ed2861d38c18b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/csv/sample_2.csv @@ -0,0 +1,4 @@ +Name,City +John Doe,New York +Jane Smith,Los Angeles +Mike Johnson,Chicago diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/csv/sample_3.csv b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/csv/sample_3.csv new file mode 100644 index 0000000000000000000000000000000000000000..fcc805b0a347bc1e7f99e47fdf42ebb331e9909c --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/csv/sample_3.csv @@ -0,0 +1,4 @@ +Name,Email +John Doe,johndoe@example.com +Jane Smith,janesmith@example.com +Mike Johnson,mikejohnson@example.com diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/docx/sample_docx.docx b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/docx/sample_docx.docx new file mode 100644 index 0000000000000000000000000000000000000000..3a740ac96876f71e624fbc80fd2cb2408024e34f Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/docx/sample_docx.docx differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/docx/sample_docx_1.docx b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/docx/sample_docx_1.docx new file mode 100644 index 0000000000000000000000000000000000000000..baa1f34d7e83dfe720a52ff4f0cce97e824e85a1 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/docx/sample_docx_1.docx differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/docx/sample_docx_2_page_breaks.docx b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/docx/sample_docx_2_page_breaks.docx new file mode 100644 index 0000000000000000000000000000000000000000..d83fb80f8cfdee9835225684859ebcd5df5a02c9 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/docx/sample_docx_2_page_breaks.docx differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/html/paul_graham_superlinear.html b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/html/paul_graham_superlinear.html new file mode 100644 index 0000000000000000000000000000000000000000..ee1e51f304be971f12f86a2583c2f4ddfea3c65e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/html/paul_graham_superlinear.html @@ -0,0 +1,417 @@ +Superlinear Returns + +


Superlinear Returns

October 2023

One of the most important things I didn't understand about the world +when I was a child is the degree to which the returns for performance +are superlinear.

Teachers and coaches implicitly told us the returns were linear. +"You get out," I heard a thousand times, "what you put in." They +meant well, but this is rarely true. If your product is only half +as good as your competitor's, you don't get half as many customers. +You get no customers, and you go out of business.

It's obviously true that the returns for performance are superlinear +in business. Some think this is a flaw of capitalism, and that if +we changed the rules it would stop being true. But superlinear +returns for performance are a feature of the world, not an artifact +of rules we've invented. We see the same pattern in fame, power, +military victories, knowledge, and even benefit to humanity. In all +of these, the rich get richer. +[1]

You can't understand the world without understanding the concept +of superlinear returns. And if you're ambitious you definitely +should, because this will be the wave you surf on.





It may seem as if there are a lot of different situations with +superlinear returns, but as far as I can tell they reduce to two +fundamental causes: exponential growth and thresholds.

The most obvious case of superlinear returns is when you're working +on something that grows exponentially. For example, growing bacterial +cultures. When they grow at all, they grow exponentially. But they're +tricky to grow. Which means the difference in outcome between someone +who's adept at it and someone who's not is very great.

Startups can also grow exponentially, and we see the same pattern +there. Some manage to achieve high growth rates. Most don't. And +as a result you get qualitatively different outcomes: the companies +with high growth rates tend to become immensely valuable, while the +ones with lower growth rates may not even survive.

Y Combinator encourages founders to focus on growth rate rather +than absolute numbers. It prevents them from being discouraged early +on, when the absolute numbers are still low. It also helps them +decide what to focus on: you can use growth rate as a compass to +tell you how to evolve the company. But the main advantage is that +by focusing on growth rate you tend to get something that grows +exponentially.

YC doesn't explicitly tell founders that with growth rate "you get +out what you put in," but it's not far from the truth. And if growth +rate were proportional to performance, then the reward for performance +p over time t would be proportional to pt.

Even after decades of thinking about this, I find that sentence +startling.

Whenever how well you do depends on how well you've done, you'll +get exponential growth. But neither our DNA nor our customs prepare +us for it. No one finds exponential growth natural; every child is +surprised, the first time they hear it, by the story of the man who +asks the king for a single grain of rice the first day and double +the amount each successive day.

What we don't understand naturally we develop customs to deal with, +but we don't have many customs about exponential growth either, +because there have been so few instances of it in human history. +In principle herding should have been one: the more animals you +had, the more offspring they'd have. But in practice grazing land +was the limiting factor, and there was no plan for growing that +exponentially.

Or more precisely, no generally applicable plan. There was a way +to grow one's territory exponentially: by conquest. The more territory +you control, the more powerful your army becomes, and the easier +it is to conquer new territory. This is why history is full of +empires. But so few people created or ran empires that their +experiences didn't affect customs very much. The emperor was a +remote and terrifying figure, not a source of lessons one could use +in one's own life.

The most common case of exponential growth in preindustrial times +was probably scholarship. The more you know, the easier it is to +learn new things. The result, then as now, was that some people +were startlingly more knowledgeable than the rest about certain +topics. But this didn't affect customs much either. Although empires +of ideas can overlap and there can thus be far more emperors, in +preindustrial times this type of empire had little practical effect. +[2]

That has changed in the last few centuries. Now the emperors of +ideas can design bombs that defeat the emperors of territory. But +this phenomenon is still so new that we haven't fully assimilated +it. Few even of the participants realize they're benefitting from +exponential growth or ask what they can learn from other instances +of it.

The other source of superlinear returns is embodied in the expression +"winner take all." In a sports match the relationship between +performance and return is a step function: the winning team gets +one win whether they do much better or just slightly better. +[3]

The source of the step function is not competition per se, however. +It's that there are thresholds in the outcome. You don't need +competition to get those. There can be thresholds in situations +where you're the only participant, like proving a theorem or hitting +a target.

It's remarkable how often a situation with one source of superlinear +returns also has the other. Crossing thresholds leads to exponential +growth: the winning side in a battle usually suffers less damage, +which makes them more likely to win in the future. And exponential +growth helps you cross thresholds: in a market with network effects, +a company that grows fast enough can shut out potential competitors.

Fame is an interesting example of a phenomenon that combines both +sources of superlinear returns. Fame grows exponentially because +existing fans bring you new ones. But the fundamental reason it's +so concentrated is thresholds: there's only so much room on the +A-list in the average person's head.

The most important case combining both sources of superlinear returns +may be learning. Knowledge grows exponentially, but there are also +thresholds in it. Learning to ride a bicycle, for example. Some of +these thresholds are akin to machine tools: once you learn to read, +you're able to learn anything else much faster. But the most important +thresholds of all are those representing new discoveries. Knowledge +seems to be fractal in the sense that if you push hard at the +boundary of one area of knowledge, you sometimes discover a whole +new field. And if you do, you get first crack at all the new +discoveries to be made in it. Newton did this, and so did Durer and +Darwin.





+Are there general rules for finding situations with superlinear +returns? The most obvious one is to seek work that compounds.

There are two ways work can compound. It can compound directly, in +the sense that doing well in one cycle causes you to do better in +the next. That happens for example when you're building infrastructure, +or growing an audience or brand. Or work can compound by teaching +you, since learning compounds. This second case is an interesting +one because you may feel you're doing badly as it's happening. You +may be failing to achieve your immediate goal. But if you're learning +a lot, then you're getting exponential growth nonetheless.

This is one reason Silicon Valley is so tolerant of failure. People +in Silicon Valley aren't blindly tolerant of failure. They'll only +continue to bet on you if you're learning from your failures. But +if you are, you are in fact a good bet: maybe your company didn't +grow the way you wanted, but you yourself have, and that should +yield results eventually.

Indeed, the forms of exponential growth that don't consist of +learning are so often intermixed with it that we should probably +treat this as the rule rather than the exception. Which yields +another heuristic: always be learning. If you're not learning, +you're probably not on a path that leads to superlinear returns.

But don't overoptimize what you're learning. Don't limit yourself +to learning things that are already known to be valuable. You're +learning; you don't know for sure yet what's going to be valuable, +and if you're too strict you'll lop off the outliers.

What about step functions? Are there also useful heuristics of the +form "seek thresholds" or "seek competition?" Here the situation +is trickier. The existence of a threshold doesn't guarantee the +game will be worth playing. If you play a round of Russian roulette, +you'll be in a situation with a threshold, certainly, but in the +best case you're no better off. "Seek competition" is similarly +useless; what if the prize isn't worth competing for? Sufficiently +fast exponential growth guarantees both the shape and magnitude of +the return curve — because something that grows fast enough will +grow big even if it's trivially small at first — but thresholds +only guarantee the shape. +[4]

A principle for taking advantage of thresholds has to include a +test to ensure the game is worth playing. Here's one that does: if +you come across something that's mediocre yet still popular, it +could be a good idea to replace it. For example, if a company makes +a product that people dislike yet still buy, then presumably they'd +buy a better alternative if you made one. +[5]

It would be great if there were a way to find promising intellectual +thresholds. Is there a way to tell which questions have whole new +fields beyond them? I doubt we could ever predict this with certainty, +but the prize is so valuable that it would be useful to have +predictors that were even a little better than random, and there's +hope of finding those. We can to some degree predict when a research +problem isn't likely to lead to new discoveries: when it seems +legit but boring. Whereas the kind that do lead to new discoveries +tend to seem very mystifying, but perhaps unimportant. (If they +were mystifying and obviously important, they'd be famous open +questions with lots of people already working on them.) So one +heuristic here is to be driven by curiosity rather than careerism +— to give free rein to your curiosity instead of working on what +you're supposed to.





+The prospect of superlinear returns for performance is an exciting +one for the ambitious. And there's good news in this department: +this territory is expanding in both directions. There are more types +of work in which you can get superlinear returns, and the returns +themselves are growing.

There are two reasons for this, though they're so closely intertwined +that they're more like one and a half: progress in technology, and +the decreasing importance of organizations.

Fifty years ago it used to be much more necessary to be part of an +organization to work on ambitious projects. It was the only way to +get the resources you needed, the only way to have colleagues, and +the only way to get distribution. So in 1970 your prestige was in +most cases the prestige of the organization you belonged to. And +prestige was an accurate predictor, because if you weren't part of +an organization, you weren't likely to achieve much. There were a +handful of exceptions, most notably artists and writers, who worked +alone using inexpensive tools and had their own brands. But even +they were at the mercy of organizations for reaching audiences. +[6]

A world dominated by organizations damped variation in the returns +for performance. But this world has eroded significantly just in +my lifetime. Now a lot more people can have the freedom that artists +and writers had in the 20th century. There are lots of ambitious +projects that don't require much initial funding, and lots of new +ways to learn, make money, find colleagues, and reach audiences.

There's still plenty of the old world left, but the rate of change +has been dramatic by historical standards. Especially considering +what's at stake. It's hard to imagine a more fundamental change +than one in the returns for performance.

Without the damping effect of institutions, there will be more +variation in outcomes. Which doesn't imply everyone will be better +off: people who do well will do even better, but those who do badly +will do worse. That's an important point to bear in mind. Exposing +oneself to superlinear returns is not for everyone. Most people +will be better off as part of the pool. So who should shoot for +superlinear returns? Ambitious people of two types: those who know +they're so good that they'll be net ahead in a world with higher +variation, and those, particularly the young, who can afford to +risk trying it to find out. +[7]

The switch away from institutions won't simply be an exodus of their +current inhabitants. Many of the new winners will be people they'd +never have let in. So the resulting democratization of opportunity +will be both greater and more authentic than any tame intramural +version the institutions themselves might have cooked up.





+Not everyone is happy about this great unlocking of ambition. It +threatens some vested interests and contradicts some ideologies. [8] +But if you're an ambitious individual it's good news for you. +How should you take advantage of it?

The most obvious way to take advantage of superlinear returns for +performance is by doing exceptionally good work. At the far end of +the curve, incremental effort is a bargain. All the more so because +there's less competition at the far end — and not just for the +obvious reason that it's hard to do something exceptionally well, +but also because people find the prospect so intimidating that few +even try. Which means it's not just a bargain to do exceptional +work, but a bargain even to try to.

There are many variables that affect how good your work is, and if +you want to be an outlier you need to get nearly all of them right. +For example, to do something exceptionally well, you have to be +interested in it. Mere diligence is not enough. So in a world with +superlinear returns, it's even more valuable to know what you're +interested in, and to find ways to work on it. +[9] +It will also be +important to choose work that suits your circumstances. For example, +if there's a kind of work that inherently requires a huge expenditure +of time and energy, it will be increasingly valuable to do it when +you're young and don't yet have children.

There's a surprising amount of technique to doing great work. +It's not just a matter of trying hard. I'm going to take a shot +giving a recipe in one paragraph.

Choose work you have a natural aptitude for and a deep interest in. +Develop a habit of working on your own projects; it doesn't matter +what they are so long as you find them excitingly ambitious. Work +as hard as you can without burning out, and this will eventually +bring you to one of the frontiers of knowledge. These look smooth +from a distance, but up close they're full of gaps. Notice and +explore such gaps, and if you're lucky one will expand into a whole +new field. Take as much risk as you can afford; if you're not failing +occasionally you're probably being too conservative. Seek out the +best colleagues. Develop good taste and learn from the best examples. +Be honest, especially with yourself. Exercise and eat and sleep +well and avoid the more dangerous drugs. When in doubt, follow your +curiosity. It never lies, and it knows more than you do about what's +worth paying attention to. +[10]

And there is of course one other thing you need: to be lucky. Luck +is always a factor, but it's even more of a factor when you're +working on your own rather than as part of an organization. And +though there are some valid aphorisms about luck being where +preparedness meets opportunity and so on, there's also a component +of true chance that you can't do anything about. The solution is +to take multiple shots. Which is another reason to start taking +risks early.





+The best example of a field with superlinear returns is probably +science. It has exponential growth, in the form of learning, combined +with thresholds at the extreme edge of performance — literally at +the limits of knowledge.

The result has been a level of inequality in scientific discovery +that makes the wealth inequality of even the most stratified societies +seem mild by comparison. Newton's discoveries were arguably greater +than all his contemporaries' combined. +[11]

This point may seem obvious, but it might be just as well to spell +it out. Superlinear returns imply inequality. The steeper the return +curve, the greater the variation in outcomes.

In fact, the correlation between superlinear returns and inequality +is so strong that it yields another heuristic for finding work of +this type: look for fields where a few big winners outperform +everyone else. A kind of work where everyone does about the same +is unlikely to be one with superlinear returns.

What are fields where a few big winners outperform everyone else? +Here are some obvious ones: sports, politics, art, music, acting, +directing, writing, math, science, starting companies, and investing. +In sports the phenomenon is due to externally imposed thresholds; +you only need to be a few percent faster to win every race. In +politics, power grows much as it did in the days of emperors. And +in some of the other fields (including politics) success is driven +largely by fame, which has its own source of superlinear growth. +But when we exclude sports and politics and the effects of fame, a +remarkable pattern emerges: the remaining list is exactly the same +as the list of fields where you have to be independent-minded to +succeed — where your ideas have to be not just correct, but novel +as well. +[12]

This is obviously the case in science. You can't publish papers +saying things that other people have already said. But it's just +as true in investing, for example. It's only useful to believe that +a company will do well if most other investors don't; if everyone +else thinks the company will do well, then its stock price will +already reflect that, and there's no room to make money.

What else can we learn from these fields? In all of them you have +to put in the initial effort. Superlinear returns seem small at +first. At this rate, you find yourself thinking, I'll never get +anywhere. But because the reward curve rises so steeply at the far +end, it's worth taking extraordinary measures to get there.

In the startup world, the name for this principle is "do things +that don't scale." If you pay a ridiculous amount of attention to +your tiny initial set of customers, ideally you'll kick off exponential +growth by word of mouth. But this same principle applies to anything +that grows exponentially. Learning, for example. When you first +start learning something, you feel lost. But it's worth making the +initial effort to get a toehold, because the more you learn, the +easier it will get.

There's another more subtle lesson in the list of fields with +superlinear returns: not to equate work with a job. For most of the +20th century the two were identical for nearly everyone, and as a +result we've inherited a custom that equates productivity with +having a job. Even now to most people the phrase "your work" means +their job. But to a writer or artist or scientist it means whatever +they're currently studying or creating. For someone like that, their +work is something they carry with them from job to job, if they +have jobs at all. It may be done for an employer, but it's part of +their portfolio.





+It's an intimidating prospect to enter a field where a few big +winners outperform everyone else. Some people do this deliberately, +but you don't need to. If you have sufficient natural ability and +you follow your curiosity sufficiently far, you'll end up in one. +Your curiosity won't let you be interested in boring questions, and +interesting questions tend to create fields with superlinear returns +if they're not already part of one.

The territory of superlinear returns is by no means static. Indeed, +the most extreme returns come from expanding it. So while both +ambition and curiosity can get you into this territory, curiosity +may be the more powerful of the two. Ambition tends to make you +climb existing peaks, but if you stick close enough to an interesting +enough question, it may grow into a mountain beneath you.









Notes

There's a limit to how sharply you can distinguish between effort, +performance, and return, because they're not sharply distinguished +in fact. What counts as return to one person might be performance +to another. But though the borders of these concepts are blurry, +they're not meaningless. I've tried to write about them as precisely +as I could without crossing into error.

[1] +Evolution itself is probably the most pervasive example of +superlinear returns for performance. But this is hard for us to +empathize with because we're not the recipients; we're the returns.

[2] +Knowledge did of course have a practical effect before the +Industrial Revolution. The development of agriculture changed human +life completely. But this kind of change was the result of broad, +gradual improvements in technique, not the discoveries of a few +exceptionally learned people.

[3] +It's not mathematically correct to describe a step function as +superlinear, but a step function starting from zero works like a +superlinear function when it describes the reward curve for effort +by a rational actor. If it starts at zero then the part before the +step is below any linearly increasing return, and the part after +the step must be above the necessary return at that point or no one +would bother.

[4] +Seeking competition could be a good heuristic in the sense that +some people find it motivating. It's also somewhat of a guide to +promising problems, because it's a sign that other people find them +promising. But it's a very imperfect sign: often there's a clamoring +crowd chasing some problem, and they all end up being trumped by +someone quietly working on another one.

[5] +Not always, though. You have to be careful with this rule. When +something is popular despite being mediocre, there's often a hidden +reason why. Perhaps monopoly or regulation make it hard to compete. +Perhaps customers have bad taste or have broken procedures for +deciding what to buy. There are huge swathes of mediocre things +that exist for such reasons.

[6] +In my twenties I wanted to be an artist +and even went to art +school to study painting. Mostly because I liked art, but a nontrivial +part of my motivation came from the fact that artists seemed least +at the mercy of organizations.

[7] +In principle everyone is getting superlinear returns. Learning +compounds, and everyone learns in the course of their life. But in +practice few push this kind of everyday learning to the point where +the return curve gets really steep.

[8] +It's unclear exactly what advocates of "equity" mean by it. +They seem to disagree among themselves. But whatever they mean is +probably at odds with a world in which institutions have less power +to control outcomes, and a handful of outliers do much better than +everyone else.

It may seem like bad luck for this concept that it arose at just +the moment when the world was shifting in the opposite direction, +but I don't think this was a coincidence. I think one reason it +arose now is because its adherents feel threatened by rapidly +increasing variation in performance.

[9] +Corollary: Parents who pressure their kids to work on something +prestigious, like medicine, even though they have no interest in +it, will be hosing them even more than they have in the past.

[10] +The original version of this paragraph was the first draft of +"How to Do Great Work." +As soon as I wrote it I realized it was a more important topic than superlinear +returns, so I paused the present essay to expand this paragraph into its +own. Practically nothing remains of the original version, because +after I finished "How to Do Great Work" I rewrote it based on that.

[11] +Before the Industrial Revolution, people who got rich usually +did it like emperors: capturing some resource made them more powerful +and enabled them to capture more. Now it can be done like a scientist, +by discovering or building something uniquely valuable. Most people +who get rich use a mix of the old and the new ways, but in the most +advanced economies the ratio has shifted dramatically toward discovery +just in the last half century.

[12] +It's not surprising that conventional-minded people would +dislike inequality if independent-mindedness is one of the biggest +drivers of it. But it's not simply that they don't want anyone to +have what they can't. The conventional-minded literally can't imagine +what it's like to have novel ideas. So the whole phenomenon of great +variation in performance seems unnatural to them, and when they +encounter it they assume it must be due to cheating or to some +malign external influence.



Thanks +to Trevor Blackwell, Patrick Collusion, Tyler Cowen, +Jessica Livingston, Harj Taggar, and Garry Tan for reading drafts +of this.




+ + + + + + + + + + diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/html/what_is_haystack.html b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/html/what_is_haystack.html new file mode 100644 index 0000000000000000000000000000000000000000..2d62b206c0973b26933bd52d4e7534d81c853e10 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/html/what_is_haystack.html @@ -0,0 +1,1634 @@ + + + + + + + + + + What is Haystack? | Haystack + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ 🎃 We're participating in Hacktoberfest 2023! + + + + + +
+
+ + + +
+ +
+
+
+ + + + + +
+

What is Haystack?

+

Haystack is the open source Python framework by deepset for building custom apps with large language models (LLMs). It lets you quickly try out the latest models in natural language processing (NLP) while being flexible and easy to use. Our inspiring community of users and builders has helped shape Haystack into what it is today: a complete framework for building production-ready NLP apps.

+

Building with Haystack

+

Haystack offers comprehensive tooling for developing state-of-the-art NLP systems that use LLMs (such as GPT-4, Falcon and similar) and Transformer models . With Haystack, you can effortlessly experiment with various models hosted on platforms like Hugging Face, OpenAI, Cohere, or even models deployed on SageMaker and your local models to find the perfect fit for your use case.

+ + + + + + + + + + + + + + + + + + + + + Model Providers + + +

Some examples of what you can build include:

+
    +
  • Semantic search on a large collection of documents in any language
  • +
  • Generative question answering on a knowledge base containing mixed types of information: images, text, and tables.
  • +
  • Natural language chatbots powered by cutting-edge generative models like GPT-4
  • +
  • An LLM-based Haystack Agent capable of resolving complex queries
  • +
  • Information extraction from documents to populate your database or build a knowledge graph
  • +
+

This is just a small subset of the kinds of systems that can be created in Haystack.

+

Functionality for all stages of an NLP project

+

A successful NLP project requires more than just the language models. As an end-to-end framework, Haystack assists you in building your system every step of the way, offering tooling for each stage of the NLP project life cycle:

+ +

But that’s not all: +metadata filtering, +model distillation, or the prompt hub, whatever your NLP heart desires, you’re likely to find it in Haystack. And if not? We’ll build it together.

+ + + + + + + + + + + + + + + + + + + + + + + Rest API + + +

Building blocks

+

Haystack uses a few simple but effective concepts to help you build fully functional and customized end-to-end NLP systems.

+

Components

+

At the core of Haystack are its components—fundamental building blocks that can perform tasks like document retrieval, text generation, or summarization. A single component is already quite powerful. It can manage local language models or communicate with a hosted model through an API.

+

While Haystack offers a bunch of components you can use out of the box, it also lets you create your own custom components. Explore the +collection of integrations that includes custom components developed by our community, which you can freely use.

+

You can chain components together to build pipelines, which are the foundation of the NLP app architecture in Haystack.

+

Pipelines

+

Pipelines are powerful structures made up of components, such as a Retriever and Reader, connected to infrastructure building blocks, such as a DocumentStore (for example, Elasticsearch or Weaviate) to form complex systems.

+

Haystack offers ready-made pipelines for most common tasks, such as question answering, document retrieval, or summarization. But it’s just as easy to design and create a custom pipeline for NLP scenarios that are way more complex than question answering.

+

Agents

+

The Haystack Agent makes use of a large language model to resolve complex tasks. When initializing the Agent, you give it a set of tools, which can be pipeline components or whole pipelines. The Agent can use to those tools iteratively to arrive at an answer. When given a query, the Agent determines which tools are useful to answer this query and calls them in a loop until it gets the answer. This way, it can achieve much more than extractive or generative question answering pipelines.

+ + + + + + + + + + + + + + + + + + + + + Agent Tools + + +

Who’s it for?

+

Haystack is for everyone looking to build natural language apps—NLP enthusiasts and newbies alike. You don’t need to understand how the models work under the hood. With Haystack’s modular and flexible components, pipelines, and agents, all you need is some basic knowledge of Python to dive right in.

+

Our community

+

At the heart of Haystack is the vibrant open source community that thrives on the diverse backgrounds and skill sets of its members. We value collaboration greatly and encourage our users to shape Haystack actively through GitHub contributions. Our Discord channel is a space where community members can connect, seek help, and learn from each other.

+

We also organize live online and in-person events, webinars, and office hours, which are an opportunity to learn and grow.

+ + + + + + + + +
+ + + +
+ Join Discord +
+ + + +
+
+ +

Enter the Haystack universe

+ + + + +
+ + + +
+ +
+
+
+
+
+ + + + + + + + + + + + + + + +
+
+
+ +
+ + + +
+ + + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/azure_sample_pdf_1.json b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/azure_sample_pdf_1.json new file mode 100644 index 0000000000000000000000000000000000000000..6077486becb4c6b517878ce5db1d0cb353175e38 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/azure_sample_pdf_1.json @@ -0,0 +1,9623 @@ +{ + "api_version": "2023-02-28-preview", + "model_id": "prebuilt-document", + "content": "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.\nColumn 1\nColumn 2\nColumn 3\nA\n324\n55 million units\n2022\nB\n234,523.00\nThe quick brown fox jumped over the lazy dog.\n54x growth\nC\n23.53%\nA short string.\nD\n$54.35\n$6345.\nPage 2 of Sample PDF\n\nPage 4 of Sample PDF\n... the page 3 is empty.", + "languages": [], + "pages": [ + { + "page_number": 1, + "angle": null, + "width": 8.2639, + "height": 11.6806, + "unit": "inch", + "lines": [ + { + "content": "A sample PDF file", + "polygon": [ + { + "x": 0.7605, + "y": 0.8365 + }, + { + "x": 3.5895, + "y": 0.8314 + }, + { + "x": 3.5945, + "y": 1.166 + }, + { + "x": 0.7605, + "y": 1.1914 + } + ], + "spans": [ + { + "offset": 0, + "length": 17 + } + ] + }, + { + "content": "History and standardization", + "polygon": [ + { + "x": 0.7706, + "y": 1.7136 + }, + { + "x": 3.1433, + "y": 1.7136 + }, + { + "x": 3.1433, + "y": 1.9214 + }, + { + "x": 0.7706, + "y": 1.9316 + } + ], + "spans": [ + { + "offset": 18, + "length": 27 + } + ] + }, + { + "content": "Format (PDF) Adobe Systems made the PDF specification available free of", + "polygon": [ + { + "x": 0.7808, + "y": 2.18 + }, + { + "x": 7.255, + "y": 2.18 + }, + { + "x": 7.255, + "y": 2.3929 + }, + { + "x": 0.7808, + "y": 2.3929 + } + ], + "spans": [ + { + "offset": 46, + "length": 71 + } + ] + }, + { + "content": "charge in 1993. In the early years PDF was popular mainly in desktop", + "polygon": [ + { + "x": 0.7706, + "y": 2.4132 + }, + { + "x": 6.7733, + "y": 2.4132 + }, + { + "x": 6.7733, + "y": 2.6362 + }, + { + "x": 0.7706, + "y": 2.6312 + } + ], + "spans": [ + { + "offset": 118, + "length": 68 + } + ] + }, + { + "content": "publishing workflows, and competed with a variety of formats such as DjVu,", + "polygon": [ + { + "x": 0.7706, + "y": 2.6565 + }, + { + "x": 7.2601, + "y": 2.6565 + }, + { + "x": 7.2601, + "y": 2.8694 + }, + { + "x": 0.7706, + "y": 2.8745 + } + ], + "spans": [ + { + "offset": 187, + "length": 74 + } + ] + }, + { + "content": "Envoy, Common Ground Digital Paper, Farallon Replica and even Adobe's", + "polygon": [ + { + "x": 0.7656, + "y": 2.8897 + }, + { + "x": 7.1789, + "y": 2.8897 + }, + { + "x": 7.1789, + "y": 3.1077 + }, + { + "x": 0.7656, + "y": 3.1077 + } + ], + "spans": [ + { + "offset": 262, + "length": 69 + } + ] + }, + { + "content": "own PostScript format. PDF was a proprietary format controlled by Adobe", + "polygon": [ + { + "x": 0.7706, + "y": 3.128 + }, + { + "x": 7.0978, + "y": 3.1331 + }, + { + "x": 7.0978, + "y": 3.3409 + }, + { + "x": 0.7706, + "y": 3.3409 + } + ], + "spans": [ + { + "offset": 332, + "length": 71 + } + ] + }, + { + "content": "until it was released as an open standard on July 1, 2008, and published by", + "polygon": [ + { + "x": 0.7858, + "y": 3.3663 + }, + { + "x": 7.2702, + "y": 3.3713 + }, + { + "x": 7.2702, + "y": 3.5792 + }, + { + "x": 0.7808, + "y": 3.5691 + } + ], + "spans": [ + { + "offset": 404, + "length": 75 + } + ] + }, + { + "content": "the International Organization for Standardization as ISO 32000-1:2008, at", + "polygon": [ + { + "x": 0.7656, + "y": 3.5995 + }, + { + "x": 7.2043, + "y": 3.5944 + }, + { + "x": 7.2043, + "y": 3.8023 + }, + { + "x": 0.7656, + "y": 3.8023 + } + ], + "spans": [ + { + "offset": 480, + "length": 74 + } + ] + }, + { + "content": "which time control of the specification passed to an ISO Committee of", + "polygon": [ + { + "x": 0.7757, + "y": 3.8327 + }, + { + "x": 6.7784, + "y": 3.8327 + }, + { + "x": 6.7784, + "y": 4.0355 + }, + { + "x": 0.7757, + "y": 4.0456 + } + ], + "spans": [ + { + "offset": 555, + "length": 69 + } + ] + }, + { + "content": "volunteer industry experts. In 2008, Adobe published a Public Patent License", + "polygon": [ + { + "x": 0.7656, + "y": 4.071 + }, + { + "x": 7.402, + "y": 4.0659 + }, + { + "x": 7.402, + "y": 4.2737 + }, + { + "x": 0.7706, + "y": 4.2839 + } + ], + "spans": [ + { + "offset": 625, + "length": 76 + } + ] + }, + { + "content": "to ISO 32000-1 granting royalty-free rights for all patents owned by Adobe", + "polygon": [ + { + "x": 0.7808, + "y": 4.3092 + }, + { + "x": 7.1232, + "y": 4.3092 + }, + { + "x": 7.1232, + "y": 4.5272 + }, + { + "x": 0.7808, + "y": 4.5222 + } + ], + "spans": [ + { + "offset": 702, + "length": 74 + } + ] + }, + { + "content": "that are necessary to make, use, sell, and distribute PDF-compliant", + "polygon": [ + { + "x": 0.7605, + "y": 4.5475 + }, + { + "x": 6.5655, + "y": 4.5475 + }, + { + "x": 6.5655, + "y": 4.7554 + }, + { + "x": 0.7605, + "y": 4.7604 + } + ], + "spans": [ + { + "offset": 777, + "length": 67 + } + ] + }, + { + "content": "implementations. PDF 1.7, the sixth edition of the PDF specification that", + "polygon": [ + { + "x": 0.7656, + "y": 4.7807 + }, + { + "x": 6.9761, + "y": 4.7807 + }, + { + "x": 6.9761, + "y": 4.9886 + }, + { + "x": 0.7656, + "y": 4.9886 + } + ], + "spans": [ + { + "offset": 845, + "length": 73 + } + ] + }, + { + "content": "became ISO 32000-1, includes some proprietary technologies defined only by", + "polygon": [ + { + "x": 0.7706, + "y": 5.0139 + }, + { + "x": 7.4781, + "y": 5.019 + }, + { + "x": 7.4781, + "y": 5.2319 + }, + { + "x": 0.7706, + "y": 5.2167 + } + ], + "spans": [ + { + "offset": 919, + "length": 74 + } + ] + }, + { + "content": "Adobe, such as Adobe XML Forms Architecture (XFA) and JavaScript", + "polygon": [ + { + "x": 0.7757, + "y": 5.2522 + }, + { + "x": 6.7683, + "y": 5.2522 + }, + { + "x": 6.7683, + "y": 5.4651 + }, + { + "x": 0.7757, + "y": 5.455 + } + ], + "spans": [ + { + "offset": 994, + "length": 64 + } + ] + }, + { + "content": "extension for Acrobat, which are referenced by ISO 32000-1 as normative", + "polygon": [ + { + "x": 0.7656, + "y": 5.4854 + }, + { + "x": 7.113, + "y": 5.4854 + }, + { + "x": 7.113, + "y": 5.6882 + }, + { + "x": 0.7656, + "y": 5.6882 + } + ], + "spans": [ + { + "offset": 1059, + "length": 71 + } + ] + }, + { + "content": "and indispensable for the full implementation of the ISO 32000-1", + "polygon": [ + { + "x": 0.7656, + "y": 5.7287 + }, + { + "x": 6.3221, + "y": 5.7237 + }, + { + "x": 6.3221, + "y": 5.9265 + }, + { + "x": 0.7656, + "y": 5.9366 + } + ], + "spans": [ + { + "offset": 1131, + "length": 64 + } + ] + }, + { + "content": "specification. These proprietary technologies are not standardized and their", + "polygon": [ + { + "x": 0.7858, + "y": 5.967 + }, + { + "x": 7.2702, + "y": 5.962 + }, + { + "x": 7.2702, + "y": 6.1647 + }, + { + "x": 0.7858, + "y": 6.1799 + } + ], + "spans": [ + { + "offset": 1196, + "length": 76 + } + ] + }, + { + "content": "specification is published only on Adobe's website. Many of them are also not", + "polygon": [ + { + "x": 0.7656, + "y": 6.2002 + }, + { + "x": 7.4324, + "y": 6.1952 + }, + { + "x": 7.4324, + "y": 6.403 + }, + { + "x": 0.7656, + "y": 6.4081 + } + ], + "spans": [ + { + "offset": 1273, + "length": 77 + } + ] + }, + { + "content": "supported by popular third-party implementations of PDF.", + "polygon": [ + { + "x": 0.7605, + "y": 6.4385 + }, + { + "x": 5.6985, + "y": 6.4284 + }, + { + "x": 5.6985, + "y": 6.6362 + }, + { + "x": 0.7605, + "y": 6.6514 + } + ], + "spans": [ + { + "offset": 1351, + "length": 56 + } + ] + }, + { + "content": "Column 1", + "polygon": [ + { + "x": 2.5045, + "y": 7.1229 + }, + { + "x": 3.1433, + "y": 7.1229 + }, + { + "x": 3.1433, + "y": 7.2649 + }, + { + "x": 2.5045, + "y": 7.2649 + } + ], + "spans": [ + { + "offset": 1408, + "length": 8 + } + ] + }, + { + "content": "Column 2", + "polygon": [ + { + "x": 4.1776, + "y": 7.1229 + }, + { + "x": 4.8214, + "y": 7.128 + }, + { + "x": 4.8214, + "y": 7.2699 + }, + { + "x": 4.1776, + "y": 7.2649 + } + ], + "spans": [ + { + "offset": 1417, + "length": 8 + } + ] + }, + { + "content": "Column 3", + "polygon": [ + { + "x": 5.8304, + "y": 7.1128 + }, + { + "x": 6.5097, + "y": 7.1128 + }, + { + "x": 6.5097, + "y": 7.2801 + }, + { + "x": 5.8304, + "y": 7.2801 + } + ], + "spans": [ + { + "offset": 1426, + "length": 8 + } + ] + }, + { + "content": "A", + "polygon": [ + { + "x": 0.8365, + "y": 7.4575 + }, + { + "x": 0.9329, + "y": 7.4524 + }, + { + "x": 0.9379, + "y": 7.5741 + }, + { + "x": 0.8365, + "y": 7.5741 + } + ], + "spans": [ + { + "offset": 1435, + "length": 1 + } + ] + }, + { + "content": "324", + "polygon": [ + { + "x": 3.8176, + "y": 7.4474 + }, + { + "x": 4.0965, + "y": 7.4423 + }, + { + "x": 4.0965, + "y": 7.5843 + }, + { + "x": 3.8227, + "y": 7.5893 + } + ], + "spans": [ + { + "offset": 1437, + "length": 3 + } + ] + }, + { + "content": "55 million units", + "polygon": [ + { + "x": 4.1674, + "y": 7.4423 + }, + { + "x": 5.1206, + "y": 7.4423 + }, + { + "x": 5.1206, + "y": 7.5944 + }, + { + "x": 4.1674, + "y": 7.5893 + } + ], + "spans": [ + { + "offset": 1441, + "length": 16 + } + ] + }, + { + "content": "2022", + "polygon": [ + { + "x": 7.0877, + "y": 7.4524 + }, + { + "x": 7.4122, + "y": 7.4575 + }, + { + "x": 7.4172, + "y": 7.5792 + }, + { + "x": 7.0927, + "y": 7.5792 + } + ], + "spans": [ + { + "offset": 1458, + "length": 4 + } + ] + }, + { + "content": "B", + "polygon": [ + { + "x": 0.8416, + "y": 7.7668 + }, + { + "x": 0.943, + "y": 7.7668 + }, + { + "x": 0.943, + "y": 7.8884 + }, + { + "x": 0.8416, + "y": 7.8834 + } + ], + "spans": [ + { + "offset": 1463, + "length": 1 + } + ] + }, + { + "content": "234,523.00", + "polygon": [ + { + "x": 2.4944, + "y": 7.7617 + }, + { + "x": 3.2194, + "y": 7.7617 + }, + { + "x": 3.2194, + "y": 7.9036 + }, + { + "x": 2.4944, + "y": 7.9036 + } + ], + "spans": [ + { + "offset": 1465, + "length": 10 + } + ] + }, + { + "content": "The quick brown fox", + "polygon": [ + { + "x": 4.1674, + "y": 7.7515 + }, + { + "x": 5.4704, + "y": 7.7515 + }, + { + "x": 5.4704, + "y": 7.9138 + }, + { + "x": 4.1674, + "y": 7.9087 + } + ], + "spans": [ + { + "offset": 1476, + "length": 19 + } + ] + }, + { + "content": "jumped over the lazy", + "polygon": [ + { + "x": 4.1674, + "y": 7.9341 + }, + { + "x": 5.4755, + "y": 7.929 + }, + { + "x": 5.4755, + "y": 8.0861 + }, + { + "x": 4.1674, + "y": 8.0861 + } + ], + "spans": [ + { + "offset": 1496, + "length": 20 + } + ] + }, + { + "content": "dog.", + "polygon": [ + { + "x": 4.1725, + "y": 8.1014 + }, + { + "x": 4.4615, + "y": 8.1014 + }, + { + "x": 4.4666, + "y": 8.2433 + }, + { + "x": 4.1725, + "y": 8.2382 + } + ], + "spans": [ + { + "offset": 1517, + "length": 4 + } + ] + }, + { + "content": "54x growth", + "polygon": [ + { + "x": 5.8456, + "y": 7.7617 + }, + { + "x": 6.5604, + "y": 7.7617 + }, + { + "x": 6.5604, + "y": 7.9138 + }, + { + "x": 5.8456, + "y": 7.9138 + } + ], + "spans": [ + { + "offset": 1522, + "length": 10 + } + ] + }, + { + "content": "C", + "polygon": [ + { + "x": 0.8416, + "y": 8.365 + }, + { + "x": 0.9481, + "y": 8.365 + }, + { + "x": 0.9481, + "y": 8.5069 + }, + { + "x": 0.8467, + "y": 8.5019 + } + ], + "spans": [ + { + "offset": 1533, + "length": 1 + } + ] + }, + { + "content": "23.53%", + "polygon": [ + { + "x": 2.4944, + "y": 8.3447 + }, + { + "x": 2.9963, + "y": 8.3396 + }, + { + "x": 3.0014, + "y": 8.5171 + }, + { + "x": 2.4893, + "y": 8.5171 + } + ], + "spans": [ + { + "offset": 1535, + "length": 6 + } + ] + }, + { + "content": "A short string.", + "polygon": [ + { + "x": 4.1674, + "y": 8.3701 + }, + { + "x": 5.0597, + "y": 8.3751 + }, + { + "x": 5.0597, + "y": 8.5272 + }, + { + "x": 4.1674, + "y": 8.5221 + } + ], + "spans": [ + { + "offset": 1542, + "length": 15 + } + ] + }, + { + "content": "D", + "polygon": [ + { + "x": 0.8416, + "y": 8.6945 + }, + { + "x": 0.9481, + "y": 8.6945 + }, + { + "x": 0.9481, + "y": 8.8213 + }, + { + "x": 0.8416, + "y": 8.8162 + } + ], + "spans": [ + { + "offset": 1558, + "length": 1 + } + ] + }, + { + "content": "$54.35", + "polygon": [ + { + "x": 2.4944, + "y": 8.6894 + }, + { + "x": 2.9456, + "y": 8.6844 + }, + { + "x": 2.9456, + "y": 8.8263 + }, + { + "x": 2.4944, + "y": 8.8263 + } + ], + "spans": [ + { + "offset": 1560, + "length": 6 + } + ] + }, + { + "content": "$6345.", + "polygon": [ + { + "x": 4.1624, + "y": 8.6894 + }, + { + "x": 4.6136, + "y": 8.6945 + }, + { + "x": 4.6136, + "y": 8.8365 + }, + { + "x": 4.1624, + "y": 8.8263 + } + ], + "spans": [ + { + "offset": 1567, + "length": 6 + } + ] + } + ], + "words": [ + { + "content": "A", + "polygon": [ + { + "x": 0.7858, + "y": 0.8416 + }, + { + "x": 0.9582, + "y": 0.8365 + }, + { + "x": 0.9531, + "y": 1.1863 + }, + { + "x": 0.7808, + "y": 1.1812 + } + ], + "span": { + "offset": 0, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "sample", + "polygon": [ + { + "x": 1.1103, + "y": 0.8365 + }, + { + "x": 2.251, + "y": 0.8365 + }, + { + "x": 2.251, + "y": 1.1863 + }, + { + "x": 1.1103, + "y": 1.1914 + } + ], + "span": { + "offset": 2, + "length": 6 + }, + "confidence": 0.993 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 2.3626, + "y": 0.8365 + }, + { + "x": 2.9963, + "y": 0.8416 + }, + { + "x": 3.0014, + "y": 1.161 + }, + { + "x": 2.3626, + "y": 1.1812 + } + ], + "span": { + "offset": 9, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "file", + "polygon": [ + { + "x": 3.1078, + "y": 0.8416 + }, + { + "x": 3.5895, + "y": 0.8416 + }, + { + "x": 3.5945, + "y": 1.1255 + }, + { + "x": 3.1078, + "y": 1.1559 + } + ], + "span": { + "offset": 13, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "History", + "polygon": [ + { + "x": 0.7808, + "y": 1.7186 + }, + { + "x": 1.3993, + "y": 1.7136 + }, + { + "x": 1.3993, + "y": 1.9316 + }, + { + "x": 0.7757, + "y": 1.9316 + } + ], + "span": { + "offset": 18, + "length": 7 + }, + "confidence": 0.995 + }, + { + "content": "and", + "polygon": [ + { + "x": 1.4449, + "y": 1.7136 + }, + { + "x": 1.7592, + "y": 1.7136 + }, + { + "x": 1.7592, + "y": 1.9316 + }, + { + "x": 1.4398, + "y": 1.9316 + } + ], + "span": { + "offset": 26, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "standardization", + "polygon": [ + { + "x": 1.815, + "y": 1.7136 + }, + { + "x": 3.123, + "y": 1.7186 + }, + { + "x": 3.123, + "y": 1.9113 + }, + { + "x": 1.815, + "y": 1.9316 + } + ], + "span": { + "offset": 30, + "length": 15 + }, + "confidence": 0.991 + }, + { + "content": "Format", + "polygon": [ + { + "x": 0.7808, + "y": 2.185 + }, + { + "x": 1.3942, + "y": 2.185 + }, + { + "x": 1.3942, + "y": 2.398 + }, + { + "x": 0.7858, + "y": 2.3929 + } + ], + "span": { + "offset": 46, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "(PDF)", + "polygon": [ + { + "x": 1.4348, + "y": 2.185 + }, + { + "x": 1.9772, + "y": 2.185 + }, + { + "x": 1.9772, + "y": 2.398 + }, + { + "x": 1.4348, + "y": 2.398 + } + ], + "span": { + "offset": 53, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "Adobe", + "polygon": [ + { + "x": 2.0178, + "y": 2.185 + }, + { + "x": 2.5603, + "y": 2.185 + }, + { + "x": 2.5654, + "y": 2.398 + }, + { + "x": 2.0229, + "y": 2.398 + } + ], + "span": { + "offset": 59, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "Systems", + "polygon": [ + { + "x": 2.6313, + "y": 2.185 + }, + { + "x": 3.3715, + "y": 2.185 + }, + { + "x": 3.3715, + "y": 2.398 + }, + { + "x": 2.6313, + "y": 2.398 + } + ], + "span": { + "offset": 65, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "made", + "polygon": [ + { + "x": 3.412, + "y": 2.185 + }, + { + "x": 3.9139, + "y": 2.185 + }, + { + "x": 3.9139, + "y": 2.398 + }, + { + "x": 3.412, + "y": 2.398 + } + ], + "span": { + "offset": 73, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "the", + "polygon": [ + { + "x": 3.9545, + "y": 2.185 + }, + { + "x": 4.2333, + "y": 2.185 + }, + { + "x": 4.2333, + "y": 2.398 + }, + { + "x": 3.9545, + "y": 2.398 + } + ], + "span": { + "offset": 78, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 4.2891, + "y": 2.185 + }, + { + "x": 4.6643, + "y": 2.185 + }, + { + "x": 4.6643, + "y": 2.398 + }, + { + "x": 4.2891, + "y": 2.398 + } + ], + "span": { + "offset": 82, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "specification", + "polygon": [ + { + "x": 4.7353, + "y": 2.185 + }, + { + "x": 5.7949, + "y": 2.185 + }, + { + "x": 5.7949, + "y": 2.398 + }, + { + "x": 4.7353, + "y": 2.398 + } + ], + "span": { + "offset": 86, + "length": 13 + }, + "confidence": 0.97 + }, + { + "content": "available", + "polygon": [ + { + "x": 5.8608, + "y": 2.185 + }, + { + "x": 6.6314, + "y": 2.185 + }, + { + "x": 6.6314, + "y": 2.3929 + }, + { + "x": 5.8658, + "y": 2.398 + } + ], + "span": { + "offset": 100, + "length": 9 + }, + "confidence": 0.986 + }, + { + "content": "free", + "polygon": [ + { + "x": 6.672, + "y": 2.185 + }, + { + "x": 7.0167, + "y": 2.185 + }, + { + "x": 7.0218, + "y": 2.3929 + }, + { + "x": 6.672, + "y": 2.3929 + } + ], + "span": { + "offset": 110, + "length": 4 + }, + "confidence": 0.992 + }, + { + "content": "of", + "polygon": [ + { + "x": 7.0623, + "y": 2.185 + }, + { + "x": 7.2601, + "y": 2.185 + }, + { + "x": 7.2601, + "y": 2.3929 + }, + { + "x": 7.0623, + "y": 2.3929 + } + ], + "span": { + "offset": 115, + "length": 2 + }, + "confidence": 0.993 + }, + { + "content": "charge", + "polygon": [ + { + "x": 0.7706, + "y": 2.4233 + }, + { + "x": 1.3638, + "y": 2.4233 + }, + { + "x": 1.3638, + "y": 2.6362 + }, + { + "x": 0.7706, + "y": 2.6362 + } + ], + "span": { + "offset": 118, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "in", + "polygon": [ + { + "x": 1.4044, + "y": 2.4233 + }, + { + "x": 1.5615, + "y": 2.4182 + }, + { + "x": 1.5615, + "y": 2.6362 + }, + { + "x": 1.4044, + "y": 2.6362 + } + ], + "span": { + "offset": 125, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "1993.", + "polygon": [ + { + "x": 1.6477, + "y": 2.4182 + }, + { + "x": 2.1141, + "y": 2.4182 + }, + { + "x": 2.1141, + "y": 2.6362 + }, + { + "x": 1.6477, + "y": 2.6362 + } + ], + "span": { + "offset": 128, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "In", + "polygon": [ + { + "x": 2.1598, + "y": 2.4182 + }, + { + "x": 2.3271, + "y": 2.4182 + }, + { + "x": 2.3271, + "y": 2.6362 + }, + { + "x": 2.1598, + "y": 2.6362 + } + ], + "span": { + "offset": 134, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "the", + "polygon": [ + { + "x": 2.3727, + "y": 2.4182 + }, + { + "x": 2.6566, + "y": 2.4182 + }, + { + "x": 2.6566, + "y": 2.6362 + }, + { + "x": 2.3727, + "y": 2.6362 + } + ], + "span": { + "offset": 137, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "early", + "polygon": [ + { + "x": 2.7124, + "y": 2.4182 + }, + { + "x": 3.1383, + "y": 2.4182 + }, + { + "x": 3.1383, + "y": 2.6362 + }, + { + "x": 2.7124, + "y": 2.6362 + } + ], + "span": { + "offset": 141, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "years", + "polygon": [ + { + "x": 3.1788, + "y": 2.4182 + }, + { + "x": 3.6604, + "y": 2.4182 + }, + { + "x": 3.6655, + "y": 2.6362 + }, + { + "x": 3.1788, + "y": 2.6362 + } + ], + "span": { + "offset": 147, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 3.7061, + "y": 2.4182 + }, + { + "x": 4.1015, + "y": 2.4182 + }, + { + "x": 4.1015, + "y": 2.6362 + }, + { + "x": 3.7061, + "y": 2.6362 + } + ], + "span": { + "offset": 153, + "length": 3 + }, + "confidence": 0.992 + }, + { + "content": "was", + "polygon": [ + { + "x": 4.1421, + "y": 2.4182 + }, + { + "x": 4.5122, + "y": 2.4182 + }, + { + "x": 4.5173, + "y": 2.6362 + }, + { + "x": 4.1472, + "y": 2.6362 + } + ], + "span": { + "offset": 157, + "length": 3 + }, + "confidence": 0.979 + }, + { + "content": "popular", + "polygon": [ + { + "x": 4.5527, + "y": 2.4182 + }, + { + "x": 5.2068, + "y": 2.4182 + }, + { + "x": 5.2118, + "y": 2.6362 + }, + { + "x": 4.5578, + "y": 2.6362 + } + ], + "span": { + "offset": 161, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "mainly", + "polygon": [ + { + "x": 5.2524, + "y": 2.4182 + }, + { + "x": 5.8151, + "y": 2.4233 + }, + { + "x": 5.8202, + "y": 2.6362 + }, + { + "x": 5.2524, + "y": 2.6362 + } + ], + "span": { + "offset": 169, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "in", + "polygon": [ + { + "x": 5.8608, + "y": 2.4233 + }, + { + "x": 6.0281, + "y": 2.4233 + }, + { + "x": 6.0331, + "y": 2.6362 + }, + { + "x": 5.8658, + "y": 2.6362 + } + ], + "span": { + "offset": 176, + "length": 2 + }, + "confidence": 0.997 + }, + { + "content": "desktop", + "polygon": [ + { + "x": 6.0737, + "y": 2.4233 + }, + { + "x": 6.7683, + "y": 2.4284 + }, + { + "x": 6.7733, + "y": 2.6362 + }, + { + "x": 6.0788, + "y": 2.6362 + } + ], + "span": { + "offset": 179, + "length": 7 + }, + "confidence": 0.995 + }, + { + "content": "publishing", + "polygon": [ + { + "x": 0.7706, + "y": 2.6616 + }, + { + "x": 1.6578, + "y": 2.6616 + }, + { + "x": 1.6578, + "y": 2.8745 + }, + { + "x": 0.7706, + "y": 2.8796 + } + ], + "span": { + "offset": 187, + "length": 10 + }, + "confidence": 0.991 + }, + { + "content": "workflows,", + "polygon": [ + { + "x": 1.6984, + "y": 2.6616 + }, + { + "x": 2.6313, + "y": 2.6616 + }, + { + "x": 2.6313, + "y": 2.8745 + }, + { + "x": 1.6984, + "y": 2.8745 + } + ], + "span": { + "offset": 198, + "length": 10 + }, + "confidence": 0.993 + }, + { + "content": "and", + "polygon": [ + { + "x": 2.6718, + "y": 2.6616 + }, + { + "x": 2.9963, + "y": 2.6616 + }, + { + "x": 2.9963, + "y": 2.8745 + }, + { + "x": 2.6718, + "y": 2.8745 + } + ], + "span": { + "offset": 209, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "competed", + "polygon": [ + { + "x": 3.0369, + "y": 2.6616 + }, + { + "x": 3.8987, + "y": 2.6616 + }, + { + "x": 3.8987, + "y": 2.8745 + }, + { + "x": 3.0369, + "y": 2.8745 + } + ], + "span": { + "offset": 213, + "length": 8 + }, + "confidence": 0.994 + }, + { + "content": "with", + "polygon": [ + { + "x": 3.9393, + "y": 2.6616 + }, + { + "x": 4.2942, + "y": 2.6616 + }, + { + "x": 4.2942, + "y": 2.8745 + }, + { + "x": 3.9393, + "y": 2.8745 + } + ], + "span": { + "offset": 222, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "a", + "polygon": [ + { + "x": 4.3652, + "y": 2.6616 + }, + { + "x": 4.4767, + "y": 2.6616 + }, + { + "x": 4.4767, + "y": 2.8745 + }, + { + "x": 4.3652, + "y": 2.8745 + } + ], + "span": { + "offset": 227, + "length": 1 + }, + "confidence": 0.992 + }, + { + "content": "variety", + "polygon": [ + { + "x": 4.5173, + "y": 2.6565 + }, + { + "x": 5.0952, + "y": 2.6565 + }, + { + "x": 5.0952, + "y": 2.8745 + }, + { + "x": 4.5173, + "y": 2.8745 + } + ], + "span": { + "offset": 229, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "of", + "polygon": [ + { + "x": 5.1408, + "y": 2.6565 + }, + { + "x": 5.3082, + "y": 2.6565 + }, + { + "x": 5.3082, + "y": 2.8745 + }, + { + "x": 5.1408, + "y": 2.8745 + } + ], + "span": { + "offset": 237, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "formats", + "polygon": [ + { + "x": 5.3487, + "y": 2.6565 + }, + { + "x": 6.0129, + "y": 2.6565 + }, + { + "x": 6.0129, + "y": 2.8745 + }, + { + "x": 5.3487, + "y": 2.8745 + } + ], + "span": { + "offset": 240, + "length": 7 + }, + "confidence": 0.993 + }, + { + "content": "such", + "polygon": [ + { + "x": 6.0534, + "y": 2.6565 + }, + { + "x": 6.4641, + "y": 2.6565 + }, + { + "x": 6.4641, + "y": 2.8745 + }, + { + "x": 6.0534, + "y": 2.8745 + } + ], + "span": { + "offset": 248, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "as", + "polygon": [ + { + "x": 6.5351, + "y": 2.6565 + }, + { + "x": 6.748, + "y": 2.6565 + }, + { + "x": 6.748, + "y": 2.8745 + }, + { + "x": 6.5351, + "y": 2.8745 + } + ], + "span": { + "offset": 253, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "DjVu,", + "polygon": [ + { + "x": 6.7886, + "y": 2.6565 + }, + { + "x": 7.255, + "y": 2.6565 + }, + { + "x": 7.255, + "y": 2.8745 + }, + { + "x": 6.7886, + "y": 2.8745 + } + ], + "span": { + "offset": 256, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "Envoy,", + "polygon": [ + { + "x": 0.7757, + "y": 2.8948 + }, + { + "x": 1.3638, + "y": 2.8948 + }, + { + "x": 1.3587, + "y": 3.1077 + }, + { + "x": 0.7706, + "y": 3.1077 + } + ], + "span": { + "offset": 262, + "length": 6 + }, + "confidence": 0.993 + }, + { + "content": "Common", + "polygon": [ + { + "x": 1.4044, + "y": 2.8948 + }, + { + "x": 2.1953, + "y": 2.8948 + }, + { + "x": 2.1902, + "y": 3.1128 + }, + { + "x": 1.3993, + "y": 3.1077 + } + ], + "span": { + "offset": 269, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "Ground", + "polygon": [ + { + "x": 2.251, + "y": 2.8948 + }, + { + "x": 2.9, + "y": 2.8948 + }, + { + "x": 2.8949, + "y": 3.1128 + }, + { + "x": 2.246, + "y": 3.1128 + } + ], + "span": { + "offset": 276, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "Digital", + "polygon": [ + { + "x": 2.9557, + "y": 2.8948 + }, + { + "x": 3.5084, + "y": 2.8948 + }, + { + "x": 3.5033, + "y": 3.1128 + }, + { + "x": 2.9557, + "y": 3.1128 + } + ], + "span": { + "offset": 283, + "length": 7 + }, + "confidence": 0.993 + }, + { + "content": "Paper,", + "polygon": [ + { + "x": 3.5489, + "y": 2.8948 + }, + { + "x": 4.1117, + "y": 2.8948 + }, + { + "x": 4.1117, + "y": 3.1128 + }, + { + "x": 3.5489, + "y": 3.1128 + } + ], + "span": { + "offset": 291, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "Farallon", + "polygon": [ + { + "x": 4.1573, + "y": 2.8948 + }, + { + "x": 4.862, + "y": 2.8948 + }, + { + "x": 4.8569, + "y": 3.1128 + }, + { + "x": 4.1522, + "y": 3.1128 + } + ], + "span": { + "offset": 298, + "length": 8 + }, + "confidence": 0.979 + }, + { + "content": "Replica", + "polygon": [ + { + "x": 4.9178, + "y": 2.8948 + }, + { + "x": 5.5819, + "y": 2.8948 + }, + { + "x": 5.5769, + "y": 3.1128 + }, + { + "x": 4.9178, + "y": 3.1128 + } + ], + "span": { + "offset": 307, + "length": 7 + }, + "confidence": 0.989 + }, + { + "content": "and", + "polygon": [ + { + "x": 5.6225, + "y": 2.8948 + }, + { + "x": 5.947, + "y": 2.8948 + }, + { + "x": 5.947, + "y": 3.1077 + }, + { + "x": 5.6225, + "y": 3.1128 + } + ], + "span": { + "offset": 315, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "even", + "polygon": [ + { + "x": 6.0027, + "y": 2.8948 + }, + { + "x": 6.4286, + "y": 2.8948 + }, + { + "x": 6.4235, + "y": 3.1077 + }, + { + "x": 6.0027, + "y": 3.1077 + } + ], + "span": { + "offset": 319, + "length": 4 + }, + "confidence": 0.924 + }, + { + "content": "Adobe's", + "polygon": [ + { + "x": 6.4692, + "y": 2.8948 + }, + { + "x": 7.1789, + "y": 2.8999 + }, + { + "x": 7.1789, + "y": 3.1026 + }, + { + "x": 6.4692, + "y": 3.1077 + } + ], + "span": { + "offset": 324, + "length": 7 + }, + "confidence": 0.961 + }, + { + "content": "own", + "polygon": [ + { + "x": 0.7706, + "y": 3.1331 + }, + { + "x": 1.1154, + "y": 3.1331 + }, + { + "x": 1.1204, + "y": 3.3359 + }, + { + "x": 0.7808, + "y": 3.3308 + } + ], + "span": { + "offset": 332, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "PostScript", + "polygon": [ + { + "x": 1.1813, + "y": 3.1331 + }, + { + "x": 2.0736, + "y": 3.1331 + }, + { + "x": 2.0786, + "y": 3.3409 + }, + { + "x": 1.1863, + "y": 3.3359 + } + ], + "span": { + "offset": 336, + "length": 10 + }, + "confidence": 0.99 + }, + { + "content": "format.", + "polygon": [ + { + "x": 2.1141, + "y": 3.1331 + }, + { + "x": 2.7327, + "y": 3.1331 + }, + { + "x": 2.7377, + "y": 3.346 + }, + { + "x": 2.1192, + "y": 3.3409 + } + ], + "span": { + "offset": 347, + "length": 7 + }, + "confidence": 0.992 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 2.7783, + "y": 3.1331 + }, + { + "x": 3.1585, + "y": 3.1331 + }, + { + "x": 3.1636, + "y": 3.346 + }, + { + "x": 2.7783, + "y": 3.346 + } + ], + "span": { + "offset": 355, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "was", + "polygon": [ + { + "x": 3.2143, + "y": 3.1331 + }, + { + "x": 3.5844, + "y": 3.1331 + }, + { + "x": 3.5895, + "y": 3.346 + }, + { + "x": 3.2194, + "y": 3.346 + } + ], + "span": { + "offset": 359, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "a", + "polygon": [ + { + "x": 3.63, + "y": 3.1331 + }, + { + "x": 3.7365, + "y": 3.1331 + }, + { + "x": 3.7416, + "y": 3.346 + }, + { + "x": 3.63, + "y": 3.346 + } + ], + "span": { + "offset": 363, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "proprietary", + "polygon": [ + { + "x": 3.7771, + "y": 3.1331 + }, + { + "x": 4.7251, + "y": 3.1331 + }, + { + "x": 4.7302, + "y": 3.346 + }, + { + "x": 3.7821, + "y": 3.346 + } + ], + "span": { + "offset": 365, + "length": 11 + }, + "confidence": 0.992 + }, + { + "content": "format", + "polygon": [ + { + "x": 4.7707, + "y": 3.1331 + }, + { + "x": 5.3335, + "y": 3.1331 + }, + { + "x": 5.3335, + "y": 3.346 + }, + { + "x": 4.7707, + "y": 3.346 + } + ], + "span": { + "offset": 377, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "controlled", + "polygon": [ + { + "x": 5.3741, + "y": 3.1331 + }, + { + "x": 6.2258, + "y": 3.1331 + }, + { + "x": 6.2258, + "y": 3.3409 + }, + { + "x": 5.3741, + "y": 3.346 + } + ], + "span": { + "offset": 384, + "length": 10 + }, + "confidence": 0.992 + }, + { + "content": "by", + "polygon": [ + { + "x": 6.2664, + "y": 3.1331 + }, + { + "x": 6.4844, + "y": 3.1331 + }, + { + "x": 6.4844, + "y": 3.3409 + }, + { + "x": 6.2664, + "y": 3.3409 + } + ], + "span": { + "offset": 395, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "Adobe", + "polygon": [ + { + "x": 6.5249, + "y": 3.1331 + }, + { + "x": 7.0927, + "y": 3.1331 + }, + { + "x": 7.0927, + "y": 3.3359 + }, + { + "x": 6.53, + "y": 3.3409 + } + ], + "span": { + "offset": 398, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "until", + "polygon": [ + { + "x": 0.7909, + "y": 3.3713 + }, + { + "x": 1.1255, + "y": 3.3713 + }, + { + "x": 1.1204, + "y": 3.564 + }, + { + "x": 0.7858, + "y": 3.564 + } + ], + "span": { + "offset": 404, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "it", + "polygon": [ + { + "x": 1.1661, + "y": 3.3713 + }, + { + "x": 1.2877, + "y": 3.3713 + }, + { + "x": 1.2827, + "y": 3.564 + }, + { + "x": 1.161, + "y": 3.564 + } + ], + "span": { + "offset": 410, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "was", + "polygon": [ + { + "x": 1.3283, + "y": 3.3713 + }, + { + "x": 1.6832, + "y": 3.3713 + }, + { + "x": 1.6781, + "y": 3.5691 + }, + { + "x": 1.3232, + "y": 3.564 + } + ], + "span": { + "offset": 413, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "released", + "polygon": [ + { + "x": 1.7238, + "y": 3.3713 + }, + { + "x": 2.4842, + "y": 3.3713 + }, + { + "x": 2.4792, + "y": 3.5741 + }, + { + "x": 1.7187, + "y": 3.5691 + } + ], + "span": { + "offset": 417, + "length": 8 + }, + "confidence": 0.994 + }, + { + "content": "as", + "polygon": [ + { + "x": 2.5501, + "y": 3.3713 + }, + { + "x": 2.7529, + "y": 3.3713 + }, + { + "x": 2.7479, + "y": 3.5741 + }, + { + "x": 2.5451, + "y": 3.5741 + } + ], + "span": { + "offset": 426, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "an", + "polygon": [ + { + "x": 2.8087, + "y": 3.3713 + }, + { + "x": 3.0115, + "y": 3.3713 + }, + { + "x": 3.0064, + "y": 3.5792 + }, + { + "x": 2.8036, + "y": 3.5741 + } + ], + "span": { + "offset": 429, + "length": 2 + }, + "confidence": 0.997 + }, + { + "content": "open", + "polygon": [ + { + "x": 3.0673, + "y": 3.3713 + }, + { + "x": 3.483, + "y": 3.3663 + }, + { + "x": 3.483, + "y": 3.5792 + }, + { + "x": 3.0622, + "y": 3.5792 + } + ], + "span": { + "offset": 432, + "length": 4 + }, + "confidence": 0.991 + }, + { + "content": "standard", + "polygon": [ + { + "x": 3.5641, + "y": 3.3663 + }, + { + "x": 4.3145, + "y": 3.3663 + }, + { + "x": 4.3094, + "y": 3.5843 + }, + { + "x": 3.5641, + "y": 3.5792 + } + ], + "span": { + "offset": 437, + "length": 8 + }, + "confidence": 0.994 + }, + { + "content": "on", + "polygon": [ + { + "x": 4.3652, + "y": 3.3663 + }, + { + "x": 4.568, + "y": 3.3663 + }, + { + "x": 4.568, + "y": 3.5843 + }, + { + "x": 4.3652, + "y": 3.5843 + } + ], + "span": { + "offset": 446, + "length": 2 + }, + "confidence": 0.997 + }, + { + "content": "July", + "polygon": [ + { + "x": 4.6389, + "y": 3.3663 + }, + { + "x": 5.004, + "y": 3.3713 + }, + { + "x": 5.004, + "y": 3.5843 + }, + { + "x": 4.6339, + "y": 3.5843 + } + ], + "span": { + "offset": 449, + "length": 4 + }, + "confidence": 0.987 + }, + { + "content": "1,", + "polygon": [ + { + "x": 5.0597, + "y": 3.3713 + }, + { + "x": 5.222, + "y": 3.3713 + }, + { + "x": 5.222, + "y": 3.5843 + }, + { + "x": 5.0547, + "y": 3.5843 + } + ], + "span": { + "offset": 454, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "2008,", + "polygon": [ + { + "x": 5.2625, + "y": 3.3713 + }, + { + "x": 5.7644, + "y": 3.3713 + }, + { + "x": 5.7644, + "y": 3.5843 + }, + { + "x": 5.2625, + "y": 3.5843 + } + ], + "span": { + "offset": 457, + "length": 5 + }, + "confidence": 0.967 + }, + { + "content": "and", + "polygon": [ + { + "x": 5.805, + "y": 3.3713 + }, + { + "x": 6.1143, + "y": 3.3713 + }, + { + "x": 6.1143, + "y": 3.5843 + }, + { + "x": 5.805, + "y": 3.5843 + } + ], + "span": { + "offset": 463, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "published", + "polygon": [ + { + "x": 6.17, + "y": 3.3713 + }, + { + "x": 7.0116, + "y": 3.3713 + }, + { + "x": 7.0116, + "y": 3.5792 + }, + { + "x": 6.17, + "y": 3.5843 + } + ], + "span": { + "offset": 467, + "length": 9 + }, + "confidence": 0.993 + }, + { + "content": "by", + "polygon": [ + { + "x": 7.0522, + "y": 3.3713 + }, + { + "x": 7.2702, + "y": 3.3713 + }, + { + "x": 7.2702, + "y": 3.5792 + }, + { + "x": 7.0522, + "y": 3.5792 + } + ], + "span": { + "offset": 477, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "the", + "polygon": [ + { + "x": 0.7706, + "y": 3.6045 + }, + { + "x": 1.0343, + "y": 3.6045 + }, + { + "x": 1.0393, + "y": 3.8073 + }, + { + "x": 0.7757, + "y": 3.8073 + } + ], + "span": { + "offset": 480, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "International", + "polygon": [ + { + "x": 1.09, + "y": 3.6045 + }, + { + "x": 2.18, + "y": 3.5995 + }, + { + "x": 2.1851, + "y": 3.8073 + }, + { + "x": 1.0951, + "y": 3.8073 + } + ], + "span": { + "offset": 484, + "length": 13 + }, + "confidence": 0.979 + }, + { + "content": "Organization", + "polygon": [ + { + "x": 2.2206, + "y": 3.5995 + }, + { + "x": 3.3106, + "y": 3.5995 + }, + { + "x": 3.3106, + "y": 3.8073 + }, + { + "x": 2.2257, + "y": 3.8073 + } + ], + "span": { + "offset": 498, + "length": 12 + }, + "confidence": 0.99 + }, + { + "content": "for", + "polygon": [ + { + "x": 3.3613, + "y": 3.5995 + }, + { + "x": 3.63, + "y": 3.5995 + }, + { + "x": 3.6351, + "y": 3.8073 + }, + { + "x": 3.3664, + "y": 3.8073 + } + ], + "span": { + "offset": 511, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "Standardization", + "polygon": [ + { + "x": 3.6706, + "y": 3.5995 + }, + { + "x": 5.004, + "y": 3.5995 + }, + { + "x": 5.004, + "y": 3.8073 + }, + { + "x": 3.6757, + "y": 3.8073 + } + ], + "span": { + "offset": 515, + "length": 15 + }, + "confidence": 0.991 + }, + { + "content": "as", + "polygon": [ + { + "x": 5.0699, + "y": 3.5995 + }, + { + "x": 5.2727, + "y": 3.5995 + }, + { + "x": 5.2727, + "y": 3.8073 + }, + { + "x": 5.0699, + "y": 3.8073 + } + ], + "span": { + "offset": 531, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "ISO", + "polygon": [ + { + "x": 5.3132, + "y": 3.5995 + }, + { + "x": 5.6225, + "y": 3.5995 + }, + { + "x": 5.6225, + "y": 3.8073 + }, + { + "x": 5.3132, + "y": 3.8073 + } + ], + "span": { + "offset": 534, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "32000-1:2008,", + "polygon": [ + { + "x": 5.7188, + "y": 3.5995 + }, + { + "x": 6.9812, + "y": 3.6045 + }, + { + "x": 6.9812, + "y": 3.8023 + }, + { + "x": 5.7188, + "y": 3.8073 + } + ], + "span": { + "offset": 538, + "length": 13 + }, + "confidence": 0.982 + }, + { + "content": "at", + "polygon": [ + { + "x": 7.0218, + "y": 3.6045 + }, + { + "x": 7.1992, + "y": 3.6045 + }, + { + "x": 7.1992, + "y": 3.8023 + }, + { + "x": 7.0218, + "y": 3.8023 + } + ], + "span": { + "offset": 552, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "which", + "polygon": [ + { + "x": 0.7757, + "y": 3.8428 + }, + { + "x": 1.2624, + "y": 3.8428 + }, + { + "x": 1.2624, + "y": 4.0355 + }, + { + "x": 0.7808, + "y": 4.0304 + } + ], + "span": { + "offset": 555, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "time", + "polygon": [ + { + "x": 1.3131, + "y": 3.8428 + }, + { + "x": 1.6832, + "y": 3.8378 + }, + { + "x": 1.6883, + "y": 4.0405 + }, + { + "x": 1.3182, + "y": 4.0355 + } + ], + "span": { + "offset": 561, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "control", + "polygon": [ + { + "x": 1.739, + "y": 3.8378 + }, + { + "x": 2.3474, + "y": 3.8378 + }, + { + "x": 2.3474, + "y": 4.0456 + }, + { + "x": 1.739, + "y": 4.0405 + } + ], + "span": { + "offset": 566, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "of", + "polygon": [ + { + "x": 2.3879, + "y": 3.8378 + }, + { + "x": 2.5451, + "y": 3.8378 + }, + { + "x": 2.5451, + "y": 4.0456 + }, + { + "x": 2.3879, + "y": 4.0456 + } + ], + "span": { + "offset": 574, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "the", + "polygon": [ + { + "x": 2.5856, + "y": 3.8378 + }, + { + "x": 2.8594, + "y": 3.8378 + }, + { + "x": 2.8645, + "y": 4.0456 + }, + { + "x": 2.5856, + "y": 4.0456 + } + ], + "span": { + "offset": 577, + "length": 3 + }, + "confidence": 0.993 + }, + { + "content": "specification", + "polygon": [ + { + "x": 2.9253, + "y": 3.8327 + }, + { + "x": 3.9849, + "y": 3.8327 + }, + { + "x": 3.9849, + "y": 4.0456 + }, + { + "x": 2.9304, + "y": 4.0456 + } + ], + "span": { + "offset": 581, + "length": 13 + }, + "confidence": 0.961 + }, + { + "content": "passed", + "polygon": [ + { + "x": 4.0356, + "y": 3.8327 + }, + { + "x": 4.6694, + "y": 3.8327 + }, + { + "x": 4.6744, + "y": 4.0456 + }, + { + "x": 4.0407, + "y": 4.0456 + } + ], + "span": { + "offset": 595, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "to", + "polygon": [ + { + "x": 4.7251, + "y": 3.8327 + }, + { + "x": 4.8975, + "y": 3.8327 + }, + { + "x": 4.8975, + "y": 4.0405 + }, + { + "x": 4.7251, + "y": 4.0456 + } + ], + "span": { + "offset": 602, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "an", + "polygon": [ + { + "x": 4.9482, + "y": 3.8327 + }, + { + "x": 5.1611, + "y": 3.8327 + }, + { + "x": 5.1611, + "y": 4.0405 + }, + { + "x": 4.9482, + "y": 4.0405 + } + ], + "span": { + "offset": 605, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "ISO", + "polygon": [ + { + "x": 5.2118, + "y": 3.8327 + }, + { + "x": 5.516, + "y": 3.8327 + }, + { + "x": 5.516, + "y": 4.0355 + }, + { + "x": 5.2118, + "y": 4.0405 + } + ], + "span": { + "offset": 608, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "Committee", + "polygon": [ + { + "x": 5.6123, + "y": 3.8327 + }, + { + "x": 6.5503, + "y": 3.8378 + }, + { + "x": 6.5503, + "y": 4.0253 + }, + { + "x": 5.6123, + "y": 4.0355 + } + ], + "span": { + "offset": 612, + "length": 9 + }, + "confidence": 0.993 + }, + { + "content": "of", + "polygon": [ + { + "x": 6.601, + "y": 3.8378 + }, + { + "x": 6.7784, + "y": 3.8378 + }, + { + "x": 6.7784, + "y": 4.0203 + }, + { + "x": 6.601, + "y": 4.0253 + } + ], + "span": { + "offset": 622, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "volunteer", + "polygon": [ + { + "x": 0.7706, + "y": 4.0811 + }, + { + "x": 1.5717, + "y": 4.076 + }, + { + "x": 1.5767, + "y": 4.2788 + }, + { + "x": 0.7757, + "y": 4.2737 + } + ], + "span": { + "offset": 625, + "length": 9 + }, + "confidence": 0.993 + }, + { + "content": "industry", + "polygon": [ + { + "x": 1.6122, + "y": 4.076 + }, + { + "x": 2.3169, + "y": 4.076 + }, + { + "x": 2.3169, + "y": 4.2839 + }, + { + "x": 1.6173, + "y": 4.2788 + } + ], + "span": { + "offset": 635, + "length": 8 + }, + "confidence": 0.994 + }, + { + "content": "experts.", + "polygon": [ + { + "x": 2.3524, + "y": 4.076 + }, + { + "x": 3.0571, + "y": 4.071 + }, + { + "x": 3.0571, + "y": 4.2839 + }, + { + "x": 2.3575, + "y": 4.2839 + } + ], + "span": { + "offset": 644, + "length": 8 + }, + "confidence": 0.992 + }, + { + "content": "In", + "polygon": [ + { + "x": 3.0926, + "y": 4.071 + }, + { + "x": 3.2549, + "y": 4.071 + }, + { + "x": 3.2549, + "y": 4.2839 + }, + { + "x": 3.0977, + "y": 4.2839 + } + ], + "span": { + "offset": 653, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "2008,", + "polygon": [ + { + "x": 3.3309, + "y": 4.071 + }, + { + "x": 3.8227, + "y": 4.071 + }, + { + "x": 3.8227, + "y": 4.2839 + }, + { + "x": 3.336, + "y": 4.2839 + } + ], + "span": { + "offset": 656, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "Adobe", + "polygon": [ + { + "x": 3.8632, + "y": 4.071 + }, + { + "x": 4.4159, + "y": 4.071 + }, + { + "x": 4.4159, + "y": 4.2839 + }, + { + "x": 3.8632, + "y": 4.2839 + } + ], + "span": { + "offset": 662, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "published", + "polygon": [ + { + "x": 4.4564, + "y": 4.071 + }, + { + "x": 5.3031, + "y": 4.071 + }, + { + "x": 5.3031, + "y": 4.2788 + }, + { + "x": 4.4564, + "y": 4.2839 + } + ], + "span": { + "offset": 668, + "length": 9 + }, + "confidence": 0.974 + }, + { + "content": "a", + "polygon": [ + { + "x": 5.3589, + "y": 4.071 + }, + { + "x": 5.4603, + "y": 4.071 + }, + { + "x": 5.4603, + "y": 4.2788 + }, + { + "x": 5.3538, + "y": 4.2788 + } + ], + "span": { + "offset": 678, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "Public", + "polygon": [ + { + "x": 5.516, + "y": 4.071 + }, + { + "x": 6.0585, + "y": 4.071 + }, + { + "x": 6.0534, + "y": 4.2737 + }, + { + "x": 5.516, + "y": 4.2788 + } + ], + "span": { + "offset": 680, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "Patent", + "polygon": [ + { + "x": 6.0991, + "y": 4.071 + }, + { + "x": 6.677, + "y": 4.076 + }, + { + "x": 6.677, + "y": 4.2687 + }, + { + "x": 6.094, + "y": 4.2737 + } + ], + "span": { + "offset": 687, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "License", + "polygon": [ + { + "x": 6.7176, + "y": 4.076 + }, + { + "x": 7.3817, + "y": 4.076 + }, + { + "x": 7.3767, + "y": 4.2585 + }, + { + "x": 6.7176, + "y": 4.2687 + } + ], + "span": { + "offset": 694, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "to", + "polygon": [ + { + "x": 0.7808, + "y": 4.3143 + }, + { + "x": 0.9278, + "y": 4.3143 + }, + { + "x": 0.9329, + "y": 4.512 + }, + { + "x": 0.7808, + "y": 4.512 + } + ], + "span": { + "offset": 702, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "ISO", + "polygon": [ + { + "x": 0.9836, + "y": 4.3143 + }, + { + "x": 1.2877, + "y": 4.3143 + }, + { + "x": 1.2877, + "y": 4.5171 + }, + { + "x": 0.9836, + "y": 4.512 + } + ], + "span": { + "offset": 705, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "32000-1", + "polygon": [ + { + "x": 1.379, + "y": 4.3092 + }, + { + "x": 2.1091, + "y": 4.3092 + }, + { + "x": 2.1091, + "y": 4.5222 + }, + { + "x": 1.3841, + "y": 4.5171 + } + ], + "span": { + "offset": 709, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "granting", + "polygon": [ + { + "x": 2.1496, + "y": 4.3092 + }, + { + "x": 2.8493, + "y": 4.3092 + }, + { + "x": 2.8493, + "y": 4.5272 + }, + { + "x": 2.1496, + "y": 4.5222 + } + ], + "span": { + "offset": 717, + "length": 8 + }, + "confidence": 0.993 + }, + { + "content": "royalty-free", + "polygon": [ + { + "x": 2.8898, + "y": 4.3092 + }, + { + "x": 3.8785, + "y": 4.3092 + }, + { + "x": 3.8785, + "y": 4.5272 + }, + { + "x": 2.8898, + "y": 4.5272 + } + ], + "span": { + "offset": 726, + "length": 12 + }, + "confidence": 0.984 + }, + { + "content": "rights", + "polygon": [ + { + "x": 3.919, + "y": 4.3092 + }, + { + "x": 4.4108, + "y": 4.3143 + }, + { + "x": 4.4108, + "y": 4.5272 + }, + { + "x": 3.919, + "y": 4.5272 + } + ], + "span": { + "offset": 739, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "for", + "polygon": [ + { + "x": 4.4513, + "y": 4.3143 + }, + { + "x": 4.6998, + "y": 4.3143 + }, + { + "x": 4.6998, + "y": 4.5272 + }, + { + "x": 4.4513, + "y": 4.5272 + } + ], + "span": { + "offset": 746, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "all", + "polygon": [ + { + "x": 4.7403, + "y": 4.3143 + }, + { + "x": 4.933, + "y": 4.3143 + }, + { + "x": 4.933, + "y": 4.5272 + }, + { + "x": 4.7403, + "y": 4.5272 + } + ], + "span": { + "offset": 750, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "patents", + "polygon": [ + { + "x": 4.9735, + "y": 4.3143 + }, + { + "x": 5.6326, + "y": 4.3143 + }, + { + "x": 5.6326, + "y": 4.5272 + }, + { + "x": 4.9735, + "y": 4.5272 + } + ], + "span": { + "offset": 754, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "owned", + "polygon": [ + { + "x": 5.6732, + "y": 4.3143 + }, + { + "x": 6.2512, + "y": 4.3143 + }, + { + "x": 6.2512, + "y": 4.5222 + }, + { + "x": 5.6732, + "y": 4.5272 + } + ], + "span": { + "offset": 762, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "by", + "polygon": [ + { + "x": 6.2917, + "y": 4.3143 + }, + { + "x": 6.5249, + "y": 4.3143 + }, + { + "x": 6.5249, + "y": 4.5171 + }, + { + "x": 6.2917, + "y": 4.5222 + } + ], + "span": { + "offset": 768, + "length": 2 + }, + "confidence": 0.961 + }, + { + "content": "Adobe", + "polygon": [ + { + "x": 6.5655, + "y": 4.3143 + }, + { + "x": 7.113, + "y": 4.3194 + }, + { + "x": 7.113, + "y": 4.512 + }, + { + "x": 6.5655, + "y": 4.5171 + } + ], + "span": { + "offset": 771, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "that", + "polygon": [ + { + "x": 0.7656, + "y": 4.5576 + }, + { + "x": 1.1204, + "y": 4.5526 + }, + { + "x": 1.1154, + "y": 4.7554 + }, + { + "x": 0.7605, + "y": 4.7554 + } + ], + "span": { + "offset": 777, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "are", + "polygon": [ + { + "x": 1.161, + "y": 4.5526 + }, + { + "x": 1.4348, + "y": 4.5526 + }, + { + "x": 1.4297, + "y": 4.7554 + }, + { + "x": 1.1559, + "y": 4.7554 + } + ], + "span": { + "offset": 782, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "necessary", + "polygon": [ + { + "x": 1.4753, + "y": 4.5526 + }, + { + "x": 2.3778, + "y": 4.5526 + }, + { + "x": 2.3727, + "y": 4.7604 + }, + { + "x": 1.4703, + "y": 4.7554 + } + ], + "span": { + "offset": 786, + "length": 9 + }, + "confidence": 0.994 + }, + { + "content": "to", + "polygon": [ + { + "x": 2.4183, + "y": 4.5526 + }, + { + "x": 2.5958, + "y": 4.5475 + }, + { + "x": 2.5958, + "y": 4.7604 + }, + { + "x": 2.4133, + "y": 4.7604 + } + ], + "span": { + "offset": 796, + "length": 2 + }, + "confidence": 0.997 + }, + { + "content": "make,", + "polygon": [ + { + "x": 2.6363, + "y": 4.5475 + }, + { + "x": 3.1839, + "y": 4.5475 + }, + { + "x": 3.1839, + "y": 4.7604 + }, + { + "x": 2.6363, + "y": 4.7604 + } + ], + "span": { + "offset": 799, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "use,", + "polygon": [ + { + "x": 3.2244, + "y": 4.5475 + }, + { + "x": 3.625, + "y": 4.5475 + }, + { + "x": 3.6199, + "y": 4.7604 + }, + { + "x": 3.2244, + "y": 4.7604 + } + ], + "span": { + "offset": 805, + "length": 4 + }, + "confidence": 0.99 + }, + { + "content": "sell,", + "polygon": [ + { + "x": 3.6655, + "y": 4.5475 + }, + { + "x": 4.0204, + "y": 4.5475 + }, + { + "x": 4.0153, + "y": 4.7604 + }, + { + "x": 3.6604, + "y": 4.7604 + } + ], + "span": { + "offset": 810, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "and", + "polygon": [ + { + "x": 4.061, + "y": 4.5475 + }, + { + "x": 4.3753, + "y": 4.5475 + }, + { + "x": 4.3753, + "y": 4.7604 + }, + { + "x": 4.061, + "y": 4.7604 + } + ], + "span": { + "offset": 816, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "distribute", + "polygon": [ + { + "x": 4.4311, + "y": 4.5475 + }, + { + "x": 5.222, + "y": 4.5475 + }, + { + "x": 5.222, + "y": 4.7604 + }, + { + "x": 4.426, + "y": 4.7604 + } + ], + "span": { + "offset": 820, + "length": 10 + }, + "confidence": 0.99 + }, + { + "content": "PDF-compliant", + "polygon": [ + { + "x": 5.2777, + "y": 4.5475 + }, + { + "x": 6.5655, + "y": 4.5526 + }, + { + "x": 6.5655, + "y": 4.7554 + }, + { + "x": 5.2777, + "y": 4.7604 + } + ], + "span": { + "offset": 831, + "length": 13 + }, + "confidence": 0.985 + }, + { + "content": "implementations.", + "polygon": [ + { + "x": 0.7706, + "y": 4.7909 + }, + { + "x": 2.251, + "y": 4.7858 + }, + { + "x": 2.246, + "y": 4.9936 + }, + { + "x": 0.7656, + "y": 4.9936 + } + ], + "span": { + "offset": 845, + "length": 16 + }, + "confidence": 0.977 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 2.2916, + "y": 4.7858 + }, + { + "x": 2.6718, + "y": 4.7858 + }, + { + "x": 2.6718, + "y": 4.9936 + }, + { + "x": 2.2865, + "y": 4.9936 + } + ], + "span": { + "offset": 862, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "1.7,", + "polygon": [ + { + "x": 2.7529, + "y": 4.7807 + }, + { + "x": 3.0673, + "y": 4.7807 + }, + { + "x": 3.0673, + "y": 4.9936 + }, + { + "x": 2.7529, + "y": 4.9936 + } + ], + "span": { + "offset": 866, + "length": 4 + }, + "confidence": 0.977 + }, + { + "content": "the", + "polygon": [ + { + "x": 3.1078, + "y": 4.7807 + }, + { + "x": 3.3968, + "y": 4.7807 + }, + { + "x": 3.3917, + "y": 4.9936 + }, + { + "x": 3.1078, + "y": 4.9936 + } + ], + "span": { + "offset": 871, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "sixth", + "polygon": [ + { + "x": 3.4475, + "y": 4.7807 + }, + { + "x": 3.843, + "y": 4.7807 + }, + { + "x": 3.843, + "y": 4.9936 + }, + { + "x": 3.4475, + "y": 4.9936 + } + ], + "span": { + "offset": 875, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "edition", + "polygon": [ + { + "x": 3.8987, + "y": 4.7807 + }, + { + "x": 4.4716, + "y": 4.7807 + }, + { + "x": 4.4666, + "y": 4.9936 + }, + { + "x": 3.8937, + "y": 4.9936 + } + ], + "span": { + "offset": 881, + "length": 7 + }, + "confidence": 0.993 + }, + { + "content": "of", + "polygon": [ + { + "x": 4.5223, + "y": 4.7807 + }, + { + "x": 4.6896, + "y": 4.7807 + }, + { + "x": 4.6846, + "y": 4.9936 + }, + { + "x": 4.5223, + "y": 4.9936 + } + ], + "span": { + "offset": 889, + "length": 2 + }, + "confidence": 0.993 + }, + { + "content": "the", + "polygon": [ + { + "x": 4.7302, + "y": 4.7807 + }, + { + "x": 5.0141, + "y": 4.7807 + }, + { + "x": 5.0141, + "y": 4.9936 + }, + { + "x": 4.7251, + "y": 4.9936 + } + ], + "span": { + "offset": 892, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 5.0699, + "y": 4.7807 + }, + { + "x": 5.4501, + "y": 4.7858 + }, + { + "x": 5.4501, + "y": 4.9936 + }, + { + "x": 5.0648, + "y": 4.9936 + } + ], + "span": { + "offset": 896, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "specification", + "polygon": [ + { + "x": 5.516, + "y": 4.7858 + }, + { + "x": 6.5807, + "y": 4.7858 + }, + { + "x": 6.5807, + "y": 4.9936 + }, + { + "x": 5.516, + "y": 4.9936 + } + ], + "span": { + "offset": 900, + "length": 13 + }, + "confidence": 0.981 + }, + { + "content": "that", + "polygon": [ + { + "x": 6.6314, + "y": 4.7858 + }, + { + "x": 6.9761, + "y": 4.7909 + }, + { + "x": 6.9761, + "y": 4.9936 + }, + { + "x": 6.6314, + "y": 4.9936 + } + ], + "span": { + "offset": 914, + "length": 4 + }, + "confidence": 0.986 + }, + { + "content": "became", + "polygon": [ + { + "x": 0.7757, + "y": 5.019 + }, + { + "x": 1.4652, + "y": 5.019 + }, + { + "x": 1.4703, + "y": 5.2116 + }, + { + "x": 0.7757, + "y": 5.2066 + } + ], + "span": { + "offset": 919, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "ISO", + "polygon": [ + { + "x": 1.5058, + "y": 5.019 + }, + { + "x": 1.815, + "y": 5.019 + }, + { + "x": 1.815, + "y": 5.2167 + }, + { + "x": 1.5108, + "y": 5.2116 + } + ], + "span": { + "offset": 926, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "32000-1,", + "polygon": [ + { + "x": 1.9063, + "y": 5.019 + }, + { + "x": 2.6718, + "y": 5.019 + }, + { + "x": 2.6718, + "y": 5.2218 + }, + { + "x": 1.9113, + "y": 5.2167 + } + ], + "span": { + "offset": 930, + "length": 8 + }, + "confidence": 0.993 + }, + { + "content": "includes", + "polygon": [ + { + "x": 2.7124, + "y": 5.019 + }, + { + "x": 3.4475, + "y": 5.019 + }, + { + "x": 3.4475, + "y": 5.2268 + }, + { + "x": 2.7124, + "y": 5.2218 + } + ], + "span": { + "offset": 939, + "length": 8 + }, + "confidence": 0.993 + }, + { + "content": "some", + "polygon": [ + { + "x": 3.5033, + "y": 5.019 + }, + { + "x": 3.9697, + "y": 5.019 + }, + { + "x": 3.9697, + "y": 5.2268 + }, + { + "x": 3.5033, + "y": 5.2268 + } + ], + "span": { + "offset": 948, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "proprietary", + "polygon": [ + { + "x": 4.0103, + "y": 5.019 + }, + { + "x": 4.9634, + "y": 5.019 + }, + { + "x": 4.9634, + "y": 5.2319 + }, + { + "x": 4.0103, + "y": 5.2268 + } + ], + "span": { + "offset": 953, + "length": 11 + }, + "confidence": 0.99 + }, + { + "content": "technologies", + "polygon": [ + { + "x": 5.004, + "y": 5.019 + }, + { + "x": 6.1143, + "y": 5.0241 + }, + { + "x": 6.1143, + "y": 5.2319 + }, + { + "x": 5.004, + "y": 5.2319 + } + ], + "span": { + "offset": 965, + "length": 12 + }, + "confidence": 0.984 + }, + { + "content": "defined", + "polygon": [ + { + "x": 6.1548, + "y": 5.0241 + }, + { + "x": 6.7987, + "y": 5.0241 + }, + { + "x": 6.7936, + "y": 5.2319 + }, + { + "x": 6.1548, + "y": 5.2319 + } + ], + "span": { + "offset": 978, + "length": 7 + }, + "confidence": 0.983 + }, + { + "content": "only", + "polygon": [ + { + "x": 6.8494, + "y": 5.0241 + }, + { + "x": 7.2144, + "y": 5.0241 + }, + { + "x": 7.2094, + "y": 5.2319 + }, + { + "x": 6.8494, + "y": 5.2319 + } + ], + "span": { + "offset": 986, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "by", + "polygon": [ + { + "x": 7.255, + "y": 5.0241 + }, + { + "x": 7.473, + "y": 5.0241 + }, + { + "x": 7.4679, + "y": 5.2319 + }, + { + "x": 7.2499, + "y": 5.2319 + } + ], + "span": { + "offset": 991, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "Adobe,", + "polygon": [ + { + "x": 0.7808, + "y": 5.2573 + }, + { + "x": 1.4094, + "y": 5.2573 + }, + { + "x": 1.4094, + "y": 5.455 + }, + { + "x": 0.7808, + "y": 5.455 + } + ], + "span": { + "offset": 994, + "length": 6 + }, + "confidence": 0.993 + }, + { + "content": "such", + "polygon": [ + { + "x": 1.45, + "y": 5.2573 + }, + { + "x": 1.8404, + "y": 5.2573 + }, + { + "x": 1.8404, + "y": 5.455 + }, + { + "x": 1.45, + "y": 5.455 + } + ], + "span": { + "offset": 1001, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "as", + "polygon": [ + { + "x": 1.9063, + "y": 5.2573 + }, + { + "x": 2.1243, + "y": 5.2522 + }, + { + "x": 2.1243, + "y": 5.455 + }, + { + "x": 1.9113, + "y": 5.455 + } + ], + "span": { + "offset": 1006, + "length": 2 + }, + "confidence": 0.971 + }, + { + "content": "Adobe", + "polygon": [ + { + "x": 2.1648, + "y": 5.2522 + }, + { + "x": 2.7175, + "y": 5.2522 + }, + { + "x": 2.7175, + "y": 5.4601 + }, + { + "x": 2.1648, + "y": 5.455 + } + ], + "span": { + "offset": 1009, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "XML", + "polygon": [ + { + "x": 2.7986, + "y": 5.2522 + }, + { + "x": 3.1737, + "y": 5.2522 + }, + { + "x": 3.1737, + "y": 5.4601 + }, + { + "x": 2.7986, + "y": 5.4601 + } + ], + "span": { + "offset": 1015, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "Forms", + "polygon": [ + { + "x": 3.2143, + "y": 5.2522 + }, + { + "x": 3.7923, + "y": 5.2522 + }, + { + "x": 3.7923, + "y": 5.4601 + }, + { + "x": 3.2143, + "y": 5.4601 + } + ], + "span": { + "offset": 1019, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "Architecture", + "polygon": [ + { + "x": 3.8328, + "y": 5.2522 + }, + { + "x": 4.8569, + "y": 5.2522 + }, + { + "x": 4.8569, + "y": 5.4601 + }, + { + "x": 3.8328, + "y": 5.4601 + } + ], + "span": { + "offset": 1025, + "length": 12 + }, + "confidence": 0.983 + }, + { + "content": "(XFA)", + "polygon": [ + { + "x": 4.9127, + "y": 5.2522 + }, + { + "x": 5.4248, + "y": 5.2573 + }, + { + "x": 5.4197, + "y": 5.4651 + }, + { + "x": 4.9076, + "y": 5.4601 + } + ], + "span": { + "offset": 1038, + "length": 5 + }, + "confidence": 0.979 + }, + { + "content": "and", + "polygon": [ + { + "x": 5.4653, + "y": 5.2573 + }, + { + "x": 5.7847, + "y": 5.2573 + }, + { + "x": 5.7847, + "y": 5.4651 + }, + { + "x": 5.4603, + "y": 5.4651 + } + ], + "span": { + "offset": 1044, + "length": 3 + }, + "confidence": 0.991 + }, + { + "content": "JavaScript", + "polygon": [ + { + "x": 5.8557, + "y": 5.2573 + }, + { + "x": 6.7733, + "y": 5.2623 + }, + { + "x": 6.7683, + "y": 5.4702 + }, + { + "x": 5.8506, + "y": 5.4651 + } + ], + "span": { + "offset": 1048, + "length": 10 + }, + "confidence": 0.993 + }, + { + "content": "extension", + "polygon": [ + { + "x": 0.7656, + "y": 5.4955 + }, + { + "x": 1.5919, + "y": 5.4955 + }, + { + "x": 1.597, + "y": 5.6882 + }, + { + "x": 0.7757, + "y": 5.6831 + } + ], + "span": { + "offset": 1059, + "length": 9 + }, + "confidence": 0.985 + }, + { + "content": "for", + "polygon": [ + { + "x": 1.6426, + "y": 5.4955 + }, + { + "x": 1.9012, + "y": 5.4905 + }, + { + "x": 1.9063, + "y": 5.6882 + }, + { + "x": 1.6477, + "y": 5.6882 + } + ], + "span": { + "offset": 1069, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "Acrobat,", + "polygon": [ + { + "x": 1.9418, + "y": 5.4905 + }, + { + "x": 2.6668, + "y": 5.4905 + }, + { + "x": 2.6718, + "y": 5.6933 + }, + { + "x": 1.9468, + "y": 5.6882 + } + ], + "span": { + "offset": 1073, + "length": 8 + }, + "confidence": 0.994 + }, + { + "content": "which", + "polygon": [ + { + "x": 2.7073, + "y": 5.4905 + }, + { + "x": 3.1839, + "y": 5.4905 + }, + { + "x": 3.1889, + "y": 5.6933 + }, + { + "x": 2.7073, + "y": 5.6933 + } + ], + "span": { + "offset": 1082, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "are", + "polygon": [ + { + "x": 3.2599, + "y": 5.4905 + }, + { + "x": 3.5337, + "y": 5.4905 + }, + { + "x": 3.5388, + "y": 5.6933 + }, + { + "x": 3.265, + "y": 5.6933 + } + ], + "span": { + "offset": 1088, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "referenced", + "polygon": [ + { + "x": 3.5844, + "y": 5.4905 + }, + { + "x": 4.5173, + "y": 5.4905 + }, + { + "x": 4.5173, + "y": 5.6933 + }, + { + "x": 3.5895, + "y": 5.6933 + } + ], + "span": { + "offset": 1092, + "length": 10 + }, + "confidence": 0.992 + }, + { + "content": "by", + "polygon": [ + { + "x": 4.568, + "y": 5.4905 + }, + { + "x": 4.786, + "y": 5.4905 + }, + { + "x": 4.791, + "y": 5.6933 + }, + { + "x": 4.568, + "y": 5.6933 + } + ], + "span": { + "offset": 1103, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "ISO", + "polygon": [ + { + "x": 4.8265, + "y": 5.4905 + }, + { + "x": 5.1256, + "y": 5.4905 + }, + { + "x": 5.1256, + "y": 5.6933 + }, + { + "x": 4.8265, + "y": 5.6933 + } + ], + "span": { + "offset": 1106, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "32000-1", + "polygon": [ + { + "x": 5.227, + "y": 5.4905 + }, + { + "x": 5.952, + "y": 5.4905 + }, + { + "x": 5.952, + "y": 5.6882 + }, + { + "x": 5.227, + "y": 5.6933 + } + ], + "span": { + "offset": 1110, + "length": 7 + }, + "confidence": 0.991 + }, + { + "content": "as", + "polygon": [ + { + "x": 6.0027, + "y": 5.4905 + }, + { + "x": 6.2005, + "y": 5.4905 + }, + { + "x": 6.2005, + "y": 5.6882 + }, + { + "x": 6.0027, + "y": 5.6882 + } + ], + "span": { + "offset": 1118, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "normative", + "polygon": [ + { + "x": 6.2359, + "y": 5.4905 + }, + { + "x": 7.1029, + "y": 5.4955 + }, + { + "x": 7.1029, + "y": 5.678 + }, + { + "x": 6.2359, + "y": 5.6882 + } + ], + "span": { + "offset": 1121, + "length": 9 + }, + "confidence": 0.994 + }, + { + "content": "and", + "polygon": [ + { + "x": 0.7757, + "y": 5.7338 + }, + { + "x": 1.085, + "y": 5.7338 + }, + { + "x": 1.09, + "y": 5.9366 + }, + { + "x": 0.7858, + "y": 5.9366 + } + ], + "span": { + "offset": 1131, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "indispensable", + "polygon": [ + { + "x": 1.1357, + "y": 5.7338 + }, + { + "x": 2.3372, + "y": 5.7287 + }, + { + "x": 2.3423, + "y": 5.9366 + }, + { + "x": 1.1458, + "y": 5.9366 + } + ], + "span": { + "offset": 1135, + "length": 13 + }, + "confidence": 0.987 + }, + { + "content": "for", + "polygon": [ + { + "x": 2.3778, + "y": 5.7287 + }, + { + "x": 2.6211, + "y": 5.7287 + }, + { + "x": 2.6262, + "y": 5.9366 + }, + { + "x": 2.3828, + "y": 5.9366 + } + ], + "span": { + "offset": 1149, + "length": 3 + }, + "confidence": 0.983 + }, + { + "content": "the", + "polygon": [ + { + "x": 2.6617, + "y": 5.7287 + }, + { + "x": 2.9405, + "y": 5.7287 + }, + { + "x": 2.9456, + "y": 5.9366 + }, + { + "x": 2.6617, + "y": 5.9366 + } + ], + "span": { + "offset": 1153, + "length": 3 + }, + "confidence": 0.994 + }, + { + "content": "full", + "polygon": [ + { + "x": 2.9963, + "y": 5.7287 + }, + { + "x": 3.2498, + "y": 5.7237 + }, + { + "x": 3.2498, + "y": 5.9366 + }, + { + "x": 2.9963, + "y": 5.9366 + } + ], + "span": { + "offset": 1157, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "implementation", + "polygon": [ + { + "x": 3.2853, + "y": 5.7237 + }, + { + "x": 4.6085, + "y": 5.7237 + }, + { + "x": 4.6136, + "y": 5.9315 + }, + { + "x": 3.2903, + "y": 5.9366 + } + ], + "span": { + "offset": 1162, + "length": 14 + }, + "confidence": 0.988 + }, + { + "content": "of", + "polygon": [ + { + "x": 4.6744, + "y": 5.7237 + }, + { + "x": 4.8519, + "y": 5.7237 + }, + { + "x": 4.8519, + "y": 5.9315 + }, + { + "x": 4.6795, + "y": 5.9315 + } + ], + "span": { + "offset": 1177, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "the", + "polygon": [ + { + "x": 4.8874, + "y": 5.7237 + }, + { + "x": 5.1713, + "y": 5.7237 + }, + { + "x": 5.1713, + "y": 5.9265 + }, + { + "x": 4.8924, + "y": 5.9265 + } + ], + "span": { + "offset": 1180, + "length": 3 + }, + "confidence": 0.994 + }, + { + "content": "ISO", + "polygon": [ + { + "x": 5.2118, + "y": 5.7237 + }, + { + "x": 5.516, + "y": 5.7237 + }, + { + "x": 5.516, + "y": 5.9214 + }, + { + "x": 5.2118, + "y": 5.9265 + } + ], + "span": { + "offset": 1184, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "32000-1", + "polygon": [ + { + "x": 5.6123, + "y": 5.7237 + }, + { + "x": 6.3221, + "y": 5.7287 + }, + { + "x": 6.3221, + "y": 5.9163 + }, + { + "x": 5.6123, + "y": 5.9214 + } + ], + "span": { + "offset": 1188, + "length": 7 + }, + "confidence": 0.993 + }, + { + "content": "specification.", + "polygon": [ + { + "x": 0.7909, + "y": 5.967 + }, + { + "x": 1.9316, + "y": 5.967 + }, + { + "x": 1.9316, + "y": 6.1799 + }, + { + "x": 0.7858, + "y": 6.1799 + } + ], + "span": { + "offset": 1196, + "length": 14 + }, + "confidence": 0.975 + }, + { + "content": "These", + "polygon": [ + { + "x": 1.9722, + "y": 5.967 + }, + { + "x": 2.4842, + "y": 5.967 + }, + { + "x": 2.4842, + "y": 6.1799 + }, + { + "x": 1.9722, + "y": 6.1799 + } + ], + "span": { + "offset": 1211, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "proprietary", + "polygon": [ + { + "x": 2.54, + "y": 5.967 + }, + { + "x": 3.483, + "y": 5.967 + }, + { + "x": 3.483, + "y": 6.1799 + }, + { + "x": 2.54, + "y": 6.1799 + } + ], + "span": { + "offset": 1217, + "length": 11 + }, + "confidence": 0.993 + }, + { + "content": "technologies", + "polygon": [ + { + "x": 3.5236, + "y": 5.967 + }, + { + "x": 4.6389, + "y": 5.967 + }, + { + "x": 4.644, + "y": 6.1749 + }, + { + "x": 3.5236, + "y": 6.1799 + } + ], + "span": { + "offset": 1229, + "length": 12 + }, + "confidence": 0.991 + }, + { + "content": "are", + "polygon": [ + { + "x": 4.6795, + "y": 5.967 + }, + { + "x": 4.9533, + "y": 5.967 + }, + { + "x": 4.9533, + "y": 6.1698 + }, + { + "x": 4.6846, + "y": 6.1749 + } + ], + "span": { + "offset": 1242, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "not", + "polygon": [ + { + "x": 5.004, + "y": 5.967 + }, + { + "x": 5.3031, + "y": 5.962 + }, + { + "x": 5.3031, + "y": 6.1698 + }, + { + "x": 5.009, + "y": 6.1698 + } + ], + "span": { + "offset": 1246, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "standardized", + "polygon": [ + { + "x": 5.3436, + "y": 5.962 + }, + { + "x": 6.4489, + "y": 5.962 + }, + { + "x": 6.4489, + "y": 6.1597 + }, + { + "x": 5.3436, + "y": 6.1698 + } + ], + "span": { + "offset": 1250, + "length": 12 + }, + "confidence": 0.992 + }, + { + "content": "and", + "polygon": [ + { + "x": 6.5148, + "y": 5.962 + }, + { + "x": 6.824, + "y": 5.962 + }, + { + "x": 6.8291, + "y": 6.1546 + }, + { + "x": 6.5199, + "y": 6.1546 + } + ], + "span": { + "offset": 1263, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "their", + "polygon": [ + { + "x": 6.8798, + "y": 5.962 + }, + { + "x": 7.2702, + "y": 5.962 + }, + { + "x": 7.2753, + "y": 6.1495 + }, + { + "x": 6.8798, + "y": 6.1495 + } + ], + "span": { + "offset": 1267, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "specification", + "polygon": [ + { + "x": 0.7757, + "y": 6.2104 + }, + { + "x": 1.8302, + "y": 6.2002 + }, + { + "x": 1.8353, + "y": 6.4132 + }, + { + "x": 0.7808, + "y": 6.4132 + } + ], + "span": { + "offset": 1273, + "length": 13 + }, + "confidence": 0.989 + }, + { + "content": "is", + "polygon": [ + { + "x": 1.886, + "y": 6.2002 + }, + { + "x": 2.0482, + "y": 6.2002 + }, + { + "x": 2.0482, + "y": 6.4132 + }, + { + "x": 1.886, + "y": 6.4132 + } + ], + "span": { + "offset": 1287, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "published", + "polygon": [ + { + "x": 2.0888, + "y": 6.2002 + }, + { + "x": 2.9253, + "y": 6.2002 + }, + { + "x": 2.9253, + "y": 6.4132 + }, + { + "x": 2.0888, + "y": 6.4132 + } + ], + "span": { + "offset": 1290, + "length": 9 + }, + "confidence": 0.993 + }, + { + "content": "only", + "polygon": [ + { + "x": 2.9811, + "y": 6.2002 + }, + { + "x": 3.341, + "y": 6.2002 + }, + { + "x": 3.3461, + "y": 6.4132 + }, + { + "x": 2.9811, + "y": 6.4132 + } + ], + "span": { + "offset": 1300, + "length": 4 + }, + "confidence": 0.983 + }, + { + "content": "on", + "polygon": [ + { + "x": 3.3816, + "y": 6.2002 + }, + { + "x": 3.5996, + "y": 6.1952 + }, + { + "x": 3.5996, + "y": 6.4132 + }, + { + "x": 3.3867, + "y": 6.4132 + } + ], + "span": { + "offset": 1305, + "length": 2 + }, + "confidence": 0.991 + }, + { + "content": "Adobe's", + "polygon": [ + { + "x": 3.6554, + "y": 6.1952 + }, + { + "x": 4.355, + "y": 6.1952 + }, + { + "x": 4.3601, + "y": 6.4081 + }, + { + "x": 3.6554, + "y": 6.4132 + } + ], + "span": { + "offset": 1308, + "length": 7 + }, + "confidence": 0.968 + }, + { + "content": "website.", + "polygon": [ + { + "x": 4.3956, + "y": 6.1952 + }, + { + "x": 5.1256, + "y": 6.2002 + }, + { + "x": 5.1256, + "y": 6.4081 + }, + { + "x": 4.3956, + "y": 6.4081 + } + ], + "span": { + "offset": 1316, + "length": 8 + }, + "confidence": 0.993 + }, + { + "content": "Many", + "polygon": [ + { + "x": 5.1662, + "y": 6.2002 + }, + { + "x": 5.6681, + "y": 6.2002 + }, + { + "x": 5.6681, + "y": 6.403 + }, + { + "x": 5.1662, + "y": 6.4081 + } + ], + "span": { + "offset": 1325, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "of", + "polygon": [ + { + "x": 5.7087, + "y": 6.2002 + }, + { + "x": 5.8709, + "y": 6.2002 + }, + { + "x": 5.8709, + "y": 6.403 + }, + { + "x": 5.7087, + "y": 6.403 + } + ], + "span": { + "offset": 1330, + "length": 2 + }, + "confidence": 0.997 + }, + { + "content": "them", + "polygon": [ + { + "x": 5.9115, + "y": 6.2002 + }, + { + "x": 6.2866, + "y": 6.2002 + }, + { + "x": 6.2866, + "y": 6.403 + }, + { + "x": 5.9115, + "y": 6.403 + } + ], + "span": { + "offset": 1333, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "are", + "polygon": [ + { + "x": 6.4083, + "y": 6.2002 + }, + { + "x": 6.6922, + "y": 6.2053 + }, + { + "x": 6.6922, + "y": 6.3979 + }, + { + "x": 6.4083, + "y": 6.403 + } + ], + "span": { + "offset": 1338, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "also", + "polygon": [ + { + "x": 6.748, + "y": 6.2053 + }, + { + "x": 7.0978, + "y": 6.2053 + }, + { + "x": 7.0978, + "y": 6.3979 + }, + { + "x": 6.748, + "y": 6.3979 + } + ], + "span": { + "offset": 1342, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "not", + "polygon": [ + { + "x": 7.1384, + "y": 6.2053 + }, + { + "x": 7.4375, + "y": 6.2104 + }, + { + "x": 7.4375, + "y": 6.3979 + }, + { + "x": 7.1384, + "y": 6.3979 + } + ], + "span": { + "offset": 1347, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "supported", + "polygon": [ + { + "x": 0.7706, + "y": 6.4486 + }, + { + "x": 1.6376, + "y": 6.4436 + }, + { + "x": 1.6376, + "y": 6.6514 + }, + { + "x": 0.7706, + "y": 6.6514 + } + ], + "span": { + "offset": 1351, + "length": 9 + }, + "confidence": 0.993 + }, + { + "content": "by", + "polygon": [ + { + "x": 1.6781, + "y": 6.4436 + }, + { + "x": 1.9063, + "y": 6.4385 + }, + { + "x": 1.9063, + "y": 6.6514 + }, + { + "x": 1.6781, + "y": 6.6514 + } + ], + "span": { + "offset": 1361, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "popular", + "polygon": [ + { + "x": 1.9468, + "y": 6.4385 + }, + { + "x": 2.611, + "y": 6.4385 + }, + { + "x": 2.611, + "y": 6.6514 + }, + { + "x": 1.9468, + "y": 6.6514 + } + ], + "span": { + "offset": 1364, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "third-party", + "polygon": [ + { + "x": 2.6515, + "y": 6.4385 + }, + { + "x": 3.5286, + "y": 6.4334 + }, + { + "x": 3.5286, + "y": 6.6464 + }, + { + "x": 2.6515, + "y": 6.6514 + } + ], + "span": { + "offset": 1372, + "length": 11 + }, + "confidence": 0.984 + }, + { + "content": "implementations", + "polygon": [ + { + "x": 3.5692, + "y": 6.4334 + }, + { + "x": 5.0192, + "y": 6.4334 + }, + { + "x": 5.0192, + "y": 6.6362 + }, + { + "x": 3.5692, + "y": 6.6464 + } + ], + "span": { + "offset": 1384, + "length": 15 + }, + "confidence": 0.989 + }, + { + "content": "of", + "polygon": [ + { + "x": 5.0597, + "y": 6.4334 + }, + { + "x": 5.2321, + "y": 6.4334 + }, + { + "x": 5.2321, + "y": 6.6311 + }, + { + "x": 5.0597, + "y": 6.6362 + } + ], + "span": { + "offset": 1400, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "PDF.", + "polygon": [ + { + "x": 5.2727, + "y": 6.4334 + }, + { + "x": 5.6985, + "y": 6.4385 + }, + { + "x": 5.6985, + "y": 6.6261 + }, + { + "x": 5.2727, + "y": 6.6311 + } + ], + "span": { + "offset": 1403, + "length": 4 + }, + "confidence": 0.979 + }, + { + "content": "Column", + "polygon": [ + { + "x": 2.5147, + "y": 7.128 + }, + { + "x": 3.0166, + "y": 7.128 + }, + { + "x": 3.0166, + "y": 7.2699 + }, + { + "x": 2.5147, + "y": 7.2699 + } + ], + "span": { + "offset": 1408, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "1", + "polygon": [ + { + "x": 3.0825, + "y": 7.128 + }, + { + "x": 3.1484, + "y": 7.128 + }, + { + "x": 3.1484, + "y": 7.2699 + }, + { + "x": 3.0825, + "y": 7.2699 + } + ], + "span": { + "offset": 1415, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "Column", + "polygon": [ + { + "x": 4.1877, + "y": 7.1229 + }, + { + "x": 4.6795, + "y": 7.133 + }, + { + "x": 4.6795, + "y": 7.2649 + }, + { + "x": 4.1877, + "y": 7.2699 + } + ], + "span": { + "offset": 1417, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "2", + "polygon": [ + { + "x": 4.7403, + "y": 7.133 + }, + { + "x": 4.8113, + "y": 7.133 + }, + { + "x": 4.8164, + "y": 7.2649 + }, + { + "x": 4.7454, + "y": 7.2649 + } + ], + "span": { + "offset": 1424, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "Column", + "polygon": [ + { + "x": 5.8557, + "y": 7.1178 + }, + { + "x": 6.3576, + "y": 7.1178 + }, + { + "x": 6.3576, + "y": 7.2851 + }, + { + "x": 5.8506, + "y": 7.2801 + } + ], + "span": { + "offset": 1426, + "length": 6 + }, + "confidence": 0.993 + }, + { + "content": "3", + "polygon": [ + { + "x": 6.4134, + "y": 7.1178 + }, + { + "x": 6.4996, + "y": 7.1178 + }, + { + "x": 6.5046, + "y": 7.2851 + }, + { + "x": 6.4134, + "y": 7.2851 + } + ], + "span": { + "offset": 1433, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "A", + "polygon": [ + { + "x": 0.8467, + "y": 7.4524 + }, + { + "x": 0.9126, + "y": 7.4524 + }, + { + "x": 0.9176, + "y": 7.5741 + }, + { + "x": 0.8517, + "y": 7.5741 + } + ], + "span": { + "offset": 1435, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "324", + "polygon": [ + { + "x": 3.843, + "y": 7.4474 + }, + { + "x": 4.066, + "y": 7.4423 + }, + { + "x": 4.0711, + "y": 7.5843 + }, + { + "x": 3.843, + "y": 7.5893 + } + ], + "span": { + "offset": 1437, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "55", + "polygon": [ + { + "x": 4.1776, + "y": 7.4423 + }, + { + "x": 4.3246, + "y": 7.4474 + }, + { + "x": 4.3297, + "y": 7.5944 + }, + { + "x": 4.1826, + "y": 7.5944 + } + ], + "span": { + "offset": 1441, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "million", + "polygon": [ + { + "x": 4.3601, + "y": 7.4474 + }, + { + "x": 4.7707, + "y": 7.4524 + }, + { + "x": 4.7707, + "y": 7.5893 + }, + { + "x": 4.3652, + "y": 7.5944 + } + ], + "span": { + "offset": 1444, + "length": 7 + }, + "confidence": 0.993 + }, + { + "content": "units", + "polygon": [ + { + "x": 4.8164, + "y": 7.4524 + }, + { + "x": 5.1206, + "y": 7.4524 + }, + { + "x": 5.1206, + "y": 7.5893 + }, + { + "x": 4.8164, + "y": 7.5893 + } + ], + "span": { + "offset": 1452, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "2022", + "polygon": [ + { + "x": 7.113, + "y": 7.4524 + }, + { + "x": 7.4172, + "y": 7.4524 + }, + { + "x": 7.4122, + "y": 7.5792 + }, + { + "x": 7.108, + "y": 7.5792 + } + ], + "span": { + "offset": 1458, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "B", + "polygon": [ + { + "x": 0.8467, + "y": 7.7668 + }, + { + "x": 0.9126, + "y": 7.7668 + }, + { + "x": 0.9075, + "y": 7.8884 + }, + { + "x": 0.8467, + "y": 7.8834 + } + ], + "span": { + "offset": 1463, + "length": 1 + }, + "confidence": 0.996 + }, + { + "content": "234,523.00", + "polygon": [ + { + "x": 2.5147, + "y": 7.7668 + }, + { + "x": 3.1991, + "y": 7.7617 + }, + { + "x": 3.2042, + "y": 7.9036 + }, + { + "x": 2.5147, + "y": 7.9036 + } + ], + "span": { + "offset": 1465, + "length": 10 + }, + "confidence": 0.993 + }, + { + "content": "The", + "polygon": [ + { + "x": 4.1877, + "y": 7.7566 + }, + { + "x": 4.4108, + "y": 7.7617 + }, + { + "x": 4.4108, + "y": 7.9138 + }, + { + "x": 4.1928, + "y": 7.9138 + } + ], + "span": { + "offset": 1476, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "quick", + "polygon": [ + { + "x": 4.4513, + "y": 7.7617 + }, + { + "x": 4.791, + "y": 7.7617 + }, + { + "x": 4.7961, + "y": 7.9138 + }, + { + "x": 4.4513, + "y": 7.9138 + } + ], + "span": { + "offset": 1480, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "brown", + "polygon": [ + { + "x": 4.8214, + "y": 7.7617 + }, + { + "x": 5.2169, + "y": 7.7617 + }, + { + "x": 5.2169, + "y": 7.9138 + }, + { + "x": 4.8265, + "y": 7.9138 + } + ], + "span": { + "offset": 1486, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "fox", + "polygon": [ + { + "x": 5.2575, + "y": 7.7617 + }, + { + "x": 5.4653, + "y": 7.7566 + }, + { + "x": 5.4704, + "y": 7.9188 + }, + { + "x": 5.2575, + "y": 7.9138 + } + ], + "span": { + "offset": 1492, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "jumped", + "polygon": [ + { + "x": 4.1674, + "y": 7.9341 + }, + { + "x": 4.6389, + "y": 7.9341 + }, + { + "x": 4.644, + "y": 8.0912 + }, + { + "x": 4.1725, + "y": 8.0912 + } + ], + "span": { + "offset": 1496, + "length": 6 + }, + "confidence": 0.993 + }, + { + "content": "over", + "polygon": [ + { + "x": 4.6795, + "y": 7.9341 + }, + { + "x": 4.9533, + "y": 7.9341 + }, + { + "x": 4.9583, + "y": 8.0912 + }, + { + "x": 4.6846, + "y": 8.0912 + } + ], + "span": { + "offset": 1503, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "the", + "polygon": [ + { + "x": 4.9837, + "y": 7.9341 + }, + { + "x": 5.1865, + "y": 7.9341 + }, + { + "x": 5.1865, + "y": 8.0912 + }, + { + "x": 4.9888, + "y": 8.0912 + } + ], + "span": { + "offset": 1508, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "lazy", + "polygon": [ + { + "x": 5.2169, + "y": 7.9341 + }, + { + "x": 5.4755, + "y": 7.9341 + }, + { + "x": 5.4755, + "y": 8.0912 + }, + { + "x": 5.2169, + "y": 8.0912 + } + ], + "span": { + "offset": 1512, + "length": 4 + }, + "confidence": 0.992 + }, + { + "content": "dog.", + "polygon": [ + { + "x": 4.1776, + "y": 8.1014 + }, + { + "x": 4.4666, + "y": 8.1014 + }, + { + "x": 4.4666, + "y": 8.2433 + }, + { + "x": 4.1776, + "y": 8.2382 + } + ], + "span": { + "offset": 1517, + "length": 4 + }, + "confidence": 0.99 + }, + { + "content": "54x", + "polygon": [ + { + "x": 5.8456, + "y": 7.7668 + }, + { + "x": 6.0838, + "y": 7.7718 + }, + { + "x": 6.0889, + "y": 7.9138 + }, + { + "x": 5.8506, + "y": 7.9138 + } + ], + "span": { + "offset": 1522, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "growth", + "polygon": [ + { + "x": 6.1143, + "y": 7.7718 + }, + { + "x": 6.5401, + "y": 7.7668 + }, + { + "x": 6.5401, + "y": 7.9188 + }, + { + "x": 6.1193, + "y": 7.9138 + } + ], + "span": { + "offset": 1526, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "C", + "polygon": [ + { + "x": 0.8467, + "y": 8.365 + }, + { + "x": 0.9227, + "y": 8.365 + }, + { + "x": 0.9227, + "y": 8.5069 + }, + { + "x": 0.8467, + "y": 8.5019 + } + ], + "span": { + "offset": 1533, + "length": 1 + }, + "confidence": 0.945 + }, + { + "content": "23.53%", + "polygon": [ + { + "x": 2.5096, + "y": 8.3396 + }, + { + "x": 2.9963, + "y": 8.3396 + }, + { + "x": 2.9963, + "y": 8.512 + }, + { + "x": 2.5096, + "y": 8.5171 + } + ], + "span": { + "offset": 1535, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "A", + "polygon": [ + { + "x": 4.1826, + "y": 8.3701 + }, + { + "x": 4.2638, + "y": 8.3701 + }, + { + "x": 4.2638, + "y": 8.5221 + }, + { + "x": 4.1877, + "y": 8.5272 + } + ], + "span": { + "offset": 1542, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "short", + "polygon": [ + { + "x": 4.3145, + "y": 8.3701 + }, + { + "x": 4.6389, + "y": 8.3751 + }, + { + "x": 4.6389, + "y": 8.5221 + }, + { + "x": 4.3145, + "y": 8.5221 + } + ], + "span": { + "offset": 1544, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "string.", + "polygon": [ + { + "x": 4.6643, + "y": 8.3751 + }, + { + "x": 5.0597, + "y": 8.3853 + }, + { + "x": 5.0597, + "y": 8.5272 + }, + { + "x": 4.6694, + "y": 8.5272 + } + ], + "span": { + "offset": 1550, + "length": 7 + }, + "confidence": 0.995 + }, + { + "content": "D", + "polygon": [ + { + "x": 0.8416, + "y": 8.6945 + }, + { + "x": 0.9176, + "y": 8.6945 + }, + { + "x": 0.9126, + "y": 8.8213 + }, + { + "x": 0.8416, + "y": 8.8162 + } + ], + "span": { + "offset": 1558, + "length": 1 + }, + "confidence": 0.972 + }, + { + "content": "$54.35", + "polygon": [ + { + "x": 2.4994, + "y": 8.6945 + }, + { + "x": 2.9355, + "y": 8.6894 + }, + { + "x": 2.9355, + "y": 8.8314 + }, + { + "x": 2.5096, + "y": 8.8314 + } + ], + "span": { + "offset": 1560, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "$6345.", + "polygon": [ + { + "x": 4.1826, + "y": 8.6894 + }, + { + "x": 4.6085, + "y": 8.6945 + }, + { + "x": 4.6136, + "y": 8.8365 + }, + { + "x": 4.1877, + "y": 8.8314 + } + ], + "span": { + "offset": 1567, + "length": 6 + }, + "confidence": 0.993 + } + ], + "selection_marks": [], + "spans": [ + { + "offset": 0, + "length": 1573 + } + ], + "kind": "document", + "annotations": [], + "barcodes": [], + "formulas": [], + "images": [] + }, + { + "page_number": 2, + "angle": -0.17829999327659607, + "width": 8.2639, + "height": 11.6806, + "unit": "inch", + "lines": [ + { + "content": "Page 2 of Sample PDF", + "polygon": [ + { + "x": 0.7808, + "y": 0.8365 + }, + { + "x": 4.0356, + "y": 0.8264 + }, + { + "x": 4.0407, + "y": 1.1508 + }, + { + "x": 0.7808, + "y": 1.161 + } + ], + "spans": [ + { + "offset": 1574, + "length": 20 + } + ] + } + ], + "words": [ + { + "content": "Page", + "polygon": [ + { + "x": 0.7909, + "y": 0.8416 + }, + { + "x": 1.5058, + "y": 0.8365 + }, + { + "x": 1.5007, + "y": 1.161 + }, + { + "x": 0.7808, + "y": 1.1559 + } + ], + "span": { + "offset": 1574, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "2", + "polygon": [ + { + "x": 1.6325, + "y": 0.8365 + }, + { + "x": 1.7998, + "y": 0.8365 + }, + { + "x": 1.7998, + "y": 1.161 + }, + { + "x": 1.6274, + "y": 1.161 + } + ], + "span": { + "offset": 1579, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "of", + "polygon": [ + { + "x": 1.8657, + "y": 0.8365 + }, + { + "x": 2.18, + "y": 0.8365 + }, + { + "x": 2.18, + "y": 1.161 + }, + { + "x": 1.8606, + "y": 1.161 + } + ], + "span": { + "offset": 1581, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "Sample", + "polygon": [ + { + "x": 2.246, + "y": 0.8365 + }, + { + "x": 3.3258, + "y": 0.8314 + }, + { + "x": 3.3309, + "y": 1.1559 + }, + { + "x": 2.246, + "y": 1.161 + } + ], + "span": { + "offset": 1584, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 3.412, + "y": 0.8314 + }, + { + "x": 4.0052, + "y": 0.8314 + }, + { + "x": 4.0103, + "y": 1.1457 + }, + { + "x": 3.4171, + "y": 1.1559 + } + ], + "span": { + "offset": 1591, + "length": 3 + }, + "confidence": 0.995 + } + ], + "selection_marks": [], + "spans": [ + { + "offset": 1574, + "length": 20 + } + ], + "kind": "document", + "annotations": [], + "barcodes": [], + "formulas": [], + "images": [] + }, + { + "page_number": 3, + "angle": null, + "width": 8.2639, + "height": 11.6806, + "unit": "inch", + "lines": [], + "words": [], + "selection_marks": [], + "spans": [ + { + "offset": 1595, + "length": 0 + } + ], + "kind": "document", + "annotations": [], + "barcodes": [], + "formulas": [], + "images": [] + }, + { + "page_number": 4, + "angle": -0.13539999723434448, + "width": 8.2639, + "height": 11.6806, + "unit": "inch", + "lines": [ + { + "content": "Page 4 of Sample PDF", + "polygon": [ + { + "x": 0.7808, + "y": 0.8416 + }, + { + "x": 4.0356, + "y": 0.8264 + }, + { + "x": 4.0356, + "y": 1.1508 + }, + { + "x": 0.7808, + "y": 1.161 + } + ], + "spans": [ + { + "offset": 1596, + "length": 20 + } + ] + }, + { + "content": "... the page 3 is empty.", + "polygon": [ + { + "x": 0.7858, + "y": 1.5513 + }, + { + "x": 2.9304, + "y": 1.5463 + }, + { + "x": 2.9304, + "y": 1.7744 + }, + { + "x": 0.7858, + "y": 1.7795 + } + ], + "spans": [ + { + "offset": 1617, + "length": 24 + } + ] + } + ], + "words": [ + { + "content": "Page", + "polygon": [ + { + "x": 0.7909, + "y": 0.8466 + }, + { + "x": 1.5159, + "y": 0.8416 + }, + { + "x": 1.5108, + "y": 1.161 + }, + { + "x": 0.7808, + "y": 1.1508 + } + ], + "span": { + "offset": 1596, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "4", + "polygon": [ + { + "x": 1.597, + "y": 0.8416 + }, + { + "x": 1.7643, + "y": 0.8416 + }, + { + "x": 1.7592, + "y": 1.161 + }, + { + "x": 1.5919, + "y": 1.161 + } + ], + "span": { + "offset": 1601, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "of", + "polygon": [ + { + "x": 1.8708, + "y": 0.8416 + }, + { + "x": 2.18, + "y": 0.8416 + }, + { + "x": 2.18, + "y": 1.161 + }, + { + "x": 1.8657, + "y": 1.161 + } + ], + "span": { + "offset": 1603, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "Sample", + "polygon": [ + { + "x": 2.246, + "y": 0.8416 + }, + { + "x": 3.3106, + "y": 0.8365 + }, + { + "x": 3.3106, + "y": 1.1559 + }, + { + "x": 2.2409, + "y": 1.161 + } + ], + "span": { + "offset": 1606, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 3.412, + "y": 0.8314 + }, + { + "x": 3.9951, + "y": 0.8314 + }, + { + "x": 4.0001, + "y": 1.1407 + }, + { + "x": 3.412, + "y": 1.1559 + } + ], + "span": { + "offset": 1613, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "...", + "polygon": [ + { + "x": 0.7858, + "y": 1.5817 + }, + { + "x": 0.9836, + "y": 1.5716 + }, + { + "x": 0.9937, + "y": 1.7795 + }, + { + "x": 0.796, + "y": 1.7795 + } + ], + "span": { + "offset": 1617, + "length": 3 + }, + "confidence": 0.989 + }, + { + "content": "the", + "polygon": [ + { + "x": 1.0292, + "y": 1.5665 + }, + { + "x": 1.3283, + "y": 1.5564 + }, + { + "x": 1.3334, + "y": 1.7744 + }, + { + "x": 1.0343, + "y": 1.7795 + } + ], + "span": { + "offset": 1621, + "length": 3 + }, + "confidence": 0.994 + }, + { + "content": "page", + "polygon": [ + { + "x": 1.3891, + "y": 1.5564 + }, + { + "x": 1.8606, + "y": 1.5513 + }, + { + "x": 1.8657, + "y": 1.7744 + }, + { + "x": 1.3942, + "y": 1.7744 + } + ], + "span": { + "offset": 1625, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "3", + "polygon": [ + { + "x": 1.9367, + "y": 1.5463 + }, + { + "x": 2.033, + "y": 1.5463 + }, + { + "x": 2.0381, + "y": 1.7744 + }, + { + "x": 1.9367, + "y": 1.7744 + } + ], + "span": { + "offset": 1630, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "is", + "polygon": [ + { + "x": 2.0786, + "y": 1.5463 + }, + { + "x": 2.2662, + "y": 1.5513 + }, + { + "x": 2.2662, + "y": 1.7744 + }, + { + "x": 2.0786, + "y": 1.7744 + } + ], + "span": { + "offset": 1632, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "empty.", + "polygon": [ + { + "x": 2.3068, + "y": 1.5513 + }, + { + "x": 2.9304, + "y": 1.5665 + }, + { + "x": 2.9304, + "y": 1.7795 + }, + { + "x": 2.3119, + "y": 1.7744 + } + ], + "span": { + "offset": 1635, + "length": 6 + }, + "confidence": 0.994 + } + ], + "selection_marks": [], + "spans": [ + { + "offset": 1596, + "length": 45 + } + ], + "kind": "document", + "annotations": [], + "barcodes": [], + "formulas": [], + "images": [] + } + ], + "paragraphs": [ + { + "role": "title", + "content": "A sample PDF file", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7573, + "y": 0.8365 + }, + { + "x": 3.5914, + "y": 0.8112 + }, + { + "x": 3.5945, + "y": 1.166 + }, + { + "x": 0.7605, + "y": 1.1914 + } + ] + } + ], + "spans": [ + { + "offset": 0, + "length": 17 + } + ] + }, + { + "role": "sectionHeading", + "content": "History and standardization", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7706, + "y": 1.7136 + }, + { + "x": 3.1433, + "y": 1.7136 + }, + { + "x": 3.1433, + "y": 1.9316 + }, + { + "x": 0.7706, + "y": 1.9316 + } + ] + } + ], + "spans": [ + { + "offset": 18, + "length": 27 + } + ] + }, + { + "role": null, + "content": "Format (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.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7605, + "y": 2.18 + }, + { + "x": 7.4781, + "y": 2.18 + }, + { + "x": 7.4781, + "y": 6.6514 + }, + { + "x": 0.7605, + "y": 6.6514 + } + ] + } + ], + "spans": [ + { + "offset": 46, + "length": 1361 + } + ] + }, + { + "role": null, + "content": "Column 1", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 7.0624 + }, + { + "x": 4.1287, + "y": 7.0624 + }, + { + "x": 4.1287, + "y": 7.3715 + }, + { + "x": 2.4575, + "y": 7.3715 + } + ] + } + ], + "spans": [ + { + "offset": 1408, + "length": 8 + } + ] + }, + { + "role": null, + "content": "Column 2", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 7.0624 + }, + { + "x": 5.7998, + "y": 7.0555 + }, + { + "x": 5.7998, + "y": 7.3715 + }, + { + "x": 4.1287, + "y": 7.3715 + } + ] + } + ], + "spans": [ + { + "offset": 1417, + "length": 8 + } + ] + }, + { + "role": null, + "content": "Column 3", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 7.0555 + }, + { + "x": 7.4709, + "y": 7.0555 + }, + { + "x": 7.4709, + "y": 7.3715 + }, + { + "x": 5.7998, + "y": 7.3715 + } + ] + } + ], + "spans": [ + { + "offset": 1426, + "length": 8 + } + ] + }, + { + "role": null, + "content": "A", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 7.3715 + }, + { + "x": 2.4575, + "y": 7.3715 + }, + { + "x": 2.4575, + "y": 7.6875 + }, + { + "x": 0.7864, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1435, + "length": 1 + } + ] + }, + { + "role": null, + "content": "324", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 7.3715 + }, + { + "x": 4.1287, + "y": 7.3715 + }, + { + "x": 4.1287, + "y": 7.6875 + }, + { + "x": 2.4575, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1437, + "length": 3 + } + ] + }, + { + "role": null, + "content": "55 million units", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 7.3715 + }, + { + "x": 5.7998, + "y": 7.3715 + }, + { + "x": 5.7998, + "y": 7.6875 + }, + { + "x": 4.1287, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1441, + "length": 16 + } + ] + }, + { + "role": null, + "content": "2022", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 7.3715 + }, + { + "x": 7.4709, + "y": 7.3715 + }, + { + "x": 7.4709, + "y": 7.6875 + }, + { + "x": 5.7998, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1458, + "length": 4 + } + ] + }, + { + "role": null, + "content": "B", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 7.6875 + }, + { + "x": 2.4575, + "y": 7.6875 + }, + { + "x": 2.4575, + "y": 8.292 + }, + { + "x": 0.7864, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1463, + "length": 1 + } + ] + }, + { + "role": null, + "content": "234,523.00", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 7.6875 + }, + { + "x": 4.1287, + "y": 7.6875 + }, + { + "x": 4.1287, + "y": 8.292 + }, + { + "x": 2.4575, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1465, + "length": 10 + } + ] + }, + { + "role": null, + "content": "The quick brown fox jumped over the lazy dog.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 7.6875 + }, + { + "x": 5.7998, + "y": 7.6875 + }, + { + "x": 5.7998, + "y": 8.292 + }, + { + "x": 4.1287, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1476, + "length": 45 + } + ] + }, + { + "role": null, + "content": "54x growth", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 7.6875 + }, + { + "x": 7.4709, + "y": 7.6875 + }, + { + "x": 7.4709, + "y": 8.2989 + }, + { + "x": 5.7998, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1522, + "length": 10 + } + ] + }, + { + "role": null, + "content": "C", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 8.292 + }, + { + "x": 2.4575, + "y": 8.292 + }, + { + "x": 2.4575, + "y": 8.6148 + }, + { + "x": 0.7864, + "y": 8.6148 + } + ] + } + ], + "spans": [ + { + "offset": 1533, + "length": 1 + } + ] + }, + { + "role": null, + "content": "23.53%", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 8.292 + }, + { + "x": 4.1287, + "y": 8.292 + }, + { + "x": 4.1287, + "y": 8.6148 + }, + { + "x": 2.4575, + "y": 8.6148 + } + ] + } + ], + "spans": [ + { + "offset": 1535, + "length": 6 + } + ] + }, + { + "role": null, + "content": "A short string.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 8.292 + }, + { + "x": 5.7998, + "y": 8.292 + }, + { + "x": 5.7998, + "y": 8.6217 + }, + { + "x": 4.1287, + "y": 8.6148 + } + ] + } + ], + "spans": [ + { + "offset": 1542, + "length": 15 + } + ] + }, + { + "role": null, + "content": "D", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 8.6148 + }, + { + "x": 2.4575, + "y": 8.6148 + }, + { + "x": 2.4575, + "y": 8.9308 + }, + { + "x": 0.7864, + "y": 8.9308 + } + ] + } + ], + "spans": [ + { + "offset": 1558, + "length": 1 + } + ] + }, + { + "role": null, + "content": "$54.35", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 8.6148 + }, + { + "x": 4.1287, + "y": 8.6148 + }, + { + "x": 4.1287, + "y": 8.9377 + }, + { + "x": 2.4575, + "y": 8.9308 + } + ] + } + ], + "spans": [ + { + "offset": 1560, + "length": 6 + } + ] + }, + { + "role": null, + "content": "$6345.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 8.6148 + }, + { + "x": 5.7998, + "y": 8.6217 + }, + { + "x": 5.7998, + "y": 8.9377 + }, + { + "x": 4.1287, + "y": 8.9377 + } + ] + } + ], + "spans": [ + { + "offset": 1567, + "length": 6 + } + ] + }, + { + "role": "title", + "content": "Page 2 of Sample PDF", + "bounding_regions": [ + { + "page_number": 2, + "polygon": [ + { + "x": 0.7798, + "y": 0.8365 + }, + { + "x": 4.0397, + "y": 0.8263 + }, + { + "x": 4.0407, + "y": 1.1508 + }, + { + "x": 0.7808, + "y": 1.161 + } + ] + } + ], + "spans": [ + { + "offset": 1574, + "length": 20 + } + ] + }, + { + "role": "title", + "content": "Page 4 of Sample PDF", + "bounding_regions": [ + { + "page_number": 4, + "polygon": [ + { + "x": 0.7797, + "y": 0.8365 + }, + { + "x": 4.0356, + "y": 0.8264 + }, + { + "x": 4.0366, + "y": 1.1508 + }, + { + "x": 0.7808, + "y": 1.161 + } + ] + } + ], + "spans": [ + { + "offset": 1596, + "length": 20 + } + ] + }, + { + "role": null, + "content": "... the page 3 is empty.", + "bounding_regions": [ + { + "page_number": 4, + "polygon": [ + { + "x": 0.7853, + "y": 1.5513 + }, + { + "x": 2.9304, + "y": 1.5463 + }, + { + "x": 2.9309, + "y": 1.7744 + }, + { + "x": 0.7858, + "y": 1.7795 + } + ] + } + ], + "spans": [ + { + "offset": 1617, + "length": 24 + } + ] + } + ], + "tables": [ + { + "row_count": 5, + "column_count": 4, + "cells": [ + { + "kind": "columnHeader", + "row_index": 0, + "column_index": 0, + "row_span": 1, + "column_span": 1, + "content": "", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 7.0624 + }, + { + "x": 2.4575, + "y": 7.0624 + }, + { + "x": 2.4575, + "y": 7.3715 + }, + { + "x": 0.7864, + "y": 7.3715 + } + ] + } + ], + "spans": [] + }, + { + "kind": "columnHeader", + "row_index": 0, + "column_index": 1, + "row_span": 1, + "column_span": 1, + "content": "Column 1", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 7.0624 + }, + { + "x": 4.1287, + "y": 7.0624 + }, + { + "x": 4.1287, + "y": 7.3715 + }, + { + "x": 2.4575, + "y": 7.3715 + } + ] + } + ], + "spans": [ + { + "offset": 1408, + "length": 8 + } + ] + }, + { + "kind": "columnHeader", + "row_index": 0, + "column_index": 2, + "row_span": 1, + "column_span": 1, + "content": "Column 2", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 7.0624 + }, + { + "x": 5.7998, + "y": 7.0555 + }, + { + "x": 5.7998, + "y": 7.3715 + }, + { + "x": 4.1287, + "y": 7.3715 + } + ] + } + ], + "spans": [ + { + "offset": 1417, + "length": 8 + } + ] + }, + { + "kind": "columnHeader", + "row_index": 0, + "column_index": 3, + "row_span": 1, + "column_span": 1, + "content": "Column 3", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 7.0555 + }, + { + "x": 7.4709, + "y": 7.0555 + }, + { + "x": 7.4709, + "y": 7.3715 + }, + { + "x": 5.7998, + "y": 7.3715 + } + ] + } + ], + "spans": [ + { + "offset": 1426, + "length": 8 + } + ] + }, + { + "kind": "content", + "row_index": 1, + "column_index": 0, + "row_span": 1, + "column_span": 1, + "content": "A", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 7.3715 + }, + { + "x": 2.4575, + "y": 7.3715 + }, + { + "x": 2.4575, + "y": 7.6875 + }, + { + "x": 0.7864, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1435, + "length": 1 + } + ] + }, + { + "kind": "content", + "row_index": 1, + "column_index": 1, + "row_span": 1, + "column_span": 1, + "content": "324", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 7.3715 + }, + { + "x": 4.1287, + "y": 7.3715 + }, + { + "x": 4.1287, + "y": 7.6875 + }, + { + "x": 2.4575, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1437, + "length": 3 + } + ] + }, + { + "kind": "content", + "row_index": 1, + "column_index": 2, + "row_span": 1, + "column_span": 1, + "content": "55 million units", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 7.3715 + }, + { + "x": 5.7998, + "y": 7.3715 + }, + { + "x": 5.7998, + "y": 7.6875 + }, + { + "x": 4.1287, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1441, + "length": 16 + } + ] + }, + { + "kind": "content", + "row_index": 1, + "column_index": 3, + "row_span": 1, + "column_span": 1, + "content": "2022", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 7.3715 + }, + { + "x": 7.4709, + "y": 7.3715 + }, + { + "x": 7.4709, + "y": 7.6875 + }, + { + "x": 5.7998, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1458, + "length": 4 + } + ] + }, + { + "kind": "content", + "row_index": 2, + "column_index": 0, + "row_span": 1, + "column_span": 1, + "content": "B", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 7.6875 + }, + { + "x": 2.4575, + "y": 7.6875 + }, + { + "x": 2.4575, + "y": 8.292 + }, + { + "x": 0.7864, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1463, + "length": 1 + } + ] + }, + { + "kind": "content", + "row_index": 2, + "column_index": 1, + "row_span": 1, + "column_span": 1, + "content": "234,523.00", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 7.6875 + }, + { + "x": 4.1287, + "y": 7.6875 + }, + { + "x": 4.1287, + "y": 8.292 + }, + { + "x": 2.4575, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1465, + "length": 10 + } + ] + }, + { + "kind": "content", + "row_index": 2, + "column_index": 2, + "row_span": 1, + "column_span": 1, + "content": "The quick brown fox jumped over the lazy dog.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 7.6875 + }, + { + "x": 5.7998, + "y": 7.6875 + }, + { + "x": 5.7998, + "y": 8.292 + }, + { + "x": 4.1287, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1476, + "length": 45 + } + ] + }, + { + "kind": "content", + "row_index": 2, + "column_index": 3, + "row_span": 1, + "column_span": 1, + "content": "54x growth", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 7.6875 + }, + { + "x": 7.4709, + "y": 7.6875 + }, + { + "x": 7.4709, + "y": 8.2989 + }, + { + "x": 5.7998, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1522, + "length": 10 + } + ] + }, + { + "kind": "content", + "row_index": 3, + "column_index": 0, + "row_span": 1, + "column_span": 1, + "content": "C", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 8.292 + }, + { + "x": 2.4575, + "y": 8.292 + }, + { + "x": 2.4575, + "y": 8.6148 + }, + { + "x": 0.7864, + "y": 8.6148 + } + ] + } + ], + "spans": [ + { + "offset": 1533, + "length": 1 + } + ] + }, + { + "kind": "content", + "row_index": 3, + "column_index": 1, + "row_span": 1, + "column_span": 1, + "content": "23.53%", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 8.292 + }, + { + "x": 4.1287, + "y": 8.292 + }, + { + "x": 4.1287, + "y": 8.6148 + }, + { + "x": 2.4575, + "y": 8.6148 + } + ] + } + ], + "spans": [ + { + "offset": 1535, + "length": 6 + } + ] + }, + { + "kind": "content", + "row_index": 3, + "column_index": 2, + "row_span": 1, + "column_span": 1, + "content": "A short string.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 8.292 + }, + { + "x": 5.7998, + "y": 8.292 + }, + { + "x": 5.7998, + "y": 8.6217 + }, + { + "x": 4.1287, + "y": 8.6148 + } + ] + } + ], + "spans": [ + { + "offset": 1542, + "length": 15 + } + ] + }, + { + "kind": "content", + "row_index": 3, + "column_index": 3, + "row_span": 1, + "column_span": 1, + "content": "", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 8.292 + }, + { + "x": 7.4709, + "y": 8.2989 + }, + { + "x": 7.4709, + "y": 8.6217 + }, + { + "x": 5.7998, + "y": 8.6217 + } + ] + } + ], + "spans": [] + }, + { + "kind": "content", + "row_index": 4, + "column_index": 0, + "row_span": 1, + "column_span": 1, + "content": "D", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 8.6148 + }, + { + "x": 2.4575, + "y": 8.6148 + }, + { + "x": 2.4575, + "y": 8.9308 + }, + { + "x": 0.7864, + "y": 8.9308 + } + ] + } + ], + "spans": [ + { + "offset": 1558, + "length": 1 + } + ] + }, + { + "kind": "content", + "row_index": 4, + "column_index": 1, + "row_span": 1, + "column_span": 1, + "content": "$54.35", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 8.6148 + }, + { + "x": 4.1287, + "y": 8.6148 + }, + { + "x": 4.1287, + "y": 8.9377 + }, + { + "x": 2.4575, + "y": 8.9308 + } + ] + } + ], + "spans": [ + { + "offset": 1560, + "length": 6 + } + ] + }, + { + "kind": "content", + "row_index": 4, + "column_index": 2, + "row_span": 1, + "column_span": 1, + "content": "$6345.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 8.6148 + }, + { + "x": 5.7998, + "y": 8.6217 + }, + { + "x": 5.7998, + "y": 8.9377 + }, + { + "x": 4.1287, + "y": 8.9377 + } + ] + } + ], + "spans": [ + { + "offset": 1567, + "length": 6 + } + ] + }, + { + "kind": "content", + "row_index": 4, + "column_index": 3, + "row_span": 1, + "column_span": 1, + "content": "", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 8.6217 + }, + { + "x": 7.4709, + "y": 8.6217 + }, + { + "x": 7.4709, + "y": 8.9239 + }, + { + "x": 5.7998, + "y": 8.9377 + } + ] + } + ], + "spans": [] + } + ], + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7722, + "y": 7.0436 + }, + { + "x": 7.4799, + "y": 7.0502 + }, + { + "x": 7.4795, + "y": 8.9455 + }, + { + "x": 0.7713, + "y": 8.9388 + } + ] + } + ], + "spans": [ + { + "offset": 1408, + "length": 165 + } + ] + } + ], + "key_value_pairs": [], + "styles": [], + "documents": [] +} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/azure_sample_pdf_1_no_table_bounding_region.json b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/azure_sample_pdf_1_no_table_bounding_region.json new file mode 100644 index 0000000000000000000000000000000000000000..f06a9acc58b55dfd91caad7534a613e96fed6918 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/azure_sample_pdf_1_no_table_bounding_region.json @@ -0,0 +1,9600 @@ +{ + "api_version": "2023-02-28-preview", + "model_id": "prebuilt-document", + "content": "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.\nColumn 1\nColumn 2\nColumn 3\nA\n324\n55 million units\n2022\nB\n234,523.00\nThe quick brown fox jumped over the lazy dog.\n54x growth\nC\n23.53%\nA short string.\nD\n$54.35\n$6345.\nPage 2 of Sample PDF\n\nPage 4 of Sample PDF\n... the page 3 is empty.", + "languages": [], + "pages": [ + { + "page_number": 1, + "angle": null, + "width": 8.2639, + "height": 11.6806, + "unit": "inch", + "lines": [ + { + "content": "A sample PDF file", + "polygon": [ + { + "x": 0.7605, + "y": 0.8365 + }, + { + "x": 3.5895, + "y": 0.8314 + }, + { + "x": 3.5945, + "y": 1.166 + }, + { + "x": 0.7605, + "y": 1.1914 + } + ], + "spans": [ + { + "offset": 0, + "length": 17 + } + ] + }, + { + "content": "History and standardization", + "polygon": [ + { + "x": 0.7706, + "y": 1.7136 + }, + { + "x": 3.1433, + "y": 1.7136 + }, + { + "x": 3.1433, + "y": 1.9214 + }, + { + "x": 0.7706, + "y": 1.9316 + } + ], + "spans": [ + { + "offset": 18, + "length": 27 + } + ] + }, + { + "content": "Format (PDF) Adobe Systems made the PDF specification available free of", + "polygon": [ + { + "x": 0.7808, + "y": 2.18 + }, + { + "x": 7.255, + "y": 2.18 + }, + { + "x": 7.255, + "y": 2.3929 + }, + { + "x": 0.7808, + "y": 2.3929 + } + ], + "spans": [ + { + "offset": 46, + "length": 71 + } + ] + }, + { + "content": "charge in 1993. In the early years PDF was popular mainly in desktop", + "polygon": [ + { + "x": 0.7706, + "y": 2.4132 + }, + { + "x": 6.7733, + "y": 2.4132 + }, + { + "x": 6.7733, + "y": 2.6362 + }, + { + "x": 0.7706, + "y": 2.6312 + } + ], + "spans": [ + { + "offset": 118, + "length": 68 + } + ] + }, + { + "content": "publishing workflows, and competed with a variety of formats such as DjVu,", + "polygon": [ + { + "x": 0.7706, + "y": 2.6565 + }, + { + "x": 7.2601, + "y": 2.6565 + }, + { + "x": 7.2601, + "y": 2.8694 + }, + { + "x": 0.7706, + "y": 2.8745 + } + ], + "spans": [ + { + "offset": 187, + "length": 74 + } + ] + }, + { + "content": "Envoy, Common Ground Digital Paper, Farallon Replica and even Adobe's", + "polygon": [ + { + "x": 0.7656, + "y": 2.8897 + }, + { + "x": 7.1789, + "y": 2.8897 + }, + { + "x": 7.1789, + "y": 3.1077 + }, + { + "x": 0.7656, + "y": 3.1077 + } + ], + "spans": [ + { + "offset": 262, + "length": 69 + } + ] + }, + { + "content": "own PostScript format. PDF was a proprietary format controlled by Adobe", + "polygon": [ + { + "x": 0.7706, + "y": 3.128 + }, + { + "x": 7.0978, + "y": 3.1331 + }, + { + "x": 7.0978, + "y": 3.3409 + }, + { + "x": 0.7706, + "y": 3.3409 + } + ], + "spans": [ + { + "offset": 332, + "length": 71 + } + ] + }, + { + "content": "until it was released as an open standard on July 1, 2008, and published by", + "polygon": [ + { + "x": 0.7858, + "y": 3.3663 + }, + { + "x": 7.2702, + "y": 3.3713 + }, + { + "x": 7.2702, + "y": 3.5792 + }, + { + "x": 0.7808, + "y": 3.5691 + } + ], + "spans": [ + { + "offset": 404, + "length": 75 + } + ] + }, + { + "content": "the International Organization for Standardization as ISO 32000-1:2008, at", + "polygon": [ + { + "x": 0.7656, + "y": 3.5995 + }, + { + "x": 7.2043, + "y": 3.5944 + }, + { + "x": 7.2043, + "y": 3.8023 + }, + { + "x": 0.7656, + "y": 3.8023 + } + ], + "spans": [ + { + "offset": 480, + "length": 74 + } + ] + }, + { + "content": "which time control of the specification passed to an ISO Committee of", + "polygon": [ + { + "x": 0.7757, + "y": 3.8327 + }, + { + "x": 6.7784, + "y": 3.8327 + }, + { + "x": 6.7784, + "y": 4.0355 + }, + { + "x": 0.7757, + "y": 4.0456 + } + ], + "spans": [ + { + "offset": 555, + "length": 69 + } + ] + }, + { + "content": "volunteer industry experts. In 2008, Adobe published a Public Patent License", + "polygon": [ + { + "x": 0.7656, + "y": 4.071 + }, + { + "x": 7.402, + "y": 4.0659 + }, + { + "x": 7.402, + "y": 4.2737 + }, + { + "x": 0.7706, + "y": 4.2839 + } + ], + "spans": [ + { + "offset": 625, + "length": 76 + } + ] + }, + { + "content": "to ISO 32000-1 granting royalty-free rights for all patents owned by Adobe", + "polygon": [ + { + "x": 0.7808, + "y": 4.3092 + }, + { + "x": 7.1232, + "y": 4.3092 + }, + { + "x": 7.1232, + "y": 4.5272 + }, + { + "x": 0.7808, + "y": 4.5222 + } + ], + "spans": [ + { + "offset": 702, + "length": 74 + } + ] + }, + { + "content": "that are necessary to make, use, sell, and distribute PDF-compliant", + "polygon": [ + { + "x": 0.7605, + "y": 4.5475 + }, + { + "x": 6.5655, + "y": 4.5475 + }, + { + "x": 6.5655, + "y": 4.7554 + }, + { + "x": 0.7605, + "y": 4.7604 + } + ], + "spans": [ + { + "offset": 777, + "length": 67 + } + ] + }, + { + "content": "implementations. PDF 1.7, the sixth edition of the PDF specification that", + "polygon": [ + { + "x": 0.7656, + "y": 4.7807 + }, + { + "x": 6.9761, + "y": 4.7807 + }, + { + "x": 6.9761, + "y": 4.9886 + }, + { + "x": 0.7656, + "y": 4.9886 + } + ], + "spans": [ + { + "offset": 845, + "length": 73 + } + ] + }, + { + "content": "became ISO 32000-1, includes some proprietary technologies defined only by", + "polygon": [ + { + "x": 0.7706, + "y": 5.0139 + }, + { + "x": 7.4781, + "y": 5.019 + }, + { + "x": 7.4781, + "y": 5.2319 + }, + { + "x": 0.7706, + "y": 5.2167 + } + ], + "spans": [ + { + "offset": 919, + "length": 74 + } + ] + }, + { + "content": "Adobe, such as Adobe XML Forms Architecture (XFA) and JavaScript", + "polygon": [ + { + "x": 0.7757, + "y": 5.2522 + }, + { + "x": 6.7683, + "y": 5.2522 + }, + { + "x": 6.7683, + "y": 5.4651 + }, + { + "x": 0.7757, + "y": 5.455 + } + ], + "spans": [ + { + "offset": 994, + "length": 64 + } + ] + }, + { + "content": "extension for Acrobat, which are referenced by ISO 32000-1 as normative", + "polygon": [ + { + "x": 0.7656, + "y": 5.4854 + }, + { + "x": 7.113, + "y": 5.4854 + }, + { + "x": 7.113, + "y": 5.6882 + }, + { + "x": 0.7656, + "y": 5.6882 + } + ], + "spans": [ + { + "offset": 1059, + "length": 71 + } + ] + }, + { + "content": "and indispensable for the full implementation of the ISO 32000-1", + "polygon": [ + { + "x": 0.7656, + "y": 5.7287 + }, + { + "x": 6.3221, + "y": 5.7237 + }, + { + "x": 6.3221, + "y": 5.9265 + }, + { + "x": 0.7656, + "y": 5.9366 + } + ], + "spans": [ + { + "offset": 1131, + "length": 64 + } + ] + }, + { + "content": "specification. These proprietary technologies are not standardized and their", + "polygon": [ + { + "x": 0.7858, + "y": 5.967 + }, + { + "x": 7.2702, + "y": 5.962 + }, + { + "x": 7.2702, + "y": 6.1647 + }, + { + "x": 0.7858, + "y": 6.1799 + } + ], + "spans": [ + { + "offset": 1196, + "length": 76 + } + ] + }, + { + "content": "specification is published only on Adobe's website. Many of them are also not", + "polygon": [ + { + "x": 0.7656, + "y": 6.2002 + }, + { + "x": 7.4324, + "y": 6.1952 + }, + { + "x": 7.4324, + "y": 6.403 + }, + { + "x": 0.7656, + "y": 6.4081 + } + ], + "spans": [ + { + "offset": 1273, + "length": 77 + } + ] + }, + { + "content": "supported by popular third-party implementations of PDF.", + "polygon": [ + { + "x": 0.7605, + "y": 6.4385 + }, + { + "x": 5.6985, + "y": 6.4284 + }, + { + "x": 5.6985, + "y": 6.6362 + }, + { + "x": 0.7605, + "y": 6.6514 + } + ], + "spans": [ + { + "offset": 1351, + "length": 56 + } + ] + }, + { + "content": "Column 1", + "polygon": [ + { + "x": 2.5045, + "y": 7.1229 + }, + { + "x": 3.1433, + "y": 7.1229 + }, + { + "x": 3.1433, + "y": 7.2649 + }, + { + "x": 2.5045, + "y": 7.2649 + } + ], + "spans": [ + { + "offset": 1408, + "length": 8 + } + ] + }, + { + "content": "Column 2", + "polygon": [ + { + "x": 4.1776, + "y": 7.1229 + }, + { + "x": 4.8214, + "y": 7.128 + }, + { + "x": 4.8214, + "y": 7.2699 + }, + { + "x": 4.1776, + "y": 7.2649 + } + ], + "spans": [ + { + "offset": 1417, + "length": 8 + } + ] + }, + { + "content": "Column 3", + "polygon": [ + { + "x": 5.8304, + "y": 7.1128 + }, + { + "x": 6.5097, + "y": 7.1128 + }, + { + "x": 6.5097, + "y": 7.2801 + }, + { + "x": 5.8304, + "y": 7.2801 + } + ], + "spans": [ + { + "offset": 1426, + "length": 8 + } + ] + }, + { + "content": "A", + "polygon": [ + { + "x": 0.8365, + "y": 7.4575 + }, + { + "x": 0.9329, + "y": 7.4524 + }, + { + "x": 0.9379, + "y": 7.5741 + }, + { + "x": 0.8365, + "y": 7.5741 + } + ], + "spans": [ + { + "offset": 1435, + "length": 1 + } + ] + }, + { + "content": "324", + "polygon": [ + { + "x": 3.8176, + "y": 7.4474 + }, + { + "x": 4.0965, + "y": 7.4423 + }, + { + "x": 4.0965, + "y": 7.5843 + }, + { + "x": 3.8227, + "y": 7.5893 + } + ], + "spans": [ + { + "offset": 1437, + "length": 3 + } + ] + }, + { + "content": "55 million units", + "polygon": [ + { + "x": 4.1674, + "y": 7.4423 + }, + { + "x": 5.1206, + "y": 7.4423 + }, + { + "x": 5.1206, + "y": 7.5944 + }, + { + "x": 4.1674, + "y": 7.5893 + } + ], + "spans": [ + { + "offset": 1441, + "length": 16 + } + ] + }, + { + "content": "2022", + "polygon": [ + { + "x": 7.0877, + "y": 7.4524 + }, + { + "x": 7.4122, + "y": 7.4575 + }, + { + "x": 7.4172, + "y": 7.5792 + }, + { + "x": 7.0927, + "y": 7.5792 + } + ], + "spans": [ + { + "offset": 1458, + "length": 4 + } + ] + }, + { + "content": "B", + "polygon": [ + { + "x": 0.8416, + "y": 7.7668 + }, + { + "x": 0.943, + "y": 7.7668 + }, + { + "x": 0.943, + "y": 7.8884 + }, + { + "x": 0.8416, + "y": 7.8834 + } + ], + "spans": [ + { + "offset": 1463, + "length": 1 + } + ] + }, + { + "content": "234,523.00", + "polygon": [ + { + "x": 2.4944, + "y": 7.7617 + }, + { + "x": 3.2194, + "y": 7.7617 + }, + { + "x": 3.2194, + "y": 7.9036 + }, + { + "x": 2.4944, + "y": 7.9036 + } + ], + "spans": [ + { + "offset": 1465, + "length": 10 + } + ] + }, + { + "content": "The quick brown fox", + "polygon": [ + { + "x": 4.1674, + "y": 7.7515 + }, + { + "x": 5.4704, + "y": 7.7515 + }, + { + "x": 5.4704, + "y": 7.9138 + }, + { + "x": 4.1674, + "y": 7.9087 + } + ], + "spans": [ + { + "offset": 1476, + "length": 19 + } + ] + }, + { + "content": "jumped over the lazy", + "polygon": [ + { + "x": 4.1674, + "y": 7.9341 + }, + { + "x": 5.4755, + "y": 7.929 + }, + { + "x": 5.4755, + "y": 8.0861 + }, + { + "x": 4.1674, + "y": 8.0861 + } + ], + "spans": [ + { + "offset": 1496, + "length": 20 + } + ] + }, + { + "content": "dog.", + "polygon": [ + { + "x": 4.1725, + "y": 8.1014 + }, + { + "x": 4.4615, + "y": 8.1014 + }, + { + "x": 4.4666, + "y": 8.2433 + }, + { + "x": 4.1725, + "y": 8.2382 + } + ], + "spans": [ + { + "offset": 1517, + "length": 4 + } + ] + }, + { + "content": "54x growth", + "polygon": [ + { + "x": 5.8456, + "y": 7.7617 + }, + { + "x": 6.5604, + "y": 7.7617 + }, + { + "x": 6.5604, + "y": 7.9138 + }, + { + "x": 5.8456, + "y": 7.9138 + } + ], + "spans": [ + { + "offset": 1522, + "length": 10 + } + ] + }, + { + "content": "C", + "polygon": [ + { + "x": 0.8416, + "y": 8.365 + }, + { + "x": 0.9481, + "y": 8.365 + }, + { + "x": 0.9481, + "y": 8.5069 + }, + { + "x": 0.8467, + "y": 8.5019 + } + ], + "spans": [ + { + "offset": 1533, + "length": 1 + } + ] + }, + { + "content": "23.53%", + "polygon": [ + { + "x": 2.4944, + "y": 8.3447 + }, + { + "x": 2.9963, + "y": 8.3396 + }, + { + "x": 3.0014, + "y": 8.5171 + }, + { + "x": 2.4893, + "y": 8.5171 + } + ], + "spans": [ + { + "offset": 1535, + "length": 6 + } + ] + }, + { + "content": "A short string.", + "polygon": [ + { + "x": 4.1674, + "y": 8.3701 + }, + { + "x": 5.0597, + "y": 8.3751 + }, + { + "x": 5.0597, + "y": 8.5272 + }, + { + "x": 4.1674, + "y": 8.5221 + } + ], + "spans": [ + { + "offset": 1542, + "length": 15 + } + ] + }, + { + "content": "D", + "polygon": [ + { + "x": 0.8416, + "y": 8.6945 + }, + { + "x": 0.9481, + "y": 8.6945 + }, + { + "x": 0.9481, + "y": 8.8213 + }, + { + "x": 0.8416, + "y": 8.8162 + } + ], + "spans": [ + { + "offset": 1558, + "length": 1 + } + ] + }, + { + "content": "$54.35", + "polygon": [ + { + "x": 2.4944, + "y": 8.6894 + }, + { + "x": 2.9456, + "y": 8.6844 + }, + { + "x": 2.9456, + "y": 8.8263 + }, + { + "x": 2.4944, + "y": 8.8263 + } + ], + "spans": [ + { + "offset": 1560, + "length": 6 + } + ] + }, + { + "content": "$6345.", + "polygon": [ + { + "x": 4.1624, + "y": 8.6894 + }, + { + "x": 4.6136, + "y": 8.6945 + }, + { + "x": 4.6136, + "y": 8.8365 + }, + { + "x": 4.1624, + "y": 8.8263 + } + ], + "spans": [ + { + "offset": 1567, + "length": 6 + } + ] + } + ], + "words": [ + { + "content": "A", + "polygon": [ + { + "x": 0.7858, + "y": 0.8416 + }, + { + "x": 0.9582, + "y": 0.8365 + }, + { + "x": 0.9531, + "y": 1.1863 + }, + { + "x": 0.7808, + "y": 1.1812 + } + ], + "span": { + "offset": 0, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "sample", + "polygon": [ + { + "x": 1.1103, + "y": 0.8365 + }, + { + "x": 2.251, + "y": 0.8365 + }, + { + "x": 2.251, + "y": 1.1863 + }, + { + "x": 1.1103, + "y": 1.1914 + } + ], + "span": { + "offset": 2, + "length": 6 + }, + "confidence": 0.993 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 2.3626, + "y": 0.8365 + }, + { + "x": 2.9963, + "y": 0.8416 + }, + { + "x": 3.0014, + "y": 1.161 + }, + { + "x": 2.3626, + "y": 1.1812 + } + ], + "span": { + "offset": 9, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "file", + "polygon": [ + { + "x": 3.1078, + "y": 0.8416 + }, + { + "x": 3.5895, + "y": 0.8416 + }, + { + "x": 3.5945, + "y": 1.1255 + }, + { + "x": 3.1078, + "y": 1.1559 + } + ], + "span": { + "offset": 13, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "History", + "polygon": [ + { + "x": 0.7808, + "y": 1.7186 + }, + { + "x": 1.3993, + "y": 1.7136 + }, + { + "x": 1.3993, + "y": 1.9316 + }, + { + "x": 0.7757, + "y": 1.9316 + } + ], + "span": { + "offset": 18, + "length": 7 + }, + "confidence": 0.995 + }, + { + "content": "and", + "polygon": [ + { + "x": 1.4449, + "y": 1.7136 + }, + { + "x": 1.7592, + "y": 1.7136 + }, + { + "x": 1.7592, + "y": 1.9316 + }, + { + "x": 1.4398, + "y": 1.9316 + } + ], + "span": { + "offset": 26, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "standardization", + "polygon": [ + { + "x": 1.815, + "y": 1.7136 + }, + { + "x": 3.123, + "y": 1.7186 + }, + { + "x": 3.123, + "y": 1.9113 + }, + { + "x": 1.815, + "y": 1.9316 + } + ], + "span": { + "offset": 30, + "length": 15 + }, + "confidence": 0.991 + }, + { + "content": "Format", + "polygon": [ + { + "x": 0.7808, + "y": 2.185 + }, + { + "x": 1.3942, + "y": 2.185 + }, + { + "x": 1.3942, + "y": 2.398 + }, + { + "x": 0.7858, + "y": 2.3929 + } + ], + "span": { + "offset": 46, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "(PDF)", + "polygon": [ + { + "x": 1.4348, + "y": 2.185 + }, + { + "x": 1.9772, + "y": 2.185 + }, + { + "x": 1.9772, + "y": 2.398 + }, + { + "x": 1.4348, + "y": 2.398 + } + ], + "span": { + "offset": 53, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "Adobe", + "polygon": [ + { + "x": 2.0178, + "y": 2.185 + }, + { + "x": 2.5603, + "y": 2.185 + }, + { + "x": 2.5654, + "y": 2.398 + }, + { + "x": 2.0229, + "y": 2.398 + } + ], + "span": { + "offset": 59, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "Systems", + "polygon": [ + { + "x": 2.6313, + "y": 2.185 + }, + { + "x": 3.3715, + "y": 2.185 + }, + { + "x": 3.3715, + "y": 2.398 + }, + { + "x": 2.6313, + "y": 2.398 + } + ], + "span": { + "offset": 65, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "made", + "polygon": [ + { + "x": 3.412, + "y": 2.185 + }, + { + "x": 3.9139, + "y": 2.185 + }, + { + "x": 3.9139, + "y": 2.398 + }, + { + "x": 3.412, + "y": 2.398 + } + ], + "span": { + "offset": 73, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "the", + "polygon": [ + { + "x": 3.9545, + "y": 2.185 + }, + { + "x": 4.2333, + "y": 2.185 + }, + { + "x": 4.2333, + "y": 2.398 + }, + { + "x": 3.9545, + "y": 2.398 + } + ], + "span": { + "offset": 78, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 4.2891, + "y": 2.185 + }, + { + "x": 4.6643, + "y": 2.185 + }, + { + "x": 4.6643, + "y": 2.398 + }, + { + "x": 4.2891, + "y": 2.398 + } + ], + "span": { + "offset": 82, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "specification", + "polygon": [ + { + "x": 4.7353, + "y": 2.185 + }, + { + "x": 5.7949, + "y": 2.185 + }, + { + "x": 5.7949, + "y": 2.398 + }, + { + "x": 4.7353, + "y": 2.398 + } + ], + "span": { + "offset": 86, + "length": 13 + }, + "confidence": 0.97 + }, + { + "content": "available", + "polygon": [ + { + "x": 5.8608, + "y": 2.185 + }, + { + "x": 6.6314, + "y": 2.185 + }, + { + "x": 6.6314, + "y": 2.3929 + }, + { + "x": 5.8658, + "y": 2.398 + } + ], + "span": { + "offset": 100, + "length": 9 + }, + "confidence": 0.986 + }, + { + "content": "free", + "polygon": [ + { + "x": 6.672, + "y": 2.185 + }, + { + "x": 7.0167, + "y": 2.185 + }, + { + "x": 7.0218, + "y": 2.3929 + }, + { + "x": 6.672, + "y": 2.3929 + } + ], + "span": { + "offset": 110, + "length": 4 + }, + "confidence": 0.992 + }, + { + "content": "of", + "polygon": [ + { + "x": 7.0623, + "y": 2.185 + }, + { + "x": 7.2601, + "y": 2.185 + }, + { + "x": 7.2601, + "y": 2.3929 + }, + { + "x": 7.0623, + "y": 2.3929 + } + ], + "span": { + "offset": 115, + "length": 2 + }, + "confidence": 0.993 + }, + { + "content": "charge", + "polygon": [ + { + "x": 0.7706, + "y": 2.4233 + }, + { + "x": 1.3638, + "y": 2.4233 + }, + { + "x": 1.3638, + "y": 2.6362 + }, + { + "x": 0.7706, + "y": 2.6362 + } + ], + "span": { + "offset": 118, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "in", + "polygon": [ + { + "x": 1.4044, + "y": 2.4233 + }, + { + "x": 1.5615, + "y": 2.4182 + }, + { + "x": 1.5615, + "y": 2.6362 + }, + { + "x": 1.4044, + "y": 2.6362 + } + ], + "span": { + "offset": 125, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "1993.", + "polygon": [ + { + "x": 1.6477, + "y": 2.4182 + }, + { + "x": 2.1141, + "y": 2.4182 + }, + { + "x": 2.1141, + "y": 2.6362 + }, + { + "x": 1.6477, + "y": 2.6362 + } + ], + "span": { + "offset": 128, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "In", + "polygon": [ + { + "x": 2.1598, + "y": 2.4182 + }, + { + "x": 2.3271, + "y": 2.4182 + }, + { + "x": 2.3271, + "y": 2.6362 + }, + { + "x": 2.1598, + "y": 2.6362 + } + ], + "span": { + "offset": 134, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "the", + "polygon": [ + { + "x": 2.3727, + "y": 2.4182 + }, + { + "x": 2.6566, + "y": 2.4182 + }, + { + "x": 2.6566, + "y": 2.6362 + }, + { + "x": 2.3727, + "y": 2.6362 + } + ], + "span": { + "offset": 137, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "early", + "polygon": [ + { + "x": 2.7124, + "y": 2.4182 + }, + { + "x": 3.1383, + "y": 2.4182 + }, + { + "x": 3.1383, + "y": 2.6362 + }, + { + "x": 2.7124, + "y": 2.6362 + } + ], + "span": { + "offset": 141, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "years", + "polygon": [ + { + "x": 3.1788, + "y": 2.4182 + }, + { + "x": 3.6604, + "y": 2.4182 + }, + { + "x": 3.6655, + "y": 2.6362 + }, + { + "x": 3.1788, + "y": 2.6362 + } + ], + "span": { + "offset": 147, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 3.7061, + "y": 2.4182 + }, + { + "x": 4.1015, + "y": 2.4182 + }, + { + "x": 4.1015, + "y": 2.6362 + }, + { + "x": 3.7061, + "y": 2.6362 + } + ], + "span": { + "offset": 153, + "length": 3 + }, + "confidence": 0.992 + }, + { + "content": "was", + "polygon": [ + { + "x": 4.1421, + "y": 2.4182 + }, + { + "x": 4.5122, + "y": 2.4182 + }, + { + "x": 4.5173, + "y": 2.6362 + }, + { + "x": 4.1472, + "y": 2.6362 + } + ], + "span": { + "offset": 157, + "length": 3 + }, + "confidence": 0.979 + }, + { + "content": "popular", + "polygon": [ + { + "x": 4.5527, + "y": 2.4182 + }, + { + "x": 5.2068, + "y": 2.4182 + }, + { + "x": 5.2118, + "y": 2.6362 + }, + { + "x": 4.5578, + "y": 2.6362 + } + ], + "span": { + "offset": 161, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "mainly", + "polygon": [ + { + "x": 5.2524, + "y": 2.4182 + }, + { + "x": 5.8151, + "y": 2.4233 + }, + { + "x": 5.8202, + "y": 2.6362 + }, + { + "x": 5.2524, + "y": 2.6362 + } + ], + "span": { + "offset": 169, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "in", + "polygon": [ + { + "x": 5.8608, + "y": 2.4233 + }, + { + "x": 6.0281, + "y": 2.4233 + }, + { + "x": 6.0331, + "y": 2.6362 + }, + { + "x": 5.8658, + "y": 2.6362 + } + ], + "span": { + "offset": 176, + "length": 2 + }, + "confidence": 0.997 + }, + { + "content": "desktop", + "polygon": [ + { + "x": 6.0737, + "y": 2.4233 + }, + { + "x": 6.7683, + "y": 2.4284 + }, + { + "x": 6.7733, + "y": 2.6362 + }, + { + "x": 6.0788, + "y": 2.6362 + } + ], + "span": { + "offset": 179, + "length": 7 + }, + "confidence": 0.995 + }, + { + "content": "publishing", + "polygon": [ + { + "x": 0.7706, + "y": 2.6616 + }, + { + "x": 1.6578, + "y": 2.6616 + }, + { + "x": 1.6578, + "y": 2.8745 + }, + { + "x": 0.7706, + "y": 2.8796 + } + ], + "span": { + "offset": 187, + "length": 10 + }, + "confidence": 0.991 + }, + { + "content": "workflows,", + "polygon": [ + { + "x": 1.6984, + "y": 2.6616 + }, + { + "x": 2.6313, + "y": 2.6616 + }, + { + "x": 2.6313, + "y": 2.8745 + }, + { + "x": 1.6984, + "y": 2.8745 + } + ], + "span": { + "offset": 198, + "length": 10 + }, + "confidence": 0.993 + }, + { + "content": "and", + "polygon": [ + { + "x": 2.6718, + "y": 2.6616 + }, + { + "x": 2.9963, + "y": 2.6616 + }, + { + "x": 2.9963, + "y": 2.8745 + }, + { + "x": 2.6718, + "y": 2.8745 + } + ], + "span": { + "offset": 209, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "competed", + "polygon": [ + { + "x": 3.0369, + "y": 2.6616 + }, + { + "x": 3.8987, + "y": 2.6616 + }, + { + "x": 3.8987, + "y": 2.8745 + }, + { + "x": 3.0369, + "y": 2.8745 + } + ], + "span": { + "offset": 213, + "length": 8 + }, + "confidence": 0.994 + }, + { + "content": "with", + "polygon": [ + { + "x": 3.9393, + "y": 2.6616 + }, + { + "x": 4.2942, + "y": 2.6616 + }, + { + "x": 4.2942, + "y": 2.8745 + }, + { + "x": 3.9393, + "y": 2.8745 + } + ], + "span": { + "offset": 222, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "a", + "polygon": [ + { + "x": 4.3652, + "y": 2.6616 + }, + { + "x": 4.4767, + "y": 2.6616 + }, + { + "x": 4.4767, + "y": 2.8745 + }, + { + "x": 4.3652, + "y": 2.8745 + } + ], + "span": { + "offset": 227, + "length": 1 + }, + "confidence": 0.992 + }, + { + "content": "variety", + "polygon": [ + { + "x": 4.5173, + "y": 2.6565 + }, + { + "x": 5.0952, + "y": 2.6565 + }, + { + "x": 5.0952, + "y": 2.8745 + }, + { + "x": 4.5173, + "y": 2.8745 + } + ], + "span": { + "offset": 229, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "of", + "polygon": [ + { + "x": 5.1408, + "y": 2.6565 + }, + { + "x": 5.3082, + "y": 2.6565 + }, + { + "x": 5.3082, + "y": 2.8745 + }, + { + "x": 5.1408, + "y": 2.8745 + } + ], + "span": { + "offset": 237, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "formats", + "polygon": [ + { + "x": 5.3487, + "y": 2.6565 + }, + { + "x": 6.0129, + "y": 2.6565 + }, + { + "x": 6.0129, + "y": 2.8745 + }, + { + "x": 5.3487, + "y": 2.8745 + } + ], + "span": { + "offset": 240, + "length": 7 + }, + "confidence": 0.993 + }, + { + "content": "such", + "polygon": [ + { + "x": 6.0534, + "y": 2.6565 + }, + { + "x": 6.4641, + "y": 2.6565 + }, + { + "x": 6.4641, + "y": 2.8745 + }, + { + "x": 6.0534, + "y": 2.8745 + } + ], + "span": { + "offset": 248, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "as", + "polygon": [ + { + "x": 6.5351, + "y": 2.6565 + }, + { + "x": 6.748, + "y": 2.6565 + }, + { + "x": 6.748, + "y": 2.8745 + }, + { + "x": 6.5351, + "y": 2.8745 + } + ], + "span": { + "offset": 253, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "DjVu,", + "polygon": [ + { + "x": 6.7886, + "y": 2.6565 + }, + { + "x": 7.255, + "y": 2.6565 + }, + { + "x": 7.255, + "y": 2.8745 + }, + { + "x": 6.7886, + "y": 2.8745 + } + ], + "span": { + "offset": 256, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "Envoy,", + "polygon": [ + { + "x": 0.7757, + "y": 2.8948 + }, + { + "x": 1.3638, + "y": 2.8948 + }, + { + "x": 1.3587, + "y": 3.1077 + }, + { + "x": 0.7706, + "y": 3.1077 + } + ], + "span": { + "offset": 262, + "length": 6 + }, + "confidence": 0.993 + }, + { + "content": "Common", + "polygon": [ + { + "x": 1.4044, + "y": 2.8948 + }, + { + "x": 2.1953, + "y": 2.8948 + }, + { + "x": 2.1902, + "y": 3.1128 + }, + { + "x": 1.3993, + "y": 3.1077 + } + ], + "span": { + "offset": 269, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "Ground", + "polygon": [ + { + "x": 2.251, + "y": 2.8948 + }, + { + "x": 2.9, + "y": 2.8948 + }, + { + "x": 2.8949, + "y": 3.1128 + }, + { + "x": 2.246, + "y": 3.1128 + } + ], + "span": { + "offset": 276, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "Digital", + "polygon": [ + { + "x": 2.9557, + "y": 2.8948 + }, + { + "x": 3.5084, + "y": 2.8948 + }, + { + "x": 3.5033, + "y": 3.1128 + }, + { + "x": 2.9557, + "y": 3.1128 + } + ], + "span": { + "offset": 283, + "length": 7 + }, + "confidence": 0.993 + }, + { + "content": "Paper,", + "polygon": [ + { + "x": 3.5489, + "y": 2.8948 + }, + { + "x": 4.1117, + "y": 2.8948 + }, + { + "x": 4.1117, + "y": 3.1128 + }, + { + "x": 3.5489, + "y": 3.1128 + } + ], + "span": { + "offset": 291, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "Farallon", + "polygon": [ + { + "x": 4.1573, + "y": 2.8948 + }, + { + "x": 4.862, + "y": 2.8948 + }, + { + "x": 4.8569, + "y": 3.1128 + }, + { + "x": 4.1522, + "y": 3.1128 + } + ], + "span": { + "offset": 298, + "length": 8 + }, + "confidence": 0.979 + }, + { + "content": "Replica", + "polygon": [ + { + "x": 4.9178, + "y": 2.8948 + }, + { + "x": 5.5819, + "y": 2.8948 + }, + { + "x": 5.5769, + "y": 3.1128 + }, + { + "x": 4.9178, + "y": 3.1128 + } + ], + "span": { + "offset": 307, + "length": 7 + }, + "confidence": 0.989 + }, + { + "content": "and", + "polygon": [ + { + "x": 5.6225, + "y": 2.8948 + }, + { + "x": 5.947, + "y": 2.8948 + }, + { + "x": 5.947, + "y": 3.1077 + }, + { + "x": 5.6225, + "y": 3.1128 + } + ], + "span": { + "offset": 315, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "even", + "polygon": [ + { + "x": 6.0027, + "y": 2.8948 + }, + { + "x": 6.4286, + "y": 2.8948 + }, + { + "x": 6.4235, + "y": 3.1077 + }, + { + "x": 6.0027, + "y": 3.1077 + } + ], + "span": { + "offset": 319, + "length": 4 + }, + "confidence": 0.924 + }, + { + "content": "Adobe's", + "polygon": [ + { + "x": 6.4692, + "y": 2.8948 + }, + { + "x": 7.1789, + "y": 2.8999 + }, + { + "x": 7.1789, + "y": 3.1026 + }, + { + "x": 6.4692, + "y": 3.1077 + } + ], + "span": { + "offset": 324, + "length": 7 + }, + "confidence": 0.961 + }, + { + "content": "own", + "polygon": [ + { + "x": 0.7706, + "y": 3.1331 + }, + { + "x": 1.1154, + "y": 3.1331 + }, + { + "x": 1.1204, + "y": 3.3359 + }, + { + "x": 0.7808, + "y": 3.3308 + } + ], + "span": { + "offset": 332, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "PostScript", + "polygon": [ + { + "x": 1.1813, + "y": 3.1331 + }, + { + "x": 2.0736, + "y": 3.1331 + }, + { + "x": 2.0786, + "y": 3.3409 + }, + { + "x": 1.1863, + "y": 3.3359 + } + ], + "span": { + "offset": 336, + "length": 10 + }, + "confidence": 0.99 + }, + { + "content": "format.", + "polygon": [ + { + "x": 2.1141, + "y": 3.1331 + }, + { + "x": 2.7327, + "y": 3.1331 + }, + { + "x": 2.7377, + "y": 3.346 + }, + { + "x": 2.1192, + "y": 3.3409 + } + ], + "span": { + "offset": 347, + "length": 7 + }, + "confidence": 0.992 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 2.7783, + "y": 3.1331 + }, + { + "x": 3.1585, + "y": 3.1331 + }, + { + "x": 3.1636, + "y": 3.346 + }, + { + "x": 2.7783, + "y": 3.346 + } + ], + "span": { + "offset": 355, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "was", + "polygon": [ + { + "x": 3.2143, + "y": 3.1331 + }, + { + "x": 3.5844, + "y": 3.1331 + }, + { + "x": 3.5895, + "y": 3.346 + }, + { + "x": 3.2194, + "y": 3.346 + } + ], + "span": { + "offset": 359, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "a", + "polygon": [ + { + "x": 3.63, + "y": 3.1331 + }, + { + "x": 3.7365, + "y": 3.1331 + }, + { + "x": 3.7416, + "y": 3.346 + }, + { + "x": 3.63, + "y": 3.346 + } + ], + "span": { + "offset": 363, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "proprietary", + "polygon": [ + { + "x": 3.7771, + "y": 3.1331 + }, + { + "x": 4.7251, + "y": 3.1331 + }, + { + "x": 4.7302, + "y": 3.346 + }, + { + "x": 3.7821, + "y": 3.346 + } + ], + "span": { + "offset": 365, + "length": 11 + }, + "confidence": 0.992 + }, + { + "content": "format", + "polygon": [ + { + "x": 4.7707, + "y": 3.1331 + }, + { + "x": 5.3335, + "y": 3.1331 + }, + { + "x": 5.3335, + "y": 3.346 + }, + { + "x": 4.7707, + "y": 3.346 + } + ], + "span": { + "offset": 377, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "controlled", + "polygon": [ + { + "x": 5.3741, + "y": 3.1331 + }, + { + "x": 6.2258, + "y": 3.1331 + }, + { + "x": 6.2258, + "y": 3.3409 + }, + { + "x": 5.3741, + "y": 3.346 + } + ], + "span": { + "offset": 384, + "length": 10 + }, + "confidence": 0.992 + }, + { + "content": "by", + "polygon": [ + { + "x": 6.2664, + "y": 3.1331 + }, + { + "x": 6.4844, + "y": 3.1331 + }, + { + "x": 6.4844, + "y": 3.3409 + }, + { + "x": 6.2664, + "y": 3.3409 + } + ], + "span": { + "offset": 395, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "Adobe", + "polygon": [ + { + "x": 6.5249, + "y": 3.1331 + }, + { + "x": 7.0927, + "y": 3.1331 + }, + { + "x": 7.0927, + "y": 3.3359 + }, + { + "x": 6.53, + "y": 3.3409 + } + ], + "span": { + "offset": 398, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "until", + "polygon": [ + { + "x": 0.7909, + "y": 3.3713 + }, + { + "x": 1.1255, + "y": 3.3713 + }, + { + "x": 1.1204, + "y": 3.564 + }, + { + "x": 0.7858, + "y": 3.564 + } + ], + "span": { + "offset": 404, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "it", + "polygon": [ + { + "x": 1.1661, + "y": 3.3713 + }, + { + "x": 1.2877, + "y": 3.3713 + }, + { + "x": 1.2827, + "y": 3.564 + }, + { + "x": 1.161, + "y": 3.564 + } + ], + "span": { + "offset": 410, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "was", + "polygon": [ + { + "x": 1.3283, + "y": 3.3713 + }, + { + "x": 1.6832, + "y": 3.3713 + }, + { + "x": 1.6781, + "y": 3.5691 + }, + { + "x": 1.3232, + "y": 3.564 + } + ], + "span": { + "offset": 413, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "released", + "polygon": [ + { + "x": 1.7238, + "y": 3.3713 + }, + { + "x": 2.4842, + "y": 3.3713 + }, + { + "x": 2.4792, + "y": 3.5741 + }, + { + "x": 1.7187, + "y": 3.5691 + } + ], + "span": { + "offset": 417, + "length": 8 + }, + "confidence": 0.994 + }, + { + "content": "as", + "polygon": [ + { + "x": 2.5501, + "y": 3.3713 + }, + { + "x": 2.7529, + "y": 3.3713 + }, + { + "x": 2.7479, + "y": 3.5741 + }, + { + "x": 2.5451, + "y": 3.5741 + } + ], + "span": { + "offset": 426, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "an", + "polygon": [ + { + "x": 2.8087, + "y": 3.3713 + }, + { + "x": 3.0115, + "y": 3.3713 + }, + { + "x": 3.0064, + "y": 3.5792 + }, + { + "x": 2.8036, + "y": 3.5741 + } + ], + "span": { + "offset": 429, + "length": 2 + }, + "confidence": 0.997 + }, + { + "content": "open", + "polygon": [ + { + "x": 3.0673, + "y": 3.3713 + }, + { + "x": 3.483, + "y": 3.3663 + }, + { + "x": 3.483, + "y": 3.5792 + }, + { + "x": 3.0622, + "y": 3.5792 + } + ], + "span": { + "offset": 432, + "length": 4 + }, + "confidence": 0.991 + }, + { + "content": "standard", + "polygon": [ + { + "x": 3.5641, + "y": 3.3663 + }, + { + "x": 4.3145, + "y": 3.3663 + }, + { + "x": 4.3094, + "y": 3.5843 + }, + { + "x": 3.5641, + "y": 3.5792 + } + ], + "span": { + "offset": 437, + "length": 8 + }, + "confidence": 0.994 + }, + { + "content": "on", + "polygon": [ + { + "x": 4.3652, + "y": 3.3663 + }, + { + "x": 4.568, + "y": 3.3663 + }, + { + "x": 4.568, + "y": 3.5843 + }, + { + "x": 4.3652, + "y": 3.5843 + } + ], + "span": { + "offset": 446, + "length": 2 + }, + "confidence": 0.997 + }, + { + "content": "July", + "polygon": [ + { + "x": 4.6389, + "y": 3.3663 + }, + { + "x": 5.004, + "y": 3.3713 + }, + { + "x": 5.004, + "y": 3.5843 + }, + { + "x": 4.6339, + "y": 3.5843 + } + ], + "span": { + "offset": 449, + "length": 4 + }, + "confidence": 0.987 + }, + { + "content": "1,", + "polygon": [ + { + "x": 5.0597, + "y": 3.3713 + }, + { + "x": 5.222, + "y": 3.3713 + }, + { + "x": 5.222, + "y": 3.5843 + }, + { + "x": 5.0547, + "y": 3.5843 + } + ], + "span": { + "offset": 454, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "2008,", + "polygon": [ + { + "x": 5.2625, + "y": 3.3713 + }, + { + "x": 5.7644, + "y": 3.3713 + }, + { + "x": 5.7644, + "y": 3.5843 + }, + { + "x": 5.2625, + "y": 3.5843 + } + ], + "span": { + "offset": 457, + "length": 5 + }, + "confidence": 0.967 + }, + { + "content": "and", + "polygon": [ + { + "x": 5.805, + "y": 3.3713 + }, + { + "x": 6.1143, + "y": 3.3713 + }, + { + "x": 6.1143, + "y": 3.5843 + }, + { + "x": 5.805, + "y": 3.5843 + } + ], + "span": { + "offset": 463, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "published", + "polygon": [ + { + "x": 6.17, + "y": 3.3713 + }, + { + "x": 7.0116, + "y": 3.3713 + }, + { + "x": 7.0116, + "y": 3.5792 + }, + { + "x": 6.17, + "y": 3.5843 + } + ], + "span": { + "offset": 467, + "length": 9 + }, + "confidence": 0.993 + }, + { + "content": "by", + "polygon": [ + { + "x": 7.0522, + "y": 3.3713 + }, + { + "x": 7.2702, + "y": 3.3713 + }, + { + "x": 7.2702, + "y": 3.5792 + }, + { + "x": 7.0522, + "y": 3.5792 + } + ], + "span": { + "offset": 477, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "the", + "polygon": [ + { + "x": 0.7706, + "y": 3.6045 + }, + { + "x": 1.0343, + "y": 3.6045 + }, + { + "x": 1.0393, + "y": 3.8073 + }, + { + "x": 0.7757, + "y": 3.8073 + } + ], + "span": { + "offset": 480, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "International", + "polygon": [ + { + "x": 1.09, + "y": 3.6045 + }, + { + "x": 2.18, + "y": 3.5995 + }, + { + "x": 2.1851, + "y": 3.8073 + }, + { + "x": 1.0951, + "y": 3.8073 + } + ], + "span": { + "offset": 484, + "length": 13 + }, + "confidence": 0.979 + }, + { + "content": "Organization", + "polygon": [ + { + "x": 2.2206, + "y": 3.5995 + }, + { + "x": 3.3106, + "y": 3.5995 + }, + { + "x": 3.3106, + "y": 3.8073 + }, + { + "x": 2.2257, + "y": 3.8073 + } + ], + "span": { + "offset": 498, + "length": 12 + }, + "confidence": 0.99 + }, + { + "content": "for", + "polygon": [ + { + "x": 3.3613, + "y": 3.5995 + }, + { + "x": 3.63, + "y": 3.5995 + }, + { + "x": 3.6351, + "y": 3.8073 + }, + { + "x": 3.3664, + "y": 3.8073 + } + ], + "span": { + "offset": 511, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "Standardization", + "polygon": [ + { + "x": 3.6706, + "y": 3.5995 + }, + { + "x": 5.004, + "y": 3.5995 + }, + { + "x": 5.004, + "y": 3.8073 + }, + { + "x": 3.6757, + "y": 3.8073 + } + ], + "span": { + "offset": 515, + "length": 15 + }, + "confidence": 0.991 + }, + { + "content": "as", + "polygon": [ + { + "x": 5.0699, + "y": 3.5995 + }, + { + "x": 5.2727, + "y": 3.5995 + }, + { + "x": 5.2727, + "y": 3.8073 + }, + { + "x": 5.0699, + "y": 3.8073 + } + ], + "span": { + "offset": 531, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "ISO", + "polygon": [ + { + "x": 5.3132, + "y": 3.5995 + }, + { + "x": 5.6225, + "y": 3.5995 + }, + { + "x": 5.6225, + "y": 3.8073 + }, + { + "x": 5.3132, + "y": 3.8073 + } + ], + "span": { + "offset": 534, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "32000-1:2008,", + "polygon": [ + { + "x": 5.7188, + "y": 3.5995 + }, + { + "x": 6.9812, + "y": 3.6045 + }, + { + "x": 6.9812, + "y": 3.8023 + }, + { + "x": 5.7188, + "y": 3.8073 + } + ], + "span": { + "offset": 538, + "length": 13 + }, + "confidence": 0.982 + }, + { + "content": "at", + "polygon": [ + { + "x": 7.0218, + "y": 3.6045 + }, + { + "x": 7.1992, + "y": 3.6045 + }, + { + "x": 7.1992, + "y": 3.8023 + }, + { + "x": 7.0218, + "y": 3.8023 + } + ], + "span": { + "offset": 552, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "which", + "polygon": [ + { + "x": 0.7757, + "y": 3.8428 + }, + { + "x": 1.2624, + "y": 3.8428 + }, + { + "x": 1.2624, + "y": 4.0355 + }, + { + "x": 0.7808, + "y": 4.0304 + } + ], + "span": { + "offset": 555, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "time", + "polygon": [ + { + "x": 1.3131, + "y": 3.8428 + }, + { + "x": 1.6832, + "y": 3.8378 + }, + { + "x": 1.6883, + "y": 4.0405 + }, + { + "x": 1.3182, + "y": 4.0355 + } + ], + "span": { + "offset": 561, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "control", + "polygon": [ + { + "x": 1.739, + "y": 3.8378 + }, + { + "x": 2.3474, + "y": 3.8378 + }, + { + "x": 2.3474, + "y": 4.0456 + }, + { + "x": 1.739, + "y": 4.0405 + } + ], + "span": { + "offset": 566, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "of", + "polygon": [ + { + "x": 2.3879, + "y": 3.8378 + }, + { + "x": 2.5451, + "y": 3.8378 + }, + { + "x": 2.5451, + "y": 4.0456 + }, + { + "x": 2.3879, + "y": 4.0456 + } + ], + "span": { + "offset": 574, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "the", + "polygon": [ + { + "x": 2.5856, + "y": 3.8378 + }, + { + "x": 2.8594, + "y": 3.8378 + }, + { + "x": 2.8645, + "y": 4.0456 + }, + { + "x": 2.5856, + "y": 4.0456 + } + ], + "span": { + "offset": 577, + "length": 3 + }, + "confidence": 0.993 + }, + { + "content": "specification", + "polygon": [ + { + "x": 2.9253, + "y": 3.8327 + }, + { + "x": 3.9849, + "y": 3.8327 + }, + { + "x": 3.9849, + "y": 4.0456 + }, + { + "x": 2.9304, + "y": 4.0456 + } + ], + "span": { + "offset": 581, + "length": 13 + }, + "confidence": 0.961 + }, + { + "content": "passed", + "polygon": [ + { + "x": 4.0356, + "y": 3.8327 + }, + { + "x": 4.6694, + "y": 3.8327 + }, + { + "x": 4.6744, + "y": 4.0456 + }, + { + "x": 4.0407, + "y": 4.0456 + } + ], + "span": { + "offset": 595, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "to", + "polygon": [ + { + "x": 4.7251, + "y": 3.8327 + }, + { + "x": 4.8975, + "y": 3.8327 + }, + { + "x": 4.8975, + "y": 4.0405 + }, + { + "x": 4.7251, + "y": 4.0456 + } + ], + "span": { + "offset": 602, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "an", + "polygon": [ + { + "x": 4.9482, + "y": 3.8327 + }, + { + "x": 5.1611, + "y": 3.8327 + }, + { + "x": 5.1611, + "y": 4.0405 + }, + { + "x": 4.9482, + "y": 4.0405 + } + ], + "span": { + "offset": 605, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "ISO", + "polygon": [ + { + "x": 5.2118, + "y": 3.8327 + }, + { + "x": 5.516, + "y": 3.8327 + }, + { + "x": 5.516, + "y": 4.0355 + }, + { + "x": 5.2118, + "y": 4.0405 + } + ], + "span": { + "offset": 608, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "Committee", + "polygon": [ + { + "x": 5.6123, + "y": 3.8327 + }, + { + "x": 6.5503, + "y": 3.8378 + }, + { + "x": 6.5503, + "y": 4.0253 + }, + { + "x": 5.6123, + "y": 4.0355 + } + ], + "span": { + "offset": 612, + "length": 9 + }, + "confidence": 0.993 + }, + { + "content": "of", + "polygon": [ + { + "x": 6.601, + "y": 3.8378 + }, + { + "x": 6.7784, + "y": 3.8378 + }, + { + "x": 6.7784, + "y": 4.0203 + }, + { + "x": 6.601, + "y": 4.0253 + } + ], + "span": { + "offset": 622, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "volunteer", + "polygon": [ + { + "x": 0.7706, + "y": 4.0811 + }, + { + "x": 1.5717, + "y": 4.076 + }, + { + "x": 1.5767, + "y": 4.2788 + }, + { + "x": 0.7757, + "y": 4.2737 + } + ], + "span": { + "offset": 625, + "length": 9 + }, + "confidence": 0.993 + }, + { + "content": "industry", + "polygon": [ + { + "x": 1.6122, + "y": 4.076 + }, + { + "x": 2.3169, + "y": 4.076 + }, + { + "x": 2.3169, + "y": 4.2839 + }, + { + "x": 1.6173, + "y": 4.2788 + } + ], + "span": { + "offset": 635, + "length": 8 + }, + "confidence": 0.994 + }, + { + "content": "experts.", + "polygon": [ + { + "x": 2.3524, + "y": 4.076 + }, + { + "x": 3.0571, + "y": 4.071 + }, + { + "x": 3.0571, + "y": 4.2839 + }, + { + "x": 2.3575, + "y": 4.2839 + } + ], + "span": { + "offset": 644, + "length": 8 + }, + "confidence": 0.992 + }, + { + "content": "In", + "polygon": [ + { + "x": 3.0926, + "y": 4.071 + }, + { + "x": 3.2549, + "y": 4.071 + }, + { + "x": 3.2549, + "y": 4.2839 + }, + { + "x": 3.0977, + "y": 4.2839 + } + ], + "span": { + "offset": 653, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "2008,", + "polygon": [ + { + "x": 3.3309, + "y": 4.071 + }, + { + "x": 3.8227, + "y": 4.071 + }, + { + "x": 3.8227, + "y": 4.2839 + }, + { + "x": 3.336, + "y": 4.2839 + } + ], + "span": { + "offset": 656, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "Adobe", + "polygon": [ + { + "x": 3.8632, + "y": 4.071 + }, + { + "x": 4.4159, + "y": 4.071 + }, + { + "x": 4.4159, + "y": 4.2839 + }, + { + "x": 3.8632, + "y": 4.2839 + } + ], + "span": { + "offset": 662, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "published", + "polygon": [ + { + "x": 4.4564, + "y": 4.071 + }, + { + "x": 5.3031, + "y": 4.071 + }, + { + "x": 5.3031, + "y": 4.2788 + }, + { + "x": 4.4564, + "y": 4.2839 + } + ], + "span": { + "offset": 668, + "length": 9 + }, + "confidence": 0.974 + }, + { + "content": "a", + "polygon": [ + { + "x": 5.3589, + "y": 4.071 + }, + { + "x": 5.4603, + "y": 4.071 + }, + { + "x": 5.4603, + "y": 4.2788 + }, + { + "x": 5.3538, + "y": 4.2788 + } + ], + "span": { + "offset": 678, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "Public", + "polygon": [ + { + "x": 5.516, + "y": 4.071 + }, + { + "x": 6.0585, + "y": 4.071 + }, + { + "x": 6.0534, + "y": 4.2737 + }, + { + "x": 5.516, + "y": 4.2788 + } + ], + "span": { + "offset": 680, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "Patent", + "polygon": [ + { + "x": 6.0991, + "y": 4.071 + }, + { + "x": 6.677, + "y": 4.076 + }, + { + "x": 6.677, + "y": 4.2687 + }, + { + "x": 6.094, + "y": 4.2737 + } + ], + "span": { + "offset": 687, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "License", + "polygon": [ + { + "x": 6.7176, + "y": 4.076 + }, + { + "x": 7.3817, + "y": 4.076 + }, + { + "x": 7.3767, + "y": 4.2585 + }, + { + "x": 6.7176, + "y": 4.2687 + } + ], + "span": { + "offset": 694, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "to", + "polygon": [ + { + "x": 0.7808, + "y": 4.3143 + }, + { + "x": 0.9278, + "y": 4.3143 + }, + { + "x": 0.9329, + "y": 4.512 + }, + { + "x": 0.7808, + "y": 4.512 + } + ], + "span": { + "offset": 702, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "ISO", + "polygon": [ + { + "x": 0.9836, + "y": 4.3143 + }, + { + "x": 1.2877, + "y": 4.3143 + }, + { + "x": 1.2877, + "y": 4.5171 + }, + { + "x": 0.9836, + "y": 4.512 + } + ], + "span": { + "offset": 705, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "32000-1", + "polygon": [ + { + "x": 1.379, + "y": 4.3092 + }, + { + "x": 2.1091, + "y": 4.3092 + }, + { + "x": 2.1091, + "y": 4.5222 + }, + { + "x": 1.3841, + "y": 4.5171 + } + ], + "span": { + "offset": 709, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "granting", + "polygon": [ + { + "x": 2.1496, + "y": 4.3092 + }, + { + "x": 2.8493, + "y": 4.3092 + }, + { + "x": 2.8493, + "y": 4.5272 + }, + { + "x": 2.1496, + "y": 4.5222 + } + ], + "span": { + "offset": 717, + "length": 8 + }, + "confidence": 0.993 + }, + { + "content": "royalty-free", + "polygon": [ + { + "x": 2.8898, + "y": 4.3092 + }, + { + "x": 3.8785, + "y": 4.3092 + }, + { + "x": 3.8785, + "y": 4.5272 + }, + { + "x": 2.8898, + "y": 4.5272 + } + ], + "span": { + "offset": 726, + "length": 12 + }, + "confidence": 0.984 + }, + { + "content": "rights", + "polygon": [ + { + "x": 3.919, + "y": 4.3092 + }, + { + "x": 4.4108, + "y": 4.3143 + }, + { + "x": 4.4108, + "y": 4.5272 + }, + { + "x": 3.919, + "y": 4.5272 + } + ], + "span": { + "offset": 739, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "for", + "polygon": [ + { + "x": 4.4513, + "y": 4.3143 + }, + { + "x": 4.6998, + "y": 4.3143 + }, + { + "x": 4.6998, + "y": 4.5272 + }, + { + "x": 4.4513, + "y": 4.5272 + } + ], + "span": { + "offset": 746, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "all", + "polygon": [ + { + "x": 4.7403, + "y": 4.3143 + }, + { + "x": 4.933, + "y": 4.3143 + }, + { + "x": 4.933, + "y": 4.5272 + }, + { + "x": 4.7403, + "y": 4.5272 + } + ], + "span": { + "offset": 750, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "patents", + "polygon": [ + { + "x": 4.9735, + "y": 4.3143 + }, + { + "x": 5.6326, + "y": 4.3143 + }, + { + "x": 5.6326, + "y": 4.5272 + }, + { + "x": 4.9735, + "y": 4.5272 + } + ], + "span": { + "offset": 754, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "owned", + "polygon": [ + { + "x": 5.6732, + "y": 4.3143 + }, + { + "x": 6.2512, + "y": 4.3143 + }, + { + "x": 6.2512, + "y": 4.5222 + }, + { + "x": 5.6732, + "y": 4.5272 + } + ], + "span": { + "offset": 762, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "by", + "polygon": [ + { + "x": 6.2917, + "y": 4.3143 + }, + { + "x": 6.5249, + "y": 4.3143 + }, + { + "x": 6.5249, + "y": 4.5171 + }, + { + "x": 6.2917, + "y": 4.5222 + } + ], + "span": { + "offset": 768, + "length": 2 + }, + "confidence": 0.961 + }, + { + "content": "Adobe", + "polygon": [ + { + "x": 6.5655, + "y": 4.3143 + }, + { + "x": 7.113, + "y": 4.3194 + }, + { + "x": 7.113, + "y": 4.512 + }, + { + "x": 6.5655, + "y": 4.5171 + } + ], + "span": { + "offset": 771, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "that", + "polygon": [ + { + "x": 0.7656, + "y": 4.5576 + }, + { + "x": 1.1204, + "y": 4.5526 + }, + { + "x": 1.1154, + "y": 4.7554 + }, + { + "x": 0.7605, + "y": 4.7554 + } + ], + "span": { + "offset": 777, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "are", + "polygon": [ + { + "x": 1.161, + "y": 4.5526 + }, + { + "x": 1.4348, + "y": 4.5526 + }, + { + "x": 1.4297, + "y": 4.7554 + }, + { + "x": 1.1559, + "y": 4.7554 + } + ], + "span": { + "offset": 782, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "necessary", + "polygon": [ + { + "x": 1.4753, + "y": 4.5526 + }, + { + "x": 2.3778, + "y": 4.5526 + }, + { + "x": 2.3727, + "y": 4.7604 + }, + { + "x": 1.4703, + "y": 4.7554 + } + ], + "span": { + "offset": 786, + "length": 9 + }, + "confidence": 0.994 + }, + { + "content": "to", + "polygon": [ + { + "x": 2.4183, + "y": 4.5526 + }, + { + "x": 2.5958, + "y": 4.5475 + }, + { + "x": 2.5958, + "y": 4.7604 + }, + { + "x": 2.4133, + "y": 4.7604 + } + ], + "span": { + "offset": 796, + "length": 2 + }, + "confidence": 0.997 + }, + { + "content": "make,", + "polygon": [ + { + "x": 2.6363, + "y": 4.5475 + }, + { + "x": 3.1839, + "y": 4.5475 + }, + { + "x": 3.1839, + "y": 4.7604 + }, + { + "x": 2.6363, + "y": 4.7604 + } + ], + "span": { + "offset": 799, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "use,", + "polygon": [ + { + "x": 3.2244, + "y": 4.5475 + }, + { + "x": 3.625, + "y": 4.5475 + }, + { + "x": 3.6199, + "y": 4.7604 + }, + { + "x": 3.2244, + "y": 4.7604 + } + ], + "span": { + "offset": 805, + "length": 4 + }, + "confidence": 0.99 + }, + { + "content": "sell,", + "polygon": [ + { + "x": 3.6655, + "y": 4.5475 + }, + { + "x": 4.0204, + "y": 4.5475 + }, + { + "x": 4.0153, + "y": 4.7604 + }, + { + "x": 3.6604, + "y": 4.7604 + } + ], + "span": { + "offset": 810, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "and", + "polygon": [ + { + "x": 4.061, + "y": 4.5475 + }, + { + "x": 4.3753, + "y": 4.5475 + }, + { + "x": 4.3753, + "y": 4.7604 + }, + { + "x": 4.061, + "y": 4.7604 + } + ], + "span": { + "offset": 816, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "distribute", + "polygon": [ + { + "x": 4.4311, + "y": 4.5475 + }, + { + "x": 5.222, + "y": 4.5475 + }, + { + "x": 5.222, + "y": 4.7604 + }, + { + "x": 4.426, + "y": 4.7604 + } + ], + "span": { + "offset": 820, + "length": 10 + }, + "confidence": 0.99 + }, + { + "content": "PDF-compliant", + "polygon": [ + { + "x": 5.2777, + "y": 4.5475 + }, + { + "x": 6.5655, + "y": 4.5526 + }, + { + "x": 6.5655, + "y": 4.7554 + }, + { + "x": 5.2777, + "y": 4.7604 + } + ], + "span": { + "offset": 831, + "length": 13 + }, + "confidence": 0.985 + }, + { + "content": "implementations.", + "polygon": [ + { + "x": 0.7706, + "y": 4.7909 + }, + { + "x": 2.251, + "y": 4.7858 + }, + { + "x": 2.246, + "y": 4.9936 + }, + { + "x": 0.7656, + "y": 4.9936 + } + ], + "span": { + "offset": 845, + "length": 16 + }, + "confidence": 0.977 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 2.2916, + "y": 4.7858 + }, + { + "x": 2.6718, + "y": 4.7858 + }, + { + "x": 2.6718, + "y": 4.9936 + }, + { + "x": 2.2865, + "y": 4.9936 + } + ], + "span": { + "offset": 862, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "1.7,", + "polygon": [ + { + "x": 2.7529, + "y": 4.7807 + }, + { + "x": 3.0673, + "y": 4.7807 + }, + { + "x": 3.0673, + "y": 4.9936 + }, + { + "x": 2.7529, + "y": 4.9936 + } + ], + "span": { + "offset": 866, + "length": 4 + }, + "confidence": 0.977 + }, + { + "content": "the", + "polygon": [ + { + "x": 3.1078, + "y": 4.7807 + }, + { + "x": 3.3968, + "y": 4.7807 + }, + { + "x": 3.3917, + "y": 4.9936 + }, + { + "x": 3.1078, + "y": 4.9936 + } + ], + "span": { + "offset": 871, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "sixth", + "polygon": [ + { + "x": 3.4475, + "y": 4.7807 + }, + { + "x": 3.843, + "y": 4.7807 + }, + { + "x": 3.843, + "y": 4.9936 + }, + { + "x": 3.4475, + "y": 4.9936 + } + ], + "span": { + "offset": 875, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "edition", + "polygon": [ + { + "x": 3.8987, + "y": 4.7807 + }, + { + "x": 4.4716, + "y": 4.7807 + }, + { + "x": 4.4666, + "y": 4.9936 + }, + { + "x": 3.8937, + "y": 4.9936 + } + ], + "span": { + "offset": 881, + "length": 7 + }, + "confidence": 0.993 + }, + { + "content": "of", + "polygon": [ + { + "x": 4.5223, + "y": 4.7807 + }, + { + "x": 4.6896, + "y": 4.7807 + }, + { + "x": 4.6846, + "y": 4.9936 + }, + { + "x": 4.5223, + "y": 4.9936 + } + ], + "span": { + "offset": 889, + "length": 2 + }, + "confidence": 0.993 + }, + { + "content": "the", + "polygon": [ + { + "x": 4.7302, + "y": 4.7807 + }, + { + "x": 5.0141, + "y": 4.7807 + }, + { + "x": 5.0141, + "y": 4.9936 + }, + { + "x": 4.7251, + "y": 4.9936 + } + ], + "span": { + "offset": 892, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 5.0699, + "y": 4.7807 + }, + { + "x": 5.4501, + "y": 4.7858 + }, + { + "x": 5.4501, + "y": 4.9936 + }, + { + "x": 5.0648, + "y": 4.9936 + } + ], + "span": { + "offset": 896, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "specification", + "polygon": [ + { + "x": 5.516, + "y": 4.7858 + }, + { + "x": 6.5807, + "y": 4.7858 + }, + { + "x": 6.5807, + "y": 4.9936 + }, + { + "x": 5.516, + "y": 4.9936 + } + ], + "span": { + "offset": 900, + "length": 13 + }, + "confidence": 0.981 + }, + { + "content": "that", + "polygon": [ + { + "x": 6.6314, + "y": 4.7858 + }, + { + "x": 6.9761, + "y": 4.7909 + }, + { + "x": 6.9761, + "y": 4.9936 + }, + { + "x": 6.6314, + "y": 4.9936 + } + ], + "span": { + "offset": 914, + "length": 4 + }, + "confidence": 0.986 + }, + { + "content": "became", + "polygon": [ + { + "x": 0.7757, + "y": 5.019 + }, + { + "x": 1.4652, + "y": 5.019 + }, + { + "x": 1.4703, + "y": 5.2116 + }, + { + "x": 0.7757, + "y": 5.2066 + } + ], + "span": { + "offset": 919, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "ISO", + "polygon": [ + { + "x": 1.5058, + "y": 5.019 + }, + { + "x": 1.815, + "y": 5.019 + }, + { + "x": 1.815, + "y": 5.2167 + }, + { + "x": 1.5108, + "y": 5.2116 + } + ], + "span": { + "offset": 926, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "32000-1,", + "polygon": [ + { + "x": 1.9063, + "y": 5.019 + }, + { + "x": 2.6718, + "y": 5.019 + }, + { + "x": 2.6718, + "y": 5.2218 + }, + { + "x": 1.9113, + "y": 5.2167 + } + ], + "span": { + "offset": 930, + "length": 8 + }, + "confidence": 0.993 + }, + { + "content": "includes", + "polygon": [ + { + "x": 2.7124, + "y": 5.019 + }, + { + "x": 3.4475, + "y": 5.019 + }, + { + "x": 3.4475, + "y": 5.2268 + }, + { + "x": 2.7124, + "y": 5.2218 + } + ], + "span": { + "offset": 939, + "length": 8 + }, + "confidence": 0.993 + }, + { + "content": "some", + "polygon": [ + { + "x": 3.5033, + "y": 5.019 + }, + { + "x": 3.9697, + "y": 5.019 + }, + { + "x": 3.9697, + "y": 5.2268 + }, + { + "x": 3.5033, + "y": 5.2268 + } + ], + "span": { + "offset": 948, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "proprietary", + "polygon": [ + { + "x": 4.0103, + "y": 5.019 + }, + { + "x": 4.9634, + "y": 5.019 + }, + { + "x": 4.9634, + "y": 5.2319 + }, + { + "x": 4.0103, + "y": 5.2268 + } + ], + "span": { + "offset": 953, + "length": 11 + }, + "confidence": 0.99 + }, + { + "content": "technologies", + "polygon": [ + { + "x": 5.004, + "y": 5.019 + }, + { + "x": 6.1143, + "y": 5.0241 + }, + { + "x": 6.1143, + "y": 5.2319 + }, + { + "x": 5.004, + "y": 5.2319 + } + ], + "span": { + "offset": 965, + "length": 12 + }, + "confidence": 0.984 + }, + { + "content": "defined", + "polygon": [ + { + "x": 6.1548, + "y": 5.0241 + }, + { + "x": 6.7987, + "y": 5.0241 + }, + { + "x": 6.7936, + "y": 5.2319 + }, + { + "x": 6.1548, + "y": 5.2319 + } + ], + "span": { + "offset": 978, + "length": 7 + }, + "confidence": 0.983 + }, + { + "content": "only", + "polygon": [ + { + "x": 6.8494, + "y": 5.0241 + }, + { + "x": 7.2144, + "y": 5.0241 + }, + { + "x": 7.2094, + "y": 5.2319 + }, + { + "x": 6.8494, + "y": 5.2319 + } + ], + "span": { + "offset": 986, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "by", + "polygon": [ + { + "x": 7.255, + "y": 5.0241 + }, + { + "x": 7.473, + "y": 5.0241 + }, + { + "x": 7.4679, + "y": 5.2319 + }, + { + "x": 7.2499, + "y": 5.2319 + } + ], + "span": { + "offset": 991, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "Adobe,", + "polygon": [ + { + "x": 0.7808, + "y": 5.2573 + }, + { + "x": 1.4094, + "y": 5.2573 + }, + { + "x": 1.4094, + "y": 5.455 + }, + { + "x": 0.7808, + "y": 5.455 + } + ], + "span": { + "offset": 994, + "length": 6 + }, + "confidence": 0.993 + }, + { + "content": "such", + "polygon": [ + { + "x": 1.45, + "y": 5.2573 + }, + { + "x": 1.8404, + "y": 5.2573 + }, + { + "x": 1.8404, + "y": 5.455 + }, + { + "x": 1.45, + "y": 5.455 + } + ], + "span": { + "offset": 1001, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "as", + "polygon": [ + { + "x": 1.9063, + "y": 5.2573 + }, + { + "x": 2.1243, + "y": 5.2522 + }, + { + "x": 2.1243, + "y": 5.455 + }, + { + "x": 1.9113, + "y": 5.455 + } + ], + "span": { + "offset": 1006, + "length": 2 + }, + "confidence": 0.971 + }, + { + "content": "Adobe", + "polygon": [ + { + "x": 2.1648, + "y": 5.2522 + }, + { + "x": 2.7175, + "y": 5.2522 + }, + { + "x": 2.7175, + "y": 5.4601 + }, + { + "x": 2.1648, + "y": 5.455 + } + ], + "span": { + "offset": 1009, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "XML", + "polygon": [ + { + "x": 2.7986, + "y": 5.2522 + }, + { + "x": 3.1737, + "y": 5.2522 + }, + { + "x": 3.1737, + "y": 5.4601 + }, + { + "x": 2.7986, + "y": 5.4601 + } + ], + "span": { + "offset": 1015, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "Forms", + "polygon": [ + { + "x": 3.2143, + "y": 5.2522 + }, + { + "x": 3.7923, + "y": 5.2522 + }, + { + "x": 3.7923, + "y": 5.4601 + }, + { + "x": 3.2143, + "y": 5.4601 + } + ], + "span": { + "offset": 1019, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "Architecture", + "polygon": [ + { + "x": 3.8328, + "y": 5.2522 + }, + { + "x": 4.8569, + "y": 5.2522 + }, + { + "x": 4.8569, + "y": 5.4601 + }, + { + "x": 3.8328, + "y": 5.4601 + } + ], + "span": { + "offset": 1025, + "length": 12 + }, + "confidence": 0.983 + }, + { + "content": "(XFA)", + "polygon": [ + { + "x": 4.9127, + "y": 5.2522 + }, + { + "x": 5.4248, + "y": 5.2573 + }, + { + "x": 5.4197, + "y": 5.4651 + }, + { + "x": 4.9076, + "y": 5.4601 + } + ], + "span": { + "offset": 1038, + "length": 5 + }, + "confidence": 0.979 + }, + { + "content": "and", + "polygon": [ + { + "x": 5.4653, + "y": 5.2573 + }, + { + "x": 5.7847, + "y": 5.2573 + }, + { + "x": 5.7847, + "y": 5.4651 + }, + { + "x": 5.4603, + "y": 5.4651 + } + ], + "span": { + "offset": 1044, + "length": 3 + }, + "confidence": 0.991 + }, + { + "content": "JavaScript", + "polygon": [ + { + "x": 5.8557, + "y": 5.2573 + }, + { + "x": 6.7733, + "y": 5.2623 + }, + { + "x": 6.7683, + "y": 5.4702 + }, + { + "x": 5.8506, + "y": 5.4651 + } + ], + "span": { + "offset": 1048, + "length": 10 + }, + "confidence": 0.993 + }, + { + "content": "extension", + "polygon": [ + { + "x": 0.7656, + "y": 5.4955 + }, + { + "x": 1.5919, + "y": 5.4955 + }, + { + "x": 1.597, + "y": 5.6882 + }, + { + "x": 0.7757, + "y": 5.6831 + } + ], + "span": { + "offset": 1059, + "length": 9 + }, + "confidence": 0.985 + }, + { + "content": "for", + "polygon": [ + { + "x": 1.6426, + "y": 5.4955 + }, + { + "x": 1.9012, + "y": 5.4905 + }, + { + "x": 1.9063, + "y": 5.6882 + }, + { + "x": 1.6477, + "y": 5.6882 + } + ], + "span": { + "offset": 1069, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "Acrobat,", + "polygon": [ + { + "x": 1.9418, + "y": 5.4905 + }, + { + "x": 2.6668, + "y": 5.4905 + }, + { + "x": 2.6718, + "y": 5.6933 + }, + { + "x": 1.9468, + "y": 5.6882 + } + ], + "span": { + "offset": 1073, + "length": 8 + }, + "confidence": 0.994 + }, + { + "content": "which", + "polygon": [ + { + "x": 2.7073, + "y": 5.4905 + }, + { + "x": 3.1839, + "y": 5.4905 + }, + { + "x": 3.1889, + "y": 5.6933 + }, + { + "x": 2.7073, + "y": 5.6933 + } + ], + "span": { + "offset": 1082, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "are", + "polygon": [ + { + "x": 3.2599, + "y": 5.4905 + }, + { + "x": 3.5337, + "y": 5.4905 + }, + { + "x": 3.5388, + "y": 5.6933 + }, + { + "x": 3.265, + "y": 5.6933 + } + ], + "span": { + "offset": 1088, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "referenced", + "polygon": [ + { + "x": 3.5844, + "y": 5.4905 + }, + { + "x": 4.5173, + "y": 5.4905 + }, + { + "x": 4.5173, + "y": 5.6933 + }, + { + "x": 3.5895, + "y": 5.6933 + } + ], + "span": { + "offset": 1092, + "length": 10 + }, + "confidence": 0.992 + }, + { + "content": "by", + "polygon": [ + { + "x": 4.568, + "y": 5.4905 + }, + { + "x": 4.786, + "y": 5.4905 + }, + { + "x": 4.791, + "y": 5.6933 + }, + { + "x": 4.568, + "y": 5.6933 + } + ], + "span": { + "offset": 1103, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "ISO", + "polygon": [ + { + "x": 4.8265, + "y": 5.4905 + }, + { + "x": 5.1256, + "y": 5.4905 + }, + { + "x": 5.1256, + "y": 5.6933 + }, + { + "x": 4.8265, + "y": 5.6933 + } + ], + "span": { + "offset": 1106, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "32000-1", + "polygon": [ + { + "x": 5.227, + "y": 5.4905 + }, + { + "x": 5.952, + "y": 5.4905 + }, + { + "x": 5.952, + "y": 5.6882 + }, + { + "x": 5.227, + "y": 5.6933 + } + ], + "span": { + "offset": 1110, + "length": 7 + }, + "confidence": 0.991 + }, + { + "content": "as", + "polygon": [ + { + "x": 6.0027, + "y": 5.4905 + }, + { + "x": 6.2005, + "y": 5.4905 + }, + { + "x": 6.2005, + "y": 5.6882 + }, + { + "x": 6.0027, + "y": 5.6882 + } + ], + "span": { + "offset": 1118, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "normative", + "polygon": [ + { + "x": 6.2359, + "y": 5.4905 + }, + { + "x": 7.1029, + "y": 5.4955 + }, + { + "x": 7.1029, + "y": 5.678 + }, + { + "x": 6.2359, + "y": 5.6882 + } + ], + "span": { + "offset": 1121, + "length": 9 + }, + "confidence": 0.994 + }, + { + "content": "and", + "polygon": [ + { + "x": 0.7757, + "y": 5.7338 + }, + { + "x": 1.085, + "y": 5.7338 + }, + { + "x": 1.09, + "y": 5.9366 + }, + { + "x": 0.7858, + "y": 5.9366 + } + ], + "span": { + "offset": 1131, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "indispensable", + "polygon": [ + { + "x": 1.1357, + "y": 5.7338 + }, + { + "x": 2.3372, + "y": 5.7287 + }, + { + "x": 2.3423, + "y": 5.9366 + }, + { + "x": 1.1458, + "y": 5.9366 + } + ], + "span": { + "offset": 1135, + "length": 13 + }, + "confidence": 0.987 + }, + { + "content": "for", + "polygon": [ + { + "x": 2.3778, + "y": 5.7287 + }, + { + "x": 2.6211, + "y": 5.7287 + }, + { + "x": 2.6262, + "y": 5.9366 + }, + { + "x": 2.3828, + "y": 5.9366 + } + ], + "span": { + "offset": 1149, + "length": 3 + }, + "confidence": 0.983 + }, + { + "content": "the", + "polygon": [ + { + "x": 2.6617, + "y": 5.7287 + }, + { + "x": 2.9405, + "y": 5.7287 + }, + { + "x": 2.9456, + "y": 5.9366 + }, + { + "x": 2.6617, + "y": 5.9366 + } + ], + "span": { + "offset": 1153, + "length": 3 + }, + "confidence": 0.994 + }, + { + "content": "full", + "polygon": [ + { + "x": 2.9963, + "y": 5.7287 + }, + { + "x": 3.2498, + "y": 5.7237 + }, + { + "x": 3.2498, + "y": 5.9366 + }, + { + "x": 2.9963, + "y": 5.9366 + } + ], + "span": { + "offset": 1157, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "implementation", + "polygon": [ + { + "x": 3.2853, + "y": 5.7237 + }, + { + "x": 4.6085, + "y": 5.7237 + }, + { + "x": 4.6136, + "y": 5.9315 + }, + { + "x": 3.2903, + "y": 5.9366 + } + ], + "span": { + "offset": 1162, + "length": 14 + }, + "confidence": 0.988 + }, + { + "content": "of", + "polygon": [ + { + "x": 4.6744, + "y": 5.7237 + }, + { + "x": 4.8519, + "y": 5.7237 + }, + { + "x": 4.8519, + "y": 5.9315 + }, + { + "x": 4.6795, + "y": 5.9315 + } + ], + "span": { + "offset": 1177, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "the", + "polygon": [ + { + "x": 4.8874, + "y": 5.7237 + }, + { + "x": 5.1713, + "y": 5.7237 + }, + { + "x": 5.1713, + "y": 5.9265 + }, + { + "x": 4.8924, + "y": 5.9265 + } + ], + "span": { + "offset": 1180, + "length": 3 + }, + "confidence": 0.994 + }, + { + "content": "ISO", + "polygon": [ + { + "x": 5.2118, + "y": 5.7237 + }, + { + "x": 5.516, + "y": 5.7237 + }, + { + "x": 5.516, + "y": 5.9214 + }, + { + "x": 5.2118, + "y": 5.9265 + } + ], + "span": { + "offset": 1184, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "32000-1", + "polygon": [ + { + "x": 5.6123, + "y": 5.7237 + }, + { + "x": 6.3221, + "y": 5.7287 + }, + { + "x": 6.3221, + "y": 5.9163 + }, + { + "x": 5.6123, + "y": 5.9214 + } + ], + "span": { + "offset": 1188, + "length": 7 + }, + "confidence": 0.993 + }, + { + "content": "specification.", + "polygon": [ + { + "x": 0.7909, + "y": 5.967 + }, + { + "x": 1.9316, + "y": 5.967 + }, + { + "x": 1.9316, + "y": 6.1799 + }, + { + "x": 0.7858, + "y": 6.1799 + } + ], + "span": { + "offset": 1196, + "length": 14 + }, + "confidence": 0.975 + }, + { + "content": "These", + "polygon": [ + { + "x": 1.9722, + "y": 5.967 + }, + { + "x": 2.4842, + "y": 5.967 + }, + { + "x": 2.4842, + "y": 6.1799 + }, + { + "x": 1.9722, + "y": 6.1799 + } + ], + "span": { + "offset": 1211, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "proprietary", + "polygon": [ + { + "x": 2.54, + "y": 5.967 + }, + { + "x": 3.483, + "y": 5.967 + }, + { + "x": 3.483, + "y": 6.1799 + }, + { + "x": 2.54, + "y": 6.1799 + } + ], + "span": { + "offset": 1217, + "length": 11 + }, + "confidence": 0.993 + }, + { + "content": "technologies", + "polygon": [ + { + "x": 3.5236, + "y": 5.967 + }, + { + "x": 4.6389, + "y": 5.967 + }, + { + "x": 4.644, + "y": 6.1749 + }, + { + "x": 3.5236, + "y": 6.1799 + } + ], + "span": { + "offset": 1229, + "length": 12 + }, + "confidence": 0.991 + }, + { + "content": "are", + "polygon": [ + { + "x": 4.6795, + "y": 5.967 + }, + { + "x": 4.9533, + "y": 5.967 + }, + { + "x": 4.9533, + "y": 6.1698 + }, + { + "x": 4.6846, + "y": 6.1749 + } + ], + "span": { + "offset": 1242, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "not", + "polygon": [ + { + "x": 5.004, + "y": 5.967 + }, + { + "x": 5.3031, + "y": 5.962 + }, + { + "x": 5.3031, + "y": 6.1698 + }, + { + "x": 5.009, + "y": 6.1698 + } + ], + "span": { + "offset": 1246, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "standardized", + "polygon": [ + { + "x": 5.3436, + "y": 5.962 + }, + { + "x": 6.4489, + "y": 5.962 + }, + { + "x": 6.4489, + "y": 6.1597 + }, + { + "x": 5.3436, + "y": 6.1698 + } + ], + "span": { + "offset": 1250, + "length": 12 + }, + "confidence": 0.992 + }, + { + "content": "and", + "polygon": [ + { + "x": 6.5148, + "y": 5.962 + }, + { + "x": 6.824, + "y": 5.962 + }, + { + "x": 6.8291, + "y": 6.1546 + }, + { + "x": 6.5199, + "y": 6.1546 + } + ], + "span": { + "offset": 1263, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "their", + "polygon": [ + { + "x": 6.8798, + "y": 5.962 + }, + { + "x": 7.2702, + "y": 5.962 + }, + { + "x": 7.2753, + "y": 6.1495 + }, + { + "x": 6.8798, + "y": 6.1495 + } + ], + "span": { + "offset": 1267, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "specification", + "polygon": [ + { + "x": 0.7757, + "y": 6.2104 + }, + { + "x": 1.8302, + "y": 6.2002 + }, + { + "x": 1.8353, + "y": 6.4132 + }, + { + "x": 0.7808, + "y": 6.4132 + } + ], + "span": { + "offset": 1273, + "length": 13 + }, + "confidence": 0.989 + }, + { + "content": "is", + "polygon": [ + { + "x": 1.886, + "y": 6.2002 + }, + { + "x": 2.0482, + "y": 6.2002 + }, + { + "x": 2.0482, + "y": 6.4132 + }, + { + "x": 1.886, + "y": 6.4132 + } + ], + "span": { + "offset": 1287, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "published", + "polygon": [ + { + "x": 2.0888, + "y": 6.2002 + }, + { + "x": 2.9253, + "y": 6.2002 + }, + { + "x": 2.9253, + "y": 6.4132 + }, + { + "x": 2.0888, + "y": 6.4132 + } + ], + "span": { + "offset": 1290, + "length": 9 + }, + "confidence": 0.993 + }, + { + "content": "only", + "polygon": [ + { + "x": 2.9811, + "y": 6.2002 + }, + { + "x": 3.341, + "y": 6.2002 + }, + { + "x": 3.3461, + "y": 6.4132 + }, + { + "x": 2.9811, + "y": 6.4132 + } + ], + "span": { + "offset": 1300, + "length": 4 + }, + "confidence": 0.983 + }, + { + "content": "on", + "polygon": [ + { + "x": 3.3816, + "y": 6.2002 + }, + { + "x": 3.5996, + "y": 6.1952 + }, + { + "x": 3.5996, + "y": 6.4132 + }, + { + "x": 3.3867, + "y": 6.4132 + } + ], + "span": { + "offset": 1305, + "length": 2 + }, + "confidence": 0.991 + }, + { + "content": "Adobe's", + "polygon": [ + { + "x": 3.6554, + "y": 6.1952 + }, + { + "x": 4.355, + "y": 6.1952 + }, + { + "x": 4.3601, + "y": 6.4081 + }, + { + "x": 3.6554, + "y": 6.4132 + } + ], + "span": { + "offset": 1308, + "length": 7 + }, + "confidence": 0.968 + }, + { + "content": "website.", + "polygon": [ + { + "x": 4.3956, + "y": 6.1952 + }, + { + "x": 5.1256, + "y": 6.2002 + }, + { + "x": 5.1256, + "y": 6.4081 + }, + { + "x": 4.3956, + "y": 6.4081 + } + ], + "span": { + "offset": 1316, + "length": 8 + }, + "confidence": 0.993 + }, + { + "content": "Many", + "polygon": [ + { + "x": 5.1662, + "y": 6.2002 + }, + { + "x": 5.6681, + "y": 6.2002 + }, + { + "x": 5.6681, + "y": 6.403 + }, + { + "x": 5.1662, + "y": 6.4081 + } + ], + "span": { + "offset": 1325, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "of", + "polygon": [ + { + "x": 5.7087, + "y": 6.2002 + }, + { + "x": 5.8709, + "y": 6.2002 + }, + { + "x": 5.8709, + "y": 6.403 + }, + { + "x": 5.7087, + "y": 6.403 + } + ], + "span": { + "offset": 1330, + "length": 2 + }, + "confidence": 0.997 + }, + { + "content": "them", + "polygon": [ + { + "x": 5.9115, + "y": 6.2002 + }, + { + "x": 6.2866, + "y": 6.2002 + }, + { + "x": 6.2866, + "y": 6.403 + }, + { + "x": 5.9115, + "y": 6.403 + } + ], + "span": { + "offset": 1333, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "are", + "polygon": [ + { + "x": 6.4083, + "y": 6.2002 + }, + { + "x": 6.6922, + "y": 6.2053 + }, + { + "x": 6.6922, + "y": 6.3979 + }, + { + "x": 6.4083, + "y": 6.403 + } + ], + "span": { + "offset": 1338, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "also", + "polygon": [ + { + "x": 6.748, + "y": 6.2053 + }, + { + "x": 7.0978, + "y": 6.2053 + }, + { + "x": 7.0978, + "y": 6.3979 + }, + { + "x": 6.748, + "y": 6.3979 + } + ], + "span": { + "offset": 1342, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "not", + "polygon": [ + { + "x": 7.1384, + "y": 6.2053 + }, + { + "x": 7.4375, + "y": 6.2104 + }, + { + "x": 7.4375, + "y": 6.3979 + }, + { + "x": 7.1384, + "y": 6.3979 + } + ], + "span": { + "offset": 1347, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "supported", + "polygon": [ + { + "x": 0.7706, + "y": 6.4486 + }, + { + "x": 1.6376, + "y": 6.4436 + }, + { + "x": 1.6376, + "y": 6.6514 + }, + { + "x": 0.7706, + "y": 6.6514 + } + ], + "span": { + "offset": 1351, + "length": 9 + }, + "confidence": 0.993 + }, + { + "content": "by", + "polygon": [ + { + "x": 1.6781, + "y": 6.4436 + }, + { + "x": 1.9063, + "y": 6.4385 + }, + { + "x": 1.9063, + "y": 6.6514 + }, + { + "x": 1.6781, + "y": 6.6514 + } + ], + "span": { + "offset": 1361, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "popular", + "polygon": [ + { + "x": 1.9468, + "y": 6.4385 + }, + { + "x": 2.611, + "y": 6.4385 + }, + { + "x": 2.611, + "y": 6.6514 + }, + { + "x": 1.9468, + "y": 6.6514 + } + ], + "span": { + "offset": 1364, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "third-party", + "polygon": [ + { + "x": 2.6515, + "y": 6.4385 + }, + { + "x": 3.5286, + "y": 6.4334 + }, + { + "x": 3.5286, + "y": 6.6464 + }, + { + "x": 2.6515, + "y": 6.6514 + } + ], + "span": { + "offset": 1372, + "length": 11 + }, + "confidence": 0.984 + }, + { + "content": "implementations", + "polygon": [ + { + "x": 3.5692, + "y": 6.4334 + }, + { + "x": 5.0192, + "y": 6.4334 + }, + { + "x": 5.0192, + "y": 6.6362 + }, + { + "x": 3.5692, + "y": 6.6464 + } + ], + "span": { + "offset": 1384, + "length": 15 + }, + "confidence": 0.989 + }, + { + "content": "of", + "polygon": [ + { + "x": 5.0597, + "y": 6.4334 + }, + { + "x": 5.2321, + "y": 6.4334 + }, + { + "x": 5.2321, + "y": 6.6311 + }, + { + "x": 5.0597, + "y": 6.6362 + } + ], + "span": { + "offset": 1400, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "PDF.", + "polygon": [ + { + "x": 5.2727, + "y": 6.4334 + }, + { + "x": 5.6985, + "y": 6.4385 + }, + { + "x": 5.6985, + "y": 6.6261 + }, + { + "x": 5.2727, + "y": 6.6311 + } + ], + "span": { + "offset": 1403, + "length": 4 + }, + "confidence": 0.979 + }, + { + "content": "Column", + "polygon": [ + { + "x": 2.5147, + "y": 7.128 + }, + { + "x": 3.0166, + "y": 7.128 + }, + { + "x": 3.0166, + "y": 7.2699 + }, + { + "x": 2.5147, + "y": 7.2699 + } + ], + "span": { + "offset": 1408, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "1", + "polygon": [ + { + "x": 3.0825, + "y": 7.128 + }, + { + "x": 3.1484, + "y": 7.128 + }, + { + "x": 3.1484, + "y": 7.2699 + }, + { + "x": 3.0825, + "y": 7.2699 + } + ], + "span": { + "offset": 1415, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "Column", + "polygon": [ + { + "x": 4.1877, + "y": 7.1229 + }, + { + "x": 4.6795, + "y": 7.133 + }, + { + "x": 4.6795, + "y": 7.2649 + }, + { + "x": 4.1877, + "y": 7.2699 + } + ], + "span": { + "offset": 1417, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "2", + "polygon": [ + { + "x": 4.7403, + "y": 7.133 + }, + { + "x": 4.8113, + "y": 7.133 + }, + { + "x": 4.8164, + "y": 7.2649 + }, + { + "x": 4.7454, + "y": 7.2649 + } + ], + "span": { + "offset": 1424, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "Column", + "polygon": [ + { + "x": 5.8557, + "y": 7.1178 + }, + { + "x": 6.3576, + "y": 7.1178 + }, + { + "x": 6.3576, + "y": 7.2851 + }, + { + "x": 5.8506, + "y": 7.2801 + } + ], + "span": { + "offset": 1426, + "length": 6 + }, + "confidence": 0.993 + }, + { + "content": "3", + "polygon": [ + { + "x": 6.4134, + "y": 7.1178 + }, + { + "x": 6.4996, + "y": 7.1178 + }, + { + "x": 6.5046, + "y": 7.2851 + }, + { + "x": 6.4134, + "y": 7.2851 + } + ], + "span": { + "offset": 1433, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "A", + "polygon": [ + { + "x": 0.8467, + "y": 7.4524 + }, + { + "x": 0.9126, + "y": 7.4524 + }, + { + "x": 0.9176, + "y": 7.5741 + }, + { + "x": 0.8517, + "y": 7.5741 + } + ], + "span": { + "offset": 1435, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "324", + "polygon": [ + { + "x": 3.843, + "y": 7.4474 + }, + { + "x": 4.066, + "y": 7.4423 + }, + { + "x": 4.0711, + "y": 7.5843 + }, + { + "x": 3.843, + "y": 7.5893 + } + ], + "span": { + "offset": 1437, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "55", + "polygon": [ + { + "x": 4.1776, + "y": 7.4423 + }, + { + "x": 4.3246, + "y": 7.4474 + }, + { + "x": 4.3297, + "y": 7.5944 + }, + { + "x": 4.1826, + "y": 7.5944 + } + ], + "span": { + "offset": 1441, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "million", + "polygon": [ + { + "x": 4.3601, + "y": 7.4474 + }, + { + "x": 4.7707, + "y": 7.4524 + }, + { + "x": 4.7707, + "y": 7.5893 + }, + { + "x": 4.3652, + "y": 7.5944 + } + ], + "span": { + "offset": 1444, + "length": 7 + }, + "confidence": 0.993 + }, + { + "content": "units", + "polygon": [ + { + "x": 4.8164, + "y": 7.4524 + }, + { + "x": 5.1206, + "y": 7.4524 + }, + { + "x": 5.1206, + "y": 7.5893 + }, + { + "x": 4.8164, + "y": 7.5893 + } + ], + "span": { + "offset": 1452, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "2022", + "polygon": [ + { + "x": 7.113, + "y": 7.4524 + }, + { + "x": 7.4172, + "y": 7.4524 + }, + { + "x": 7.4122, + "y": 7.5792 + }, + { + "x": 7.108, + "y": 7.5792 + } + ], + "span": { + "offset": 1458, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "B", + "polygon": [ + { + "x": 0.8467, + "y": 7.7668 + }, + { + "x": 0.9126, + "y": 7.7668 + }, + { + "x": 0.9075, + "y": 7.8884 + }, + { + "x": 0.8467, + "y": 7.8834 + } + ], + "span": { + "offset": 1463, + "length": 1 + }, + "confidence": 0.996 + }, + { + "content": "234,523.00", + "polygon": [ + { + "x": 2.5147, + "y": 7.7668 + }, + { + "x": 3.1991, + "y": 7.7617 + }, + { + "x": 3.2042, + "y": 7.9036 + }, + { + "x": 2.5147, + "y": 7.9036 + } + ], + "span": { + "offset": 1465, + "length": 10 + }, + "confidence": 0.993 + }, + { + "content": "The", + "polygon": [ + { + "x": 4.1877, + "y": 7.7566 + }, + { + "x": 4.4108, + "y": 7.7617 + }, + { + "x": 4.4108, + "y": 7.9138 + }, + { + "x": 4.1928, + "y": 7.9138 + } + ], + "span": { + "offset": 1476, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "quick", + "polygon": [ + { + "x": 4.4513, + "y": 7.7617 + }, + { + "x": 4.791, + "y": 7.7617 + }, + { + "x": 4.7961, + "y": 7.9138 + }, + { + "x": 4.4513, + "y": 7.9138 + } + ], + "span": { + "offset": 1480, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "brown", + "polygon": [ + { + "x": 4.8214, + "y": 7.7617 + }, + { + "x": 5.2169, + "y": 7.7617 + }, + { + "x": 5.2169, + "y": 7.9138 + }, + { + "x": 4.8265, + "y": 7.9138 + } + ], + "span": { + "offset": 1486, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "fox", + "polygon": [ + { + "x": 5.2575, + "y": 7.7617 + }, + { + "x": 5.4653, + "y": 7.7566 + }, + { + "x": 5.4704, + "y": 7.9188 + }, + { + "x": 5.2575, + "y": 7.9138 + } + ], + "span": { + "offset": 1492, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "jumped", + "polygon": [ + { + "x": 4.1674, + "y": 7.9341 + }, + { + "x": 4.6389, + "y": 7.9341 + }, + { + "x": 4.644, + "y": 8.0912 + }, + { + "x": 4.1725, + "y": 8.0912 + } + ], + "span": { + "offset": 1496, + "length": 6 + }, + "confidence": 0.993 + }, + { + "content": "over", + "polygon": [ + { + "x": 4.6795, + "y": 7.9341 + }, + { + "x": 4.9533, + "y": 7.9341 + }, + { + "x": 4.9583, + "y": 8.0912 + }, + { + "x": 4.6846, + "y": 8.0912 + } + ], + "span": { + "offset": 1503, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "the", + "polygon": [ + { + "x": 4.9837, + "y": 7.9341 + }, + { + "x": 5.1865, + "y": 7.9341 + }, + { + "x": 5.1865, + "y": 8.0912 + }, + { + "x": 4.9888, + "y": 8.0912 + } + ], + "span": { + "offset": 1508, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "lazy", + "polygon": [ + { + "x": 5.2169, + "y": 7.9341 + }, + { + "x": 5.4755, + "y": 7.9341 + }, + { + "x": 5.4755, + "y": 8.0912 + }, + { + "x": 5.2169, + "y": 8.0912 + } + ], + "span": { + "offset": 1512, + "length": 4 + }, + "confidence": 0.992 + }, + { + "content": "dog.", + "polygon": [ + { + "x": 4.1776, + "y": 8.1014 + }, + { + "x": 4.4666, + "y": 8.1014 + }, + { + "x": 4.4666, + "y": 8.2433 + }, + { + "x": 4.1776, + "y": 8.2382 + } + ], + "span": { + "offset": 1517, + "length": 4 + }, + "confidence": 0.99 + }, + { + "content": "54x", + "polygon": [ + { + "x": 5.8456, + "y": 7.7668 + }, + { + "x": 6.0838, + "y": 7.7718 + }, + { + "x": 6.0889, + "y": 7.9138 + }, + { + "x": 5.8506, + "y": 7.9138 + } + ], + "span": { + "offset": 1522, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "growth", + "polygon": [ + { + "x": 6.1143, + "y": 7.7718 + }, + { + "x": 6.5401, + "y": 7.7668 + }, + { + "x": 6.5401, + "y": 7.9188 + }, + { + "x": 6.1193, + "y": 7.9138 + } + ], + "span": { + "offset": 1526, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "C", + "polygon": [ + { + "x": 0.8467, + "y": 8.365 + }, + { + "x": 0.9227, + "y": 8.365 + }, + { + "x": 0.9227, + "y": 8.5069 + }, + { + "x": 0.8467, + "y": 8.5019 + } + ], + "span": { + "offset": 1533, + "length": 1 + }, + "confidence": 0.945 + }, + { + "content": "23.53%", + "polygon": [ + { + "x": 2.5096, + "y": 8.3396 + }, + { + "x": 2.9963, + "y": 8.3396 + }, + { + "x": 2.9963, + "y": 8.512 + }, + { + "x": 2.5096, + "y": 8.5171 + } + ], + "span": { + "offset": 1535, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "A", + "polygon": [ + { + "x": 4.1826, + "y": 8.3701 + }, + { + "x": 4.2638, + "y": 8.3701 + }, + { + "x": 4.2638, + "y": 8.5221 + }, + { + "x": 4.1877, + "y": 8.5272 + } + ], + "span": { + "offset": 1542, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "short", + "polygon": [ + { + "x": 4.3145, + "y": 8.3701 + }, + { + "x": 4.6389, + "y": 8.3751 + }, + { + "x": 4.6389, + "y": 8.5221 + }, + { + "x": 4.3145, + "y": 8.5221 + } + ], + "span": { + "offset": 1544, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "string.", + "polygon": [ + { + "x": 4.6643, + "y": 8.3751 + }, + { + "x": 5.0597, + "y": 8.3853 + }, + { + "x": 5.0597, + "y": 8.5272 + }, + { + "x": 4.6694, + "y": 8.5272 + } + ], + "span": { + "offset": 1550, + "length": 7 + }, + "confidence": 0.995 + }, + { + "content": "D", + "polygon": [ + { + "x": 0.8416, + "y": 8.6945 + }, + { + "x": 0.9176, + "y": 8.6945 + }, + { + "x": 0.9126, + "y": 8.8213 + }, + { + "x": 0.8416, + "y": 8.8162 + } + ], + "span": { + "offset": 1558, + "length": 1 + }, + "confidence": 0.972 + }, + { + "content": "$54.35", + "polygon": [ + { + "x": 2.4994, + "y": 8.6945 + }, + { + "x": 2.9355, + "y": 8.6894 + }, + { + "x": 2.9355, + "y": 8.8314 + }, + { + "x": 2.5096, + "y": 8.8314 + } + ], + "span": { + "offset": 1560, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "$6345.", + "polygon": [ + { + "x": 4.1826, + "y": 8.6894 + }, + { + "x": 4.6085, + "y": 8.6945 + }, + { + "x": 4.6136, + "y": 8.8365 + }, + { + "x": 4.1877, + "y": 8.8314 + } + ], + "span": { + "offset": 1567, + "length": 6 + }, + "confidence": 0.993 + } + ], + "selection_marks": [], + "spans": [ + { + "offset": 0, + "length": 1573 + } + ], + "kind": "document", + "annotations": [], + "barcodes": [], + "formulas": [], + "images": [] + }, + { + "page_number": 2, + "angle": -0.17829999327659607, + "width": 8.2639, + "height": 11.6806, + "unit": "inch", + "lines": [ + { + "content": "Page 2 of Sample PDF", + "polygon": [ + { + "x": 0.7808, + "y": 0.8365 + }, + { + "x": 4.0356, + "y": 0.8264 + }, + { + "x": 4.0407, + "y": 1.1508 + }, + { + "x": 0.7808, + "y": 1.161 + } + ], + "spans": [ + { + "offset": 1574, + "length": 20 + } + ] + } + ], + "words": [ + { + "content": "Page", + "polygon": [ + { + "x": 0.7909, + "y": 0.8416 + }, + { + "x": 1.5058, + "y": 0.8365 + }, + { + "x": 1.5007, + "y": 1.161 + }, + { + "x": 0.7808, + "y": 1.1559 + } + ], + "span": { + "offset": 1574, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "2", + "polygon": [ + { + "x": 1.6325, + "y": 0.8365 + }, + { + "x": 1.7998, + "y": 0.8365 + }, + { + "x": 1.7998, + "y": 1.161 + }, + { + "x": 1.6274, + "y": 1.161 + } + ], + "span": { + "offset": 1579, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "of", + "polygon": [ + { + "x": 1.8657, + "y": 0.8365 + }, + { + "x": 2.18, + "y": 0.8365 + }, + { + "x": 2.18, + "y": 1.161 + }, + { + "x": 1.8606, + "y": 1.161 + } + ], + "span": { + "offset": 1581, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "Sample", + "polygon": [ + { + "x": 2.246, + "y": 0.8365 + }, + { + "x": 3.3258, + "y": 0.8314 + }, + { + "x": 3.3309, + "y": 1.1559 + }, + { + "x": 2.246, + "y": 1.161 + } + ], + "span": { + "offset": 1584, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 3.412, + "y": 0.8314 + }, + { + "x": 4.0052, + "y": 0.8314 + }, + { + "x": 4.0103, + "y": 1.1457 + }, + { + "x": 3.4171, + "y": 1.1559 + } + ], + "span": { + "offset": 1591, + "length": 3 + }, + "confidence": 0.995 + } + ], + "selection_marks": [], + "spans": [ + { + "offset": 1574, + "length": 20 + } + ], + "kind": "document", + "annotations": [], + "barcodes": [], + "formulas": [], + "images": [] + }, + { + "page_number": 3, + "angle": null, + "width": 8.2639, + "height": 11.6806, + "unit": "inch", + "lines": [], + "words": [], + "selection_marks": [], + "spans": [ + { + "offset": 1595, + "length": 0 + } + ], + "kind": "document", + "annotations": [], + "barcodes": [], + "formulas": [], + "images": [] + }, + { + "page_number": 4, + "angle": -0.13539999723434448, + "width": 8.2639, + "height": 11.6806, + "unit": "inch", + "lines": [ + { + "content": "Page 4 of Sample PDF", + "polygon": [ + { + "x": 0.7808, + "y": 0.8416 + }, + { + "x": 4.0356, + "y": 0.8264 + }, + { + "x": 4.0356, + "y": 1.1508 + }, + { + "x": 0.7808, + "y": 1.161 + } + ], + "spans": [ + { + "offset": 1596, + "length": 20 + } + ] + }, + { + "content": "... the page 3 is empty.", + "polygon": [ + { + "x": 0.7858, + "y": 1.5513 + }, + { + "x": 2.9304, + "y": 1.5463 + }, + { + "x": 2.9304, + "y": 1.7744 + }, + { + "x": 0.7858, + "y": 1.7795 + } + ], + "spans": [ + { + "offset": 1617, + "length": 24 + } + ] + } + ], + "words": [ + { + "content": "Page", + "polygon": [ + { + "x": 0.7909, + "y": 0.8466 + }, + { + "x": 1.5159, + "y": 0.8416 + }, + { + "x": 1.5108, + "y": 1.161 + }, + { + "x": 0.7808, + "y": 1.1508 + } + ], + "span": { + "offset": 1596, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "4", + "polygon": [ + { + "x": 1.597, + "y": 0.8416 + }, + { + "x": 1.7643, + "y": 0.8416 + }, + { + "x": 1.7592, + "y": 1.161 + }, + { + "x": 1.5919, + "y": 1.161 + } + ], + "span": { + "offset": 1601, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "of", + "polygon": [ + { + "x": 1.8708, + "y": 0.8416 + }, + { + "x": 2.18, + "y": 0.8416 + }, + { + "x": 2.18, + "y": 1.161 + }, + { + "x": 1.8657, + "y": 1.161 + } + ], + "span": { + "offset": 1603, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "Sample", + "polygon": [ + { + "x": 2.246, + "y": 0.8416 + }, + { + "x": 3.3106, + "y": 0.8365 + }, + { + "x": 3.3106, + "y": 1.1559 + }, + { + "x": 2.2409, + "y": 1.161 + } + ], + "span": { + "offset": 1606, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 3.412, + "y": 0.8314 + }, + { + "x": 3.9951, + "y": 0.8314 + }, + { + "x": 4.0001, + "y": 1.1407 + }, + { + "x": 3.412, + "y": 1.1559 + } + ], + "span": { + "offset": 1613, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "...", + "polygon": [ + { + "x": 0.7858, + "y": 1.5817 + }, + { + "x": 0.9836, + "y": 1.5716 + }, + { + "x": 0.9937, + "y": 1.7795 + }, + { + "x": 0.796, + "y": 1.7795 + } + ], + "span": { + "offset": 1617, + "length": 3 + }, + "confidence": 0.989 + }, + { + "content": "the", + "polygon": [ + { + "x": 1.0292, + "y": 1.5665 + }, + { + "x": 1.3283, + "y": 1.5564 + }, + { + "x": 1.3334, + "y": 1.7744 + }, + { + "x": 1.0343, + "y": 1.7795 + } + ], + "span": { + "offset": 1621, + "length": 3 + }, + "confidence": 0.994 + }, + { + "content": "page", + "polygon": [ + { + "x": 1.3891, + "y": 1.5564 + }, + { + "x": 1.8606, + "y": 1.5513 + }, + { + "x": 1.8657, + "y": 1.7744 + }, + { + "x": 1.3942, + "y": 1.7744 + } + ], + "span": { + "offset": 1625, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "3", + "polygon": [ + { + "x": 1.9367, + "y": 1.5463 + }, + { + "x": 2.033, + "y": 1.5463 + }, + { + "x": 2.0381, + "y": 1.7744 + }, + { + "x": 1.9367, + "y": 1.7744 + } + ], + "span": { + "offset": 1630, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "is", + "polygon": [ + { + "x": 2.0786, + "y": 1.5463 + }, + { + "x": 2.2662, + "y": 1.5513 + }, + { + "x": 2.2662, + "y": 1.7744 + }, + { + "x": 2.0786, + "y": 1.7744 + } + ], + "span": { + "offset": 1632, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "empty.", + "polygon": [ + { + "x": 2.3068, + "y": 1.5513 + }, + { + "x": 2.9304, + "y": 1.5665 + }, + { + "x": 2.9304, + "y": 1.7795 + }, + { + "x": 2.3119, + "y": 1.7744 + } + ], + "span": { + "offset": 1635, + "length": 6 + }, + "confidence": 0.994 + } + ], + "selection_marks": [], + "spans": [ + { + "offset": 1596, + "length": 45 + } + ], + "kind": "document", + "annotations": [], + "barcodes": [], + "formulas": [], + "images": [] + } + ], + "paragraphs": [ + { + "role": "title", + "content": "A sample PDF file", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7573, + "y": 0.8365 + }, + { + "x": 3.5914, + "y": 0.8112 + }, + { + "x": 3.5945, + "y": 1.166 + }, + { + "x": 0.7605, + "y": 1.1914 + } + ] + } + ], + "spans": [ + { + "offset": 0, + "length": 17 + } + ] + }, + { + "role": "sectionHeading", + "content": "History and standardization", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7706, + "y": 1.7136 + }, + { + "x": 3.1433, + "y": 1.7136 + }, + { + "x": 3.1433, + "y": 1.9316 + }, + { + "x": 0.7706, + "y": 1.9316 + } + ] + } + ], + "spans": [ + { + "offset": 18, + "length": 27 + } + ] + }, + { + "role": null, + "content": "Format (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.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7605, + "y": 2.18 + }, + { + "x": 7.4781, + "y": 2.18 + }, + { + "x": 7.4781, + "y": 6.6514 + }, + { + "x": 0.7605, + "y": 6.6514 + } + ] + } + ], + "spans": [ + { + "offset": 46, + "length": 1361 + } + ] + }, + { + "role": null, + "content": "Column 1", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 7.0624 + }, + { + "x": 4.1287, + "y": 7.0624 + }, + { + "x": 4.1287, + "y": 7.3715 + }, + { + "x": 2.4575, + "y": 7.3715 + } + ] + } + ], + "spans": [ + { + "offset": 1408, + "length": 8 + } + ] + }, + { + "role": null, + "content": "Column 2", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 7.0624 + }, + { + "x": 5.7998, + "y": 7.0555 + }, + { + "x": 5.7998, + "y": 7.3715 + }, + { + "x": 4.1287, + "y": 7.3715 + } + ] + } + ], + "spans": [ + { + "offset": 1417, + "length": 8 + } + ] + }, + { + "role": null, + "content": "Column 3", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 7.0555 + }, + { + "x": 7.4709, + "y": 7.0555 + }, + { + "x": 7.4709, + "y": 7.3715 + }, + { + "x": 5.7998, + "y": 7.3715 + } + ] + } + ], + "spans": [ + { + "offset": 1426, + "length": 8 + } + ] + }, + { + "role": null, + "content": "A", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 7.3715 + }, + { + "x": 2.4575, + "y": 7.3715 + }, + { + "x": 2.4575, + "y": 7.6875 + }, + { + "x": 0.7864, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1435, + "length": 1 + } + ] + }, + { + "role": null, + "content": "324", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 7.3715 + }, + { + "x": 4.1287, + "y": 7.3715 + }, + { + "x": 4.1287, + "y": 7.6875 + }, + { + "x": 2.4575, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1437, + "length": 3 + } + ] + }, + { + "role": null, + "content": "55 million units", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 7.3715 + }, + { + "x": 5.7998, + "y": 7.3715 + }, + { + "x": 5.7998, + "y": 7.6875 + }, + { + "x": 4.1287, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1441, + "length": 16 + } + ] + }, + { + "role": null, + "content": "2022", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 7.3715 + }, + { + "x": 7.4709, + "y": 7.3715 + }, + { + "x": 7.4709, + "y": 7.6875 + }, + { + "x": 5.7998, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1458, + "length": 4 + } + ] + }, + { + "role": null, + "content": "B", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 7.6875 + }, + { + "x": 2.4575, + "y": 7.6875 + }, + { + "x": 2.4575, + "y": 8.292 + }, + { + "x": 0.7864, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1463, + "length": 1 + } + ] + }, + { + "role": null, + "content": "234,523.00", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 7.6875 + }, + { + "x": 4.1287, + "y": 7.6875 + }, + { + "x": 4.1287, + "y": 8.292 + }, + { + "x": 2.4575, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1465, + "length": 10 + } + ] + }, + { + "role": null, + "content": "The quick brown fox jumped over the lazy dog.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 7.6875 + }, + { + "x": 5.7998, + "y": 7.6875 + }, + { + "x": 5.7998, + "y": 8.292 + }, + { + "x": 4.1287, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1476, + "length": 45 + } + ] + }, + { + "role": null, + "content": "54x growth", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 7.6875 + }, + { + "x": 7.4709, + "y": 7.6875 + }, + { + "x": 7.4709, + "y": 8.2989 + }, + { + "x": 5.7998, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1522, + "length": 10 + } + ] + }, + { + "role": null, + "content": "C", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 8.292 + }, + { + "x": 2.4575, + "y": 8.292 + }, + { + "x": 2.4575, + "y": 8.6148 + }, + { + "x": 0.7864, + "y": 8.6148 + } + ] + } + ], + "spans": [ + { + "offset": 1533, + "length": 1 + } + ] + }, + { + "role": null, + "content": "23.53%", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 8.292 + }, + { + "x": 4.1287, + "y": 8.292 + }, + { + "x": 4.1287, + "y": 8.6148 + }, + { + "x": 2.4575, + "y": 8.6148 + } + ] + } + ], + "spans": [ + { + "offset": 1535, + "length": 6 + } + ] + }, + { + "role": null, + "content": "A short string.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 8.292 + }, + { + "x": 5.7998, + "y": 8.292 + }, + { + "x": 5.7998, + "y": 8.6217 + }, + { + "x": 4.1287, + "y": 8.6148 + } + ] + } + ], + "spans": [ + { + "offset": 1542, + "length": 15 + } + ] + }, + { + "role": null, + "content": "D", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 8.6148 + }, + { + "x": 2.4575, + "y": 8.6148 + }, + { + "x": 2.4575, + "y": 8.9308 + }, + { + "x": 0.7864, + "y": 8.9308 + } + ] + } + ], + "spans": [ + { + "offset": 1558, + "length": 1 + } + ] + }, + { + "role": null, + "content": "$54.35", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 8.6148 + }, + { + "x": 4.1287, + "y": 8.6148 + }, + { + "x": 4.1287, + "y": 8.9377 + }, + { + "x": 2.4575, + "y": 8.9308 + } + ] + } + ], + "spans": [ + { + "offset": 1560, + "length": 6 + } + ] + }, + { + "role": null, + "content": "$6345.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 8.6148 + }, + { + "x": 5.7998, + "y": 8.6217 + }, + { + "x": 5.7998, + "y": 8.9377 + }, + { + "x": 4.1287, + "y": 8.9377 + } + ] + } + ], + "spans": [ + { + "offset": 1567, + "length": 6 + } + ] + }, + { + "role": "title", + "content": "Page 2 of Sample PDF", + "bounding_regions": [ + { + "page_number": 2, + "polygon": [ + { + "x": 0.7798, + "y": 0.8365 + }, + { + "x": 4.0397, + "y": 0.8263 + }, + { + "x": 4.0407, + "y": 1.1508 + }, + { + "x": 0.7808, + "y": 1.161 + } + ] + } + ], + "spans": [ + { + "offset": 1574, + "length": 20 + } + ] + }, + { + "role": "title", + "content": "Page 4 of Sample PDF", + "bounding_regions": [ + { + "page_number": 4, + "polygon": [ + { + "x": 0.7797, + "y": 0.8365 + }, + { + "x": 4.0356, + "y": 0.8264 + }, + { + "x": 4.0366, + "y": 1.1508 + }, + { + "x": 0.7808, + "y": 1.161 + } + ] + } + ], + "spans": [ + { + "offset": 1596, + "length": 20 + } + ] + }, + { + "role": null, + "content": "... the page 3 is empty.", + "bounding_regions": [ + { + "page_number": 4, + "polygon": [ + { + "x": 0.7853, + "y": 1.5513 + }, + { + "x": 2.9304, + "y": 1.5463 + }, + { + "x": 2.9309, + "y": 1.7744 + }, + { + "x": 0.7858, + "y": 1.7795 + } + ] + } + ], + "spans": [ + { + "offset": 1617, + "length": 24 + } + ] + } + ], + "tables": [ + { + "row_count": 5, + "column_count": 4, + "cells": [ + { + "kind": "columnHeader", + "row_index": 0, + "column_index": 0, + "row_span": 1, + "column_span": 1, + "content": "", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 7.0624 + }, + { + "x": 2.4575, + "y": 7.0624 + }, + { + "x": 2.4575, + "y": 7.3715 + }, + { + "x": 0.7864, + "y": 7.3715 + } + ] + } + ], + "spans": [] + }, + { + "kind": "columnHeader", + "row_index": 0, + "column_index": 1, + "row_span": 1, + "column_span": 1, + "content": "Column 1", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 7.0624 + }, + { + "x": 4.1287, + "y": 7.0624 + }, + { + "x": 4.1287, + "y": 7.3715 + }, + { + "x": 2.4575, + "y": 7.3715 + } + ] + } + ], + "spans": [ + { + "offset": 1408, + "length": 8 + } + ] + }, + { + "kind": "columnHeader", + "row_index": 0, + "column_index": 2, + "row_span": 1, + "column_span": 1, + "content": "Column 2", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 7.0624 + }, + { + "x": 5.7998, + "y": 7.0555 + }, + { + "x": 5.7998, + "y": 7.3715 + }, + { + "x": 4.1287, + "y": 7.3715 + } + ] + } + ], + "spans": [ + { + "offset": 1417, + "length": 8 + } + ] + }, + { + "kind": "columnHeader", + "row_index": 0, + "column_index": 3, + "row_span": 1, + "column_span": 1, + "content": "Column 3", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 7.0555 + }, + { + "x": 7.4709, + "y": 7.0555 + }, + { + "x": 7.4709, + "y": 7.3715 + }, + { + "x": 5.7998, + "y": 7.3715 + } + ] + } + ], + "spans": [ + { + "offset": 1426, + "length": 8 + } + ] + }, + { + "kind": "content", + "row_index": 1, + "column_index": 0, + "row_span": 1, + "column_span": 1, + "content": "A", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 7.3715 + }, + { + "x": 2.4575, + "y": 7.3715 + }, + { + "x": 2.4575, + "y": 7.6875 + }, + { + "x": 0.7864, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1435, + "length": 1 + } + ] + }, + { + "kind": "content", + "row_index": 1, + "column_index": 1, + "row_span": 1, + "column_span": 1, + "content": "324", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 7.3715 + }, + { + "x": 4.1287, + "y": 7.3715 + }, + { + "x": 4.1287, + "y": 7.6875 + }, + { + "x": 2.4575, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1437, + "length": 3 + } + ] + }, + { + "kind": "content", + "row_index": 1, + "column_index": 2, + "row_span": 1, + "column_span": 1, + "content": "55 million units", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 7.3715 + }, + { + "x": 5.7998, + "y": 7.3715 + }, + { + "x": 5.7998, + "y": 7.6875 + }, + { + "x": 4.1287, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1441, + "length": 16 + } + ] + }, + { + "kind": "content", + "row_index": 1, + "column_index": 3, + "row_span": 1, + "column_span": 1, + "content": "2022", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 7.3715 + }, + { + "x": 7.4709, + "y": 7.3715 + }, + { + "x": 7.4709, + "y": 7.6875 + }, + { + "x": 5.7998, + "y": 7.6875 + } + ] + } + ], + "spans": [ + { + "offset": 1458, + "length": 4 + } + ] + }, + { + "kind": "content", + "row_index": 2, + "column_index": 0, + "row_span": 1, + "column_span": 1, + "content": "B", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 7.6875 + }, + { + "x": 2.4575, + "y": 7.6875 + }, + { + "x": 2.4575, + "y": 8.292 + }, + { + "x": 0.7864, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1463, + "length": 1 + } + ] + }, + { + "kind": "content", + "row_index": 2, + "column_index": 1, + "row_span": 1, + "column_span": 1, + "content": "234,523.00", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 7.6875 + }, + { + "x": 4.1287, + "y": 7.6875 + }, + { + "x": 4.1287, + "y": 8.292 + }, + { + "x": 2.4575, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1465, + "length": 10 + } + ] + }, + { + "kind": "content", + "row_index": 2, + "column_index": 2, + "row_span": 1, + "column_span": 1, + "content": "The quick brown fox jumped over the lazy dog.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 7.6875 + }, + { + "x": 5.7998, + "y": 7.6875 + }, + { + "x": 5.7998, + "y": 8.292 + }, + { + "x": 4.1287, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1476, + "length": 45 + } + ] + }, + { + "kind": "content", + "row_index": 2, + "column_index": 3, + "row_span": 1, + "column_span": 1, + "content": "54x growth", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 7.6875 + }, + { + "x": 7.4709, + "y": 7.6875 + }, + { + "x": 7.4709, + "y": 8.2989 + }, + { + "x": 5.7998, + "y": 8.292 + } + ] + } + ], + "spans": [ + { + "offset": 1522, + "length": 10 + } + ] + }, + { + "kind": "content", + "row_index": 3, + "column_index": 0, + "row_span": 1, + "column_span": 1, + "content": "C", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 8.292 + }, + { + "x": 2.4575, + "y": 8.292 + }, + { + "x": 2.4575, + "y": 8.6148 + }, + { + "x": 0.7864, + "y": 8.6148 + } + ] + } + ], + "spans": [ + { + "offset": 1533, + "length": 1 + } + ] + }, + { + "kind": "content", + "row_index": 3, + "column_index": 1, + "row_span": 1, + "column_span": 1, + "content": "23.53%", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 8.292 + }, + { + "x": 4.1287, + "y": 8.292 + }, + { + "x": 4.1287, + "y": 8.6148 + }, + { + "x": 2.4575, + "y": 8.6148 + } + ] + } + ], + "spans": [ + { + "offset": 1535, + "length": 6 + } + ] + }, + { + "kind": "content", + "row_index": 3, + "column_index": 2, + "row_span": 1, + "column_span": 1, + "content": "A short string.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 8.292 + }, + { + "x": 5.7998, + "y": 8.292 + }, + { + "x": 5.7998, + "y": 8.6217 + }, + { + "x": 4.1287, + "y": 8.6148 + } + ] + } + ], + "spans": [ + { + "offset": 1542, + "length": 15 + } + ] + }, + { + "kind": "content", + "row_index": 3, + "column_index": 3, + "row_span": 1, + "column_span": 1, + "content": "", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 8.292 + }, + { + "x": 7.4709, + "y": 8.2989 + }, + { + "x": 7.4709, + "y": 8.6217 + }, + { + "x": 5.7998, + "y": 8.6217 + } + ] + } + ], + "spans": [] + }, + { + "kind": "content", + "row_index": 4, + "column_index": 0, + "row_span": 1, + "column_span": 1, + "content": "D", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.7864, + "y": 8.6148 + }, + { + "x": 2.4575, + "y": 8.6148 + }, + { + "x": 2.4575, + "y": 8.9308 + }, + { + "x": 0.7864, + "y": 8.9308 + } + ] + } + ], + "spans": [ + { + "offset": 1558, + "length": 1 + } + ] + }, + { + "kind": "content", + "row_index": 4, + "column_index": 1, + "row_span": 1, + "column_span": 1, + "content": "$54.35", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.4575, + "y": 8.6148 + }, + { + "x": 4.1287, + "y": 8.6148 + }, + { + "x": 4.1287, + "y": 8.9377 + }, + { + "x": 2.4575, + "y": 8.9308 + } + ] + } + ], + "spans": [ + { + "offset": 1560, + "length": 6 + } + ] + }, + { + "kind": "content", + "row_index": 4, + "column_index": 2, + "row_span": 1, + "column_span": 1, + "content": "$6345.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.1287, + "y": 8.6148 + }, + { + "x": 5.7998, + "y": 8.6217 + }, + { + "x": 5.7998, + "y": 8.9377 + }, + { + "x": 4.1287, + "y": 8.9377 + } + ] + } + ], + "spans": [ + { + "offset": 1567, + "length": 6 + } + ] + }, + { + "kind": "content", + "row_index": 4, + "column_index": 3, + "row_span": 1, + "column_span": 1, + "content": "", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 5.7998, + "y": 8.6217 + }, + { + "x": 7.4709, + "y": 8.6217 + }, + { + "x": 7.4709, + "y": 8.9239 + }, + { + "x": 5.7998, + "y": 8.9377 + } + ] + } + ], + "spans": [] + } + ], + "spans": [ + { + "offset": 1408, + "length": 165 + } + ] + } + ], + "key_value_pairs": [], + "styles": [], + "documents": [] +} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/azure_sample_pdf_2.json b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/azure_sample_pdf_2.json new file mode 100644 index 0000000000000000000000000000000000000000..128b3fddcb6fb00cef1bda7522ab8ea263de30fa --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/azure_sample_pdf_2.json @@ -0,0 +1,5480 @@ +{ + "api_version": "2023-02-28-preview", + "model_id": "prebuilt-read", + "content": "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 ...\nSimple 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.", + "languages": [ + { + "locale": "en", + "spans": [ + { + "offset": 0, + "length": 17 + }, + { + "offset": 560, + "length": 17 + } + ], + "confidence": 0.95 + }, + { + "locale": "en", + "spans": [ + { + "offset": 18, + "length": 41 + }, + { + "offset": 129, + "length": 50 + }, + { + "offset": 319, + "length": 100 + }, + { + "offset": 578, + "length": 71 + }, + { + "offset": 789, + "length": 70 + } + ], + "confidence": 1.0 + }, + { + "locale": "en", + "spans": [ + { + "offset": 60, + "length": 68 + }, + { + "offset": 180, + "length": 138 + }, + { + "offset": 420, + "length": 139 + }, + { + "offset": 650, + "length": 68 + }, + { + "offset": 860, + "length": 60 + } + ], + "confidence": 0.99 + }, + { + "locale": "en", + "spans": [ + { + "offset": 719, + "length": 69 + } + ], + "confidence": 0.9 + } + ], + "pages": [ + { + "page_number": 1, + "angle": null, + "width": 8.5, + "height": 11.0, + "unit": "inch", + "lines": [ + { + "content": "A Simple PDF File", + "polygon": [ + { + "x": 0.8787, + "y": 0.6684 + }, + { + "x": 3.9587, + "y": 0.6684 + }, + { + "x": 3.9635, + "y": 1.0217 + }, + { + "x": 0.8787, + "y": 1.0408 + } + ], + "spans": [ + { + "offset": 0, + "length": 17 + } + ] + }, + { + "content": "This is a small demonstration .pdf file -", + "polygon": [ + { + "x": 0.9837, + "y": 1.3129 + }, + { + "x": 3.3666, + "y": 1.3177 + }, + { + "x": 3.3666, + "y": 1.4657 + }, + { + "x": 0.9837, + "y": 1.4562 + } + ], + "spans": [ + { + "offset": 18, + "length": 41 + } + ] + }, + { + "content": "just for use in the Virtual Mechanics tutorials. More text. And more", + "polygon": [ + { + "x": 0.9837, + "y": 1.6424 + }, + { + "x": 5.0522, + "y": 1.6424 + }, + { + "x": 5.0522, + "y": 1.7904 + }, + { + "x": 0.9837, + "y": 1.7951 + } + ], + "spans": [ + { + "offset": 60, + "length": 68 + } + ] + }, + { + "content": "text. And more text. And more text. And more text.", + "polygon": [ + { + "x": 0.9885, + "y": 1.8142 + }, + { + "x": 4.0876, + "y": 1.8142 + }, + { + "x": 4.0876, + "y": 1.9527 + }, + { + "x": 0.9885, + "y": 1.9527 + } + ], + "spans": [ + { + "offset": 129, + "length": 50 + } + ] + }, + { + "content": "And more text. And more text. And more text. And more text. And more", + "polygon": [ + { + "x": 0.9837, + "y": 2.1437 + }, + { + "x": 5.3722, + "y": 2.1437 + }, + { + "x": 5.3722, + "y": 2.2869 + }, + { + "x": 0.9837, + "y": 2.2869 + } + ], + "spans": [ + { + "offset": 180, + "length": 68 + } + ] + }, + { + "content": "text. And more text. Boring, zzzzz. And more text. And more text. And", + "polygon": [ + { + "x": 0.9837, + "y": 2.3108 + }, + { + "x": 5.2862, + "y": 2.306 + }, + { + "x": 5.2862, + "y": 2.454 + }, + { + "x": 0.9837, + "y": 2.454 + } + ], + "spans": [ + { + "offset": 249, + "length": 69 + } + ] + }, + { + "content": "more text. And more text. And more text. And more text. And more text.", + "polygon": [ + { + "x": 0.9885, + "y": 2.4779 + }, + { + "x": 5.377, + "y": 2.4731 + }, + { + "x": 5.377, + "y": 2.6163 + }, + { + "x": 0.9885, + "y": 2.6163 + } + ], + "spans": [ + { + "offset": 319, + "length": 70 + } + ] + }, + { + "content": "And more text. And more text.", + "polygon": [ + { + "x": 0.9885, + "y": 2.6497 + }, + { + "x": 2.8413, + "y": 2.6497 + }, + { + "x": 2.8413, + "y": 2.7786 + }, + { + "x": 0.9885, + "y": 2.7786 + } + ], + "spans": [ + { + "offset": 390, + "length": 29 + } + ] + }, + { + "content": "And more text. And more text. And more text. And more text. And more", + "polygon": [ + { + "x": 0.9789, + "y": 2.9696 + }, + { + "x": 5.3674, + "y": 2.9696 + }, + { + "x": 5.3674, + "y": 3.1176 + }, + { + "x": 0.9789, + "y": 3.1128 + } + ], + "spans": [ + { + "offset": 420, + "length": 68 + } + ] + }, + { + "content": "text. And more text. And more text. Even more. Continued on page 2 ...", + "polygon": [ + { + "x": 0.9789, + "y": 3.1367 + }, + { + "x": 5.3865, + "y": 3.1367 + }, + { + "x": 5.3865, + "y": 3.299 + }, + { + "x": 0.9789, + "y": 3.2895 + } + ], + "spans": [ + { + "offset": 489, + "length": 70 + } + ] + } + ], + "words": [ + { + "content": "A", + "polygon": [ + { + "x": 0.9025, + "y": 0.6732 + }, + { + "x": 1.0888, + "y": 0.6732 + }, + { + "x": 1.084, + "y": 1.036 + }, + { + "x": 0.8978, + "y": 1.0313 + } + ], + "span": { + "offset": 0, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "Simple", + "polygon": [ + { + "x": 1.275, + "y": 0.6732 + }, + { + "x": 2.3638, + "y": 0.6732 + }, + { + "x": 2.3638, + "y": 1.0408 + }, + { + "x": 1.2702, + "y": 1.0408 + } + ], + "span": { + "offset": 2, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 2.4831, + "y": 0.6732 + }, + { + "x": 3.1994, + "y": 0.6732 + }, + { + "x": 3.2042, + "y": 1.0169 + }, + { + "x": 2.4831, + "y": 1.0408 + } + ], + "span": { + "offset": 9, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "File", + "polygon": [ + { + "x": 3.3427, + "y": 0.6732 + }, + { + "x": 3.9444, + "y": 0.6684 + }, + { + "x": 3.9492, + "y": 0.9787 + }, + { + "x": 3.3427, + "y": 1.0122 + } + ], + "span": { + "offset": 13, + "length": 4 + }, + "confidence": 0.968 + }, + { + "content": "This", + "polygon": [ + { + "x": 1.0028, + "y": 1.3177 + }, + { + "x": 1.2511, + "y": 1.3177 + }, + { + "x": 1.2511, + "y": 1.4609 + }, + { + "x": 1.0028, + "y": 1.4562 + } + ], + "span": { + "offset": 18, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "is", + "polygon": [ + { + "x": 1.2798, + "y": 1.3177 + }, + { + "x": 1.4039, + "y": 1.3177 + }, + { + "x": 1.4039, + "y": 1.4609 + }, + { + "x": 1.2798, + "y": 1.4609 + } + ], + "span": { + "offset": 23, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "a", + "polygon": [ + { + "x": 1.4326, + "y": 1.3177 + }, + { + "x": 1.509, + "y": 1.3177 + }, + { + "x": 1.509, + "y": 1.4609 + }, + { + "x": 1.4326, + "y": 1.4609 + } + ], + "span": { + "offset": 26, + "length": 1 + }, + "confidence": 0.996 + }, + { + "content": "small", + "polygon": [ + { + "x": 1.5472, + "y": 1.3177 + }, + { + "x": 1.8815, + "y": 1.3177 + }, + { + "x": 1.8815, + "y": 1.4657 + }, + { + "x": 1.5472, + "y": 1.4609 + } + ], + "span": { + "offset": 28, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "demonstration", + "polygon": [ + { + "x": 1.9101, + "y": 1.3177 + }, + { + "x": 2.784, + "y": 1.3177 + }, + { + "x": 2.784, + "y": 1.4657 + }, + { + "x": 1.9101, + "y": 1.4657 + } + ], + "span": { + "offset": 34, + "length": 13 + }, + "confidence": 0.991 + }, + { + "content": ".pdf", + "polygon": [ + { + "x": 2.8222, + "y": 1.3177 + }, + { + "x": 3.0705, + "y": 1.3225 + }, + { + "x": 3.0705, + "y": 1.4657 + }, + { + "x": 2.8222, + "y": 1.4657 + } + ], + "span": { + "offset": 48, + "length": 4 + }, + "confidence": 0.881 + }, + { + "content": "file", + "polygon": [ + { + "x": 3.0992, + "y": 1.3225 + }, + { + "x": 3.2806, + "y": 1.3225 + }, + { + "x": 3.2806, + "y": 1.4657 + }, + { + "x": 3.0992, + "y": 1.4657 + } + ], + "span": { + "offset": 53, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "-", + "polygon": [ + { + "x": 3.3093, + "y": 1.3225 + }, + { + "x": 3.3713, + "y": 1.3225 + }, + { + "x": 3.3666, + "y": 1.4657 + }, + { + "x": 3.3093, + "y": 1.4657 + } + ], + "span": { + "offset": 58, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "just", + "polygon": [ + { + "x": 0.9837, + "y": 1.6519 + }, + { + "x": 1.2081, + "y": 1.6519 + }, + { + "x": 1.2129, + "y": 1.7999 + }, + { + "x": 0.9885, + "y": 1.7999 + } + ], + "span": { + "offset": 60, + "length": 4 + }, + "confidence": 0.982 + }, + { + "content": "for", + "polygon": [ + { + "x": 1.2368, + "y": 1.6519 + }, + { + "x": 1.4183, + "y": 1.6519 + }, + { + "x": 1.423, + "y": 1.7999 + }, + { + "x": 1.2416, + "y": 1.7999 + } + ], + "span": { + "offset": 65, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "use", + "polygon": [ + { + "x": 1.4469, + "y": 1.6519 + }, + { + "x": 1.6666, + "y": 1.6471 + }, + { + "x": 1.6666, + "y": 1.7951 + }, + { + "x": 1.4517, + "y": 1.7999 + } + ], + "span": { + "offset": 69, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "in", + "polygon": [ + { + "x": 1.6952, + "y": 1.6471 + }, + { + "x": 1.8098, + "y": 1.6471 + }, + { + "x": 1.8098, + "y": 1.7951 + }, + { + "x": 1.6952, + "y": 1.7951 + } + ], + "span": { + "offset": 73, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "the", + "polygon": [ + { + "x": 1.848, + "y": 1.6471 + }, + { + "x": 2.0438, + "y": 1.6471 + }, + { + "x": 2.0486, + "y": 1.7951 + }, + { + "x": 1.848, + "y": 1.7951 + } + ], + "span": { + "offset": 76, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "Virtual", + "polygon": [ + { + "x": 2.0916, + "y": 1.6471 + }, + { + "x": 2.4831, + "y": 1.6471 + }, + { + "x": 2.4831, + "y": 1.7951 + }, + { + "x": 2.0963, + "y": 1.7951 + } + ], + "span": { + "offset": 80, + "length": 7 + }, + "confidence": 0.991 + }, + { + "content": "Mechanics", + "polygon": [ + { + "x": 2.5118, + "y": 1.6471 + }, + { + "x": 3.1851, + "y": 1.6471 + }, + { + "x": 3.1899, + "y": 1.7904 + }, + { + "x": 2.5118, + "y": 1.7951 + } + ], + "span": { + "offset": 88, + "length": 9 + }, + "confidence": 0.993 + }, + { + "content": "tutorials.", + "polygon": [ + { + "x": 3.2138, + "y": 1.6471 + }, + { + "x": 3.7534, + "y": 1.6471 + }, + { + "x": 3.7581, + "y": 1.7904 + }, + { + "x": 3.2185, + "y": 1.7904 + } + ], + "span": { + "offset": 98, + "length": 10 + }, + "confidence": 0.991 + }, + { + "content": "More", + "polygon": [ + { + "x": 3.782, + "y": 1.6471 + }, + { + "x": 4.1067, + "y": 1.6471 + }, + { + "x": 4.1067, + "y": 1.7904 + }, + { + "x": 3.7868, + "y": 1.7904 + } + ], + "span": { + "offset": 109, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 4.1354, + "y": 1.6471 + }, + { + "x": 4.4171, + "y": 1.6471 + }, + { + "x": 4.4219, + "y": 1.7904 + }, + { + "x": 4.1354, + "y": 1.7904 + } + ], + "span": { + "offset": 114, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "And", + "polygon": [ + { + "x": 4.4458, + "y": 1.6519 + }, + { + "x": 4.6846, + "y": 1.6519 + }, + { + "x": 4.6893, + "y": 1.7904 + }, + { + "x": 4.4506, + "y": 1.7904 + } + ], + "span": { + "offset": 120, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 4.7228, + "y": 1.6519 + }, + { + "x": 5.0475, + "y": 1.6519 + }, + { + "x": 5.0475, + "y": 1.7904 + }, + { + "x": 4.7275, + "y": 1.7904 + } + ], + "span": { + "offset": 124, + "length": 4 + }, + "confidence": 0.992 + }, + { + "content": "text.", + "polygon": [ + { + "x": 0.9885, + "y": 1.819 + }, + { + "x": 1.2702, + "y": 1.819 + }, + { + "x": 1.275, + "y": 1.9575 + }, + { + "x": 0.9933, + "y": 1.9575 + } + ], + "span": { + "offset": 129, + "length": 5 + }, + "confidence": 0.991 + }, + { + "content": "And", + "polygon": [ + { + "x": 1.2989, + "y": 1.819 + }, + { + "x": 1.5376, + "y": 1.819 + }, + { + "x": 1.5376, + "y": 1.9575 + }, + { + "x": 1.2989, + "y": 1.9575 + } + ], + "span": { + "offset": 135, + "length": 3 + }, + "confidence": 0.994 + }, + { + "content": "more", + "polygon": [ + { + "x": 1.5711, + "y": 1.819 + }, + { + "x": 1.891, + "y": 1.8142 + }, + { + "x": 1.8958, + "y": 1.9575 + }, + { + "x": 1.5758, + "y": 1.9575 + } + ], + "span": { + "offset": 139, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 1.9292, + "y": 1.8142 + }, + { + "x": 2.211, + "y": 1.8142 + }, + { + "x": 2.211, + "y": 1.9575 + }, + { + "x": 1.9292, + "y": 1.9575 + } + ], + "span": { + "offset": 144, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "And", + "polygon": [ + { + "x": 2.2396, + "y": 1.8142 + }, + { + "x": 2.4784, + "y": 1.8142 + }, + { + "x": 2.4784, + "y": 1.9575 + }, + { + "x": 2.2396, + "y": 1.9575 + } + ], + "span": { + "offset": 150, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 2.5118, + "y": 1.8142 + }, + { + "x": 2.8317, + "y": 1.8142 + }, + { + "x": 2.8317, + "y": 1.9575 + }, + { + "x": 2.5118, + "y": 1.9575 + } + ], + "span": { + "offset": 154, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 2.8699, + "y": 1.8142 + }, + { + "x": 3.1612, + "y": 1.8142 + }, + { + "x": 3.1612, + "y": 1.9575 + }, + { + "x": 2.8699, + "y": 1.9575 + } + ], + "span": { + "offset": 159, + "length": 5 + }, + "confidence": 0.992 + }, + { + "content": "And", + "polygon": [ + { + "x": 3.1899, + "y": 1.8142 + }, + { + "x": 3.4239, + "y": 1.819 + }, + { + "x": 3.4239, + "y": 1.9575 + }, + { + "x": 3.1899, + "y": 1.9575 + } + ], + "span": { + "offset": 165, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 3.4621, + "y": 1.819 + }, + { + "x": 3.782, + "y": 1.819 + }, + { + "x": 3.782, + "y": 1.9575 + }, + { + "x": 3.4621, + "y": 1.9575 + } + ], + "span": { + "offset": 169, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 3.8202, + "y": 1.819 + }, + { + "x": 4.0924, + "y": 1.819 + }, + { + "x": 4.0924, + "y": 1.9527 + }, + { + "x": 3.8202, + "y": 1.9575 + } + ], + "span": { + "offset": 174, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 0.9933, + "y": 2.1532 + }, + { + "x": 1.232, + "y": 2.1484 + }, + { + "x": 1.2368, + "y": 2.2869 + }, + { + "x": 0.998, + "y": 2.2869 + } + ], + "span": { + "offset": 180, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 1.2702, + "y": 2.1484 + }, + { + "x": 1.5902, + "y": 2.1484 + }, + { + "x": 1.5949, + "y": 2.2869 + }, + { + "x": 1.275, + "y": 2.2869 + } + ], + "span": { + "offset": 184, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 1.6284, + "y": 2.1484 + }, + { + "x": 1.9149, + "y": 2.1484 + }, + { + "x": 1.9149, + "y": 2.2869 + }, + { + "x": 1.6331, + "y": 2.2869 + } + ], + "span": { + "offset": 189, + "length": 5 + }, + "confidence": 0.918 + }, + { + "content": "And", + "polygon": [ + { + "x": 1.9435, + "y": 2.1484 + }, + { + "x": 2.1728, + "y": 2.1484 + }, + { + "x": 2.1728, + "y": 2.2869 + }, + { + "x": 1.9435, + "y": 2.2869 + } + ], + "span": { + "offset": 195, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 2.211, + "y": 2.1484 + }, + { + "x": 2.5309, + "y": 2.1484 + }, + { + "x": 2.5309, + "y": 2.2869 + }, + { + "x": 2.211, + "y": 2.2869 + } + ], + "span": { + "offset": 199, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 2.5691, + "y": 2.1484 + }, + { + "x": 2.8556, + "y": 2.1484 + }, + { + "x": 2.8556, + "y": 2.2869 + }, + { + "x": 2.5691, + "y": 2.2869 + } + ], + "span": { + "offset": 204, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 2.8795, + "y": 2.1484 + }, + { + "x": 3.1183, + "y": 2.1484 + }, + { + "x": 3.123, + "y": 2.2869 + }, + { + "x": 2.8843, + "y": 2.2869 + } + ], + "span": { + "offset": 210, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 3.1565, + "y": 2.1484 + }, + { + "x": 3.4812, + "y": 2.1484 + }, + { + "x": 3.4812, + "y": 2.2917 + }, + { + "x": 3.1565, + "y": 2.2869 + } + ], + "span": { + "offset": 214, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 3.5146, + "y": 2.1484 + }, + { + "x": 3.8011, + "y": 2.1484 + }, + { + "x": 3.8011, + "y": 2.2917 + }, + { + "x": 3.5194, + "y": 2.2917 + } + ], + "span": { + "offset": 219, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 3.8298, + "y": 2.1484 + }, + { + "x": 4.059, + "y": 2.1484 + }, + { + "x": 4.059, + "y": 2.2917 + }, + { + "x": 3.8298, + "y": 2.2917 + } + ], + "span": { + "offset": 225, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "more", + "polygon": [ + { + "x": 4.1067, + "y": 2.1484 + }, + { + "x": 4.4171, + "y": 2.1484 + }, + { + "x": 4.4171, + "y": 2.2917 + }, + { + "x": 4.1067, + "y": 2.2917 + } + ], + "span": { + "offset": 229, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 4.4553, + "y": 2.1484 + }, + { + "x": 4.7419, + "y": 2.1484 + }, + { + "x": 4.7419, + "y": 2.2917 + }, + { + "x": 4.4553, + "y": 2.2917 + } + ], + "span": { + "offset": 234, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "And", + "polygon": [ + { + "x": 4.7657, + "y": 2.1484 + }, + { + "x": 5.0093, + "y": 2.1484 + }, + { + "x": 5.0093, + "y": 2.2917 + }, + { + "x": 4.7705, + "y": 2.2917 + } + ], + "span": { + "offset": 240, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 5.0427, + "y": 2.1484 + }, + { + "x": 5.3674, + "y": 2.1484 + }, + { + "x": 5.3674, + "y": 2.2917 + }, + { + "x": 5.0427, + "y": 2.2917 + } + ], + "span": { + "offset": 244, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 0.9885, + "y": 2.3155 + }, + { + "x": 1.2702, + "y": 2.3155 + }, + { + "x": 1.2702, + "y": 2.454 + }, + { + "x": 0.9885, + "y": 2.454 + } + ], + "span": { + "offset": 249, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 1.2989, + "y": 2.3155 + }, + { + "x": 1.5329, + "y": 2.3155 + }, + { + "x": 1.5329, + "y": 2.454 + }, + { + "x": 1.2989, + "y": 2.454 + } + ], + "span": { + "offset": 255, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 1.5711, + "y": 2.3155 + }, + { + "x": 1.891, + "y": 2.3155 + }, + { + "x": 1.891, + "y": 2.4588 + }, + { + "x": 1.5711, + "y": 2.454 + } + ], + "span": { + "offset": 259, + "length": 4 + }, + "confidence": 0.991 + }, + { + "content": "text.", + "polygon": [ + { + "x": 1.9292, + "y": 2.3155 + }, + { + "x": 2.2014, + "y": 2.3155 + }, + { + "x": 2.2014, + "y": 2.4588 + }, + { + "x": 1.9292, + "y": 2.4588 + } + ], + "span": { + "offset": 264, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "Boring,", + "polygon": [ + { + "x": 2.2301, + "y": 2.3155 + }, + { + "x": 2.6933, + "y": 2.3155 + }, + { + "x": 2.6933, + "y": 2.4588 + }, + { + "x": 2.2301, + "y": 2.4588 + } + ], + "span": { + "offset": 270, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "zzzzz.", + "polygon": [ + { + "x": 2.7219, + "y": 2.3155 + }, + { + "x": 3.1183, + "y": 2.3155 + }, + { + "x": 3.1183, + "y": 2.4588 + }, + { + "x": 2.7219, + "y": 2.4588 + } + ], + "span": { + "offset": 278, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 3.1421, + "y": 2.3155 + }, + { + "x": 3.3809, + "y": 2.3155 + }, + { + "x": 3.3809, + "y": 2.4588 + }, + { + "x": 3.1469, + "y": 2.4588 + } + ], + "span": { + "offset": 285, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 3.4191, + "y": 2.3155 + }, + { + "x": 3.739, + "y": 2.3108 + }, + { + "x": 3.739, + "y": 2.4588 + }, + { + "x": 3.4191, + "y": 2.4588 + } + ], + "span": { + "offset": 289, + "length": 4 + }, + "confidence": 0.99 + }, + { + "content": "text.", + "polygon": [ + { + "x": 3.7772, + "y": 2.3108 + }, + { + "x": 4.059, + "y": 2.3108 + }, + { + "x": 4.059, + "y": 2.4588 + }, + { + "x": 3.7772, + "y": 2.4588 + } + ], + "span": { + "offset": 294, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "And", + "polygon": [ + { + "x": 4.0876, + "y": 2.3108 + }, + { + "x": 4.3216, + "y": 2.3108 + }, + { + "x": 4.3216, + "y": 2.4588 + }, + { + "x": 4.0876, + "y": 2.4588 + } + ], + "span": { + "offset": 300, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 4.3598, + "y": 2.3108 + }, + { + "x": 4.6798, + "y": 2.3108 + }, + { + "x": 4.6798, + "y": 2.454 + }, + { + "x": 4.3598, + "y": 2.4588 + } + ], + "span": { + "offset": 304, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 4.718, + "y": 2.3108 + }, + { + "x": 4.9997, + "y": 2.3108 + }, + { + "x": 4.9997, + "y": 2.454 + }, + { + "x": 4.718, + "y": 2.454 + } + ], + "span": { + "offset": 309, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "And", + "polygon": [ + { + "x": 5.0284, + "y": 2.3108 + }, + { + "x": 5.2671, + "y": 2.306 + }, + { + "x": 5.2671, + "y": 2.454 + }, + { + "x": 5.0284, + "y": 2.454 + } + ], + "span": { + "offset": 315, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 0.9885, + "y": 2.4874 + }, + { + "x": 1.3037, + "y": 2.4826 + }, + { + "x": 1.3037, + "y": 2.6211 + }, + { + "x": 0.9933, + "y": 2.6211 + } + ], + "span": { + "offset": 319, + "length": 4 + }, + "confidence": 0.985 + }, + { + "content": "text.", + "polygon": [ + { + "x": 1.3371, + "y": 2.4826 + }, + { + "x": 1.6236, + "y": 2.4826 + }, + { + "x": 1.6284, + "y": 2.6211 + }, + { + "x": 1.3419, + "y": 2.6211 + } + ], + "span": { + "offset": 324, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 1.6522, + "y": 2.4826 + }, + { + "x": 1.8862, + "y": 2.4826 + }, + { + "x": 1.8862, + "y": 2.6211 + }, + { + "x": 1.657, + "y": 2.6211 + } + ], + "span": { + "offset": 330, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 1.9197, + "y": 2.4826 + }, + { + "x": 2.2444, + "y": 2.4779 + }, + { + "x": 2.2492, + "y": 2.6211 + }, + { + "x": 1.9244, + "y": 2.6211 + } + ], + "span": { + "offset": 334, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 2.2826, + "y": 2.4779 + }, + { + "x": 2.5691, + "y": 2.4779 + }, + { + "x": 2.5691, + "y": 2.6211 + }, + { + "x": 2.2826, + "y": 2.6211 + } + ], + "span": { + "offset": 339, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "And", + "polygon": [ + { + "x": 2.5978, + "y": 2.4779 + }, + { + "x": 2.827, + "y": 2.4779 + }, + { + "x": 2.8317, + "y": 2.6211 + }, + { + "x": 2.5978, + "y": 2.6211 + } + ], + "span": { + "offset": 345, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 2.8652, + "y": 2.4779 + }, + { + "x": 3.1899, + "y": 2.4779 + }, + { + "x": 3.1899, + "y": 2.6211 + }, + { + "x": 2.8652, + "y": 2.6211 + } + ], + "span": { + "offset": 349, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 3.2233, + "y": 2.4779 + }, + { + "x": 3.5098, + "y": 2.4779 + }, + { + "x": 3.5146, + "y": 2.6211 + }, + { + "x": 3.2281, + "y": 2.6211 + } + ], + "span": { + "offset": 354, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 3.5385, + "y": 2.4779 + }, + { + "x": 3.7725, + "y": 2.4779 + }, + { + "x": 3.7725, + "y": 2.6211 + }, + { + "x": 3.5433, + "y": 2.6211 + } + ], + "span": { + "offset": 360, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 3.8059, + "y": 2.4779 + }, + { + "x": 4.1306, + "y": 2.4779 + }, + { + "x": 4.1306, + "y": 2.6211 + }, + { + "x": 3.8107, + "y": 2.6211 + } + ], + "span": { + "offset": 364, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 4.1688, + "y": 2.4779 + }, + { + "x": 4.4458, + "y": 2.4779 + }, + { + "x": 4.4458, + "y": 2.6211 + }, + { + "x": 4.1688, + "y": 2.6211 + } + ], + "span": { + "offset": 369, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 4.4744, + "y": 2.4779 + }, + { + "x": 4.7132, + "y": 2.4779 + }, + { + "x": 4.7132, + "y": 2.6211 + }, + { + "x": 4.4744, + "y": 2.6211 + } + ], + "span": { + "offset": 375, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "more", + "polygon": [ + { + "x": 4.7514, + "y": 2.4779 + }, + { + "x": 5.0761, + "y": 2.4779 + }, + { + "x": 5.0761, + "y": 2.6211 + }, + { + "x": 4.7514, + "y": 2.6211 + } + ], + "span": { + "offset": 379, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 5.1096, + "y": 2.4779 + }, + { + "x": 5.3722, + "y": 2.4826 + }, + { + "x": 5.3722, + "y": 2.6211 + }, + { + "x": 5.1143, + "y": 2.6211 + } + ], + "span": { + "offset": 384, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "And", + "polygon": [ + { + "x": 0.998, + "y": 2.6497 + }, + { + "x": 1.2272, + "y": 2.6497 + }, + { + "x": 1.2272, + "y": 2.7834 + }, + { + "x": 0.998, + "y": 2.7834 + } + ], + "span": { + "offset": 390, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 1.2702, + "y": 2.6497 + }, + { + "x": 1.5854, + "y": 2.6497 + }, + { + "x": 1.5854, + "y": 2.7786 + }, + { + "x": 1.2702, + "y": 2.7834 + } + ], + "span": { + "offset": 394, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 1.6284, + "y": 2.6497 + }, + { + "x": 1.9149, + "y": 2.6497 + }, + { + "x": 1.9197, + "y": 2.7786 + }, + { + "x": 1.6284, + "y": 2.7786 + } + ], + "span": { + "offset": 399, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "And", + "polygon": [ + { + "x": 1.9435, + "y": 2.6497 + }, + { + "x": 2.1728, + "y": 2.6497 + }, + { + "x": 2.1728, + "y": 2.7786 + }, + { + "x": 1.9435, + "y": 2.7786 + } + ], + "span": { + "offset": 405, + "length": 3 + }, + "confidence": 0.998 + }, + { + "content": "more", + "polygon": [ + { + "x": 2.2157, + "y": 2.6497 + }, + { + "x": 2.5309, + "y": 2.6497 + }, + { + "x": 2.5309, + "y": 2.7786 + }, + { + "x": 2.2157, + "y": 2.7786 + } + ], + "span": { + "offset": 409, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 2.5739, + "y": 2.6545 + }, + { + "x": 2.8413, + "y": 2.6545 + }, + { + "x": 2.8413, + "y": 2.7834 + }, + { + "x": 2.5739, + "y": 2.7786 + } + ], + "span": { + "offset": 414, + "length": 5 + }, + "confidence": 0.992 + }, + { + "content": "And", + "polygon": [ + { + "x": 0.9885, + "y": 2.9792 + }, + { + "x": 1.232, + "y": 2.9792 + }, + { + "x": 1.2368, + "y": 3.1128 + }, + { + "x": 0.9933, + "y": 3.1128 + } + ], + "span": { + "offset": 420, + "length": 3 + }, + "confidence": 0.994 + }, + { + "content": "more", + "polygon": [ + { + "x": 1.2702, + "y": 2.9792 + }, + { + "x": 1.5902, + "y": 2.9744 + }, + { + "x": 1.5902, + "y": 3.1128 + }, + { + "x": 1.2702, + "y": 3.1128 + } + ], + "span": { + "offset": 424, + "length": 4 + }, + "confidence": 0.99 + }, + { + "content": "text.", + "polygon": [ + { + "x": 1.6284, + "y": 2.9744 + }, + { + "x": 1.9053, + "y": 2.9744 + }, + { + "x": 1.9101, + "y": 3.1176 + }, + { + "x": 1.6284, + "y": 3.1128 + } + ], + "span": { + "offset": 429, + "length": 5 + }, + "confidence": 0.982 + }, + { + "content": "And", + "polygon": [ + { + "x": 1.934, + "y": 2.9744 + }, + { + "x": 2.1775, + "y": 2.9744 + }, + { + "x": 2.1823, + "y": 3.1176 + }, + { + "x": 1.9388, + "y": 3.1176 + } + ], + "span": { + "offset": 435, + "length": 3 + }, + "confidence": 0.993 + }, + { + "content": "more", + "polygon": [ + { + "x": 2.2062, + "y": 2.9744 + }, + { + "x": 2.5357, + "y": 2.9744 + }, + { + "x": 2.5357, + "y": 3.1176 + }, + { + "x": 2.211, + "y": 3.1176 + } + ], + "span": { + "offset": 439, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 2.5643, + "y": 2.9744 + }, + { + "x": 2.8556, + "y": 2.9744 + }, + { + "x": 2.8556, + "y": 3.1176 + }, + { + "x": 2.5643, + "y": 3.1176 + } + ], + "span": { + "offset": 444, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "And", + "polygon": [ + { + "x": 2.8795, + "y": 2.9744 + }, + { + "x": 3.1135, + "y": 2.9744 + }, + { + "x": 3.1183, + "y": 3.1176 + }, + { + "x": 2.8843, + "y": 3.1176 + } + ], + "span": { + "offset": 450, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "more", + "polygon": [ + { + "x": 3.1517, + "y": 2.9744 + }, + { + "x": 3.4716, + "y": 2.9744 + }, + { + "x": 3.4716, + "y": 3.1176 + }, + { + "x": 3.1565, + "y": 3.1176 + } + ], + "span": { + "offset": 454, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 3.5098, + "y": 2.9744 + }, + { + "x": 3.7916, + "y": 2.9744 + }, + { + "x": 3.7916, + "y": 3.1176 + }, + { + "x": 3.5098, + "y": 3.1176 + } + ], + "span": { + "offset": 459, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 3.8202, + "y": 2.9744 + }, + { + "x": 4.0638, + "y": 2.9744 + }, + { + "x": 4.0638, + "y": 3.1224 + }, + { + "x": 3.8202, + "y": 3.1176 + } + ], + "span": { + "offset": 465, + "length": 3 + }, + "confidence": 0.993 + }, + { + "content": "more", + "polygon": [ + { + "x": 4.102, + "y": 2.9744 + }, + { + "x": 4.4171, + "y": 2.9744 + }, + { + "x": 4.4171, + "y": 3.1224 + }, + { + "x": 4.102, + "y": 3.1224 + } + ], + "span": { + "offset": 469, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 4.4553, + "y": 2.9744 + }, + { + "x": 4.7371, + "y": 2.9744 + }, + { + "x": 4.7371, + "y": 3.1224 + }, + { + "x": 4.4553, + "y": 3.1224 + } + ], + "span": { + "offset": 474, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "And", + "polygon": [ + { + "x": 4.7657, + "y": 2.9744 + }, + { + "x": 5.0093, + "y": 2.9744 + }, + { + "x": 5.0093, + "y": 3.1224 + }, + { + "x": 4.7657, + "y": 3.1224 + } + ], + "span": { + "offset": 480, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "more", + "polygon": [ + { + "x": 5.0379, + "y": 2.9744 + }, + { + "x": 5.3626, + "y": 2.9744 + }, + { + "x": 5.3626, + "y": 3.1224 + }, + { + "x": 5.0379, + "y": 3.1224 + } + ], + "span": { + "offset": 484, + "length": 4 + }, + "confidence": 0.992 + }, + { + "content": "text.", + "polygon": [ + { + "x": 0.9837, + "y": 3.1463 + }, + { + "x": 1.2607, + "y": 3.1463 + }, + { + "x": 1.2654, + "y": 3.2799 + }, + { + "x": 0.9837, + "y": 3.2799 + } + ], + "span": { + "offset": 489, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 1.2893, + "y": 3.1463 + }, + { + "x": 1.5329, + "y": 3.1463 + }, + { + "x": 1.5376, + "y": 3.2847 + }, + { + "x": 1.2941, + "y": 3.2799 + } + ], + "span": { + "offset": 495, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "more", + "polygon": [ + { + "x": 1.5711, + "y": 3.1463 + }, + { + "x": 1.8958, + "y": 3.1415 + }, + { + "x": 1.8958, + "y": 3.2847 + }, + { + "x": 1.5758, + "y": 3.2847 + } + ], + "span": { + "offset": 499, + "length": 4 + }, + "confidence": 0.992 + }, + { + "content": "text.", + "polygon": [ + { + "x": 1.9244, + "y": 3.1415 + }, + { + "x": 2.2062, + "y": 3.1415 + }, + { + "x": 2.2062, + "y": 3.2847 + }, + { + "x": 1.9244, + "y": 3.2847 + } + ], + "span": { + "offset": 504, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "And", + "polygon": [ + { + "x": 2.2348, + "y": 3.1415 + }, + { + "x": 2.4784, + "y": 3.1415 + }, + { + "x": 2.4784, + "y": 3.2847 + }, + { + "x": 2.2348, + "y": 3.2847 + } + ], + "span": { + "offset": 510, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "more", + "polygon": [ + { + "x": 2.507, + "y": 3.1415 + }, + { + "x": 2.8365, + "y": 3.1415 + }, + { + "x": 2.8365, + "y": 3.2847 + }, + { + "x": 2.507, + "y": 3.2847 + } + ], + "span": { + "offset": 514, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 2.8699, + "y": 3.1415 + }, + { + "x": 3.1517, + "y": 3.1415 + }, + { + "x": 3.1517, + "y": 3.2895 + }, + { + "x": 2.8699, + "y": 3.2847 + } + ], + "span": { + "offset": 519, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "Even", + "polygon": [ + { + "x": 3.1803, + "y": 3.1415 + }, + { + "x": 3.4907, + "y": 3.1415 + }, + { + "x": 3.4907, + "y": 3.2895 + }, + { + "x": 3.1803, + "y": 3.2895 + } + ], + "span": { + "offset": 525, + "length": 4 + }, + "confidence": 0.992 + }, + { + "content": "more.", + "polygon": [ + { + "x": 3.5289, + "y": 3.1415 + }, + { + "x": 3.9014, + "y": 3.1415 + }, + { + "x": 3.8966, + "y": 3.2943 + }, + { + "x": 3.5289, + "y": 3.2895 + } + ], + "span": { + "offset": 530, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "Continued", + "polygon": [ + { + "x": 3.9301, + "y": 3.1415 + }, + { + "x": 4.5604, + "y": 3.1415 + }, + { + "x": 4.5604, + "y": 3.299 + }, + { + "x": 3.9253, + "y": 3.2943 + } + ], + "span": { + "offset": 536, + "length": 9 + }, + "confidence": 0.993 + }, + { + "content": "on", + "polygon": [ + { + "x": 4.5986, + "y": 3.1415 + }, + { + "x": 4.7466, + "y": 3.1415 + }, + { + "x": 4.7419, + "y": 3.299 + }, + { + "x": 4.5986, + "y": 3.299 + } + ], + "span": { + "offset": 546, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "page", + "polygon": [ + { + "x": 4.7848, + "y": 3.1415 + }, + { + "x": 5.1048, + "y": 3.1415 + }, + { + "x": 5.1048, + "y": 3.3038 + }, + { + "x": 4.7848, + "y": 3.299 + } + ], + "span": { + "offset": 549, + "length": 4 + }, + "confidence": 0.983 + }, + { + "content": "2", + "polygon": [ + { + "x": 5.1525, + "y": 3.1415 + }, + { + "x": 5.2146, + "y": 3.1415 + }, + { + "x": 5.2098, + "y": 3.3038 + }, + { + "x": 5.1525, + "y": 3.3038 + } + ], + "span": { + "offset": 554, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "...", + "polygon": [ + { + "x": 5.2433, + "y": 3.1415 + }, + { + "x": 5.3913, + "y": 3.1415 + }, + { + "x": 5.3865, + "y": 3.3038 + }, + { + "x": 5.2385, + "y": 3.3038 + } + ], + "span": { + "offset": 556, + "length": 3 + }, + "confidence": 0.948 + } + ], + "selection_marks": [], + "spans": [ + { + "offset": 0, + "length": 559 + } + ], + "kind": "document", + "annotations": [], + "barcodes": [], + "formulas": [], + "images": [] + }, + { + "page_number": 2, + "angle": null, + "width": 8.5, + "height": 11.0, + "unit": "inch", + "lines": [ + { + "content": "Simple PDF File 2", + "polygon": [ + { + "x": 0.9073, + "y": 0.6732 + }, + { + "x": 3.911, + "y": 0.6684 + }, + { + "x": 3.9157, + "y": 1.0169 + }, + { + "x": 0.9073, + "y": 1.0551 + } + ], + "spans": [ + { + "offset": 560, + "length": 17 + } + ] + }, + { + "content": "... continued from page 1. Yet more text. And more text. And more text.", + "polygon": [ + { + "x": 0.998, + "y": 1.3129 + }, + { + "x": 5.3244, + "y": 1.3129 + }, + { + "x": 5.3244, + "y": 1.4609 + }, + { + "x": 0.998, + "y": 1.4657 + } + ], + "spans": [ + { + "offset": 578, + "length": 71 + } + ] + }, + { + "content": "And more text. And more text. And more text. And more text. And more", + "polygon": [ + { + "x": 0.9837, + "y": 1.48 + }, + { + "x": 5.3674, + "y": 1.48 + }, + { + "x": 5.3674, + "y": 1.628 + }, + { + "x": 0.9837, + "y": 1.628 + } + ], + "spans": [ + { + "offset": 650, + "length": 68 + } + ] + }, + { + "content": "text. Oh, how boring typing this stuff. But not as boring as watching", + "polygon": [ + { + "x": 0.9789, + "y": 1.6424 + }, + { + "x": 5.1096, + "y": 1.6471 + }, + { + "x": 5.1096, + "y": 1.7999 + }, + { + "x": 0.9789, + "y": 1.7951 + } + ], + "spans": [ + { + "offset": 719, + "length": 69 + } + ] + }, + { + "content": "paint dry. And more text. And more text. And more text. And more text.", + "polygon": [ + { + "x": 0.9789, + "y": 1.8142 + }, + { + "x": 5.3388, + "y": 1.8095 + }, + { + "x": 5.3388, + "y": 1.9622 + }, + { + "x": 0.9789, + "y": 1.967 + } + ], + "spans": [ + { + "offset": 789, + "length": 70 + } + ] + }, + { + "content": "Boring. More, a little more text. The end, and just as well.", + "polygon": [ + { + "x": 0.9837, + "y": 1.9766 + }, + { + "x": 4.5461, + "y": 1.9766 + }, + { + "x": 4.5461, + "y": 2.1341 + }, + { + "x": 0.9837, + "y": 2.1341 + } + ], + "spans": [ + { + "offset": 860, + "length": 60 + } + ] + } + ], + "words": [ + { + "content": "Simple", + "polygon": [ + { + "x": 0.9169, + "y": 0.678 + }, + { + "x": 2.0199, + "y": 0.6732 + }, + { + "x": 2.0199, + "y": 1.036 + }, + { + "x": 0.9073, + "y": 1.0599 + } + ], + "span": { + "offset": 560, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "PDF", + "polygon": [ + { + "x": 2.1393, + "y": 0.6732 + }, + { + "x": 2.8556, + "y": 0.6732 + }, + { + "x": 2.8556, + "y": 1.0169 + }, + { + "x": 2.1346, + "y": 1.036 + } + ], + "span": { + "offset": 567, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "File", + "polygon": [ + { + "x": 2.9941, + "y": 0.6732 + }, + { + "x": 3.5719, + "y": 0.6732 + }, + { + "x": 3.5767, + "y": 0.9978 + }, + { + "x": 2.9989, + "y": 1.0122 + } + ], + "span": { + "offset": 571, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "2", + "polygon": [ + { + "x": 3.7343, + "y": 0.6732 + }, + { + "x": 3.9014, + "y": 0.6732 + }, + { + "x": 3.911, + "y": 0.9883 + }, + { + "x": 3.7438, + "y": 0.9931 + } + ], + "span": { + "offset": 576, + "length": 1 + }, + "confidence": 0.997 + }, + { + "content": "...", + "polygon": [ + { + "x": 0.998, + "y": 1.3225 + }, + { + "x": 1.0744, + "y": 1.3225 + }, + { + "x": 1.0744, + "y": 1.4705 + }, + { + "x": 0.998, + "y": 1.4705 + } + ], + "span": { + "offset": 578, + "length": 3 + }, + "confidence": 0.993 + }, + { + "content": "continued", + "polygon": [ + { + "x": 1.1031, + "y": 1.3225 + }, + { + "x": 1.7096, + "y": 1.3177 + }, + { + "x": 1.7096, + "y": 1.4705 + }, + { + "x": 1.1031, + "y": 1.4705 + } + ], + "span": { + "offset": 582, + "length": 9 + }, + "confidence": 0.992 + }, + { + "content": "from", + "polygon": [ + { + "x": 1.7382, + "y": 1.3177 + }, + { + "x": 1.9865, + "y": 1.3177 + }, + { + "x": 1.9865, + "y": 1.4705 + }, + { + "x": 1.7382, + "y": 1.4705 + } + ], + "span": { + "offset": 592, + "length": 4 + }, + "confidence": 0.985 + }, + { + "content": "page", + "polygon": [ + { + "x": 2.0581, + "y": 1.3177 + }, + { + "x": 2.3733, + "y": 1.3177 + }, + { + "x": 2.3733, + "y": 1.4705 + }, + { + "x": 2.0534, + "y": 1.4705 + } + ], + "span": { + "offset": 597, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "1.", + "polygon": [ + { + "x": 2.4306, + "y": 1.3177 + }, + { + "x": 2.55, + "y": 1.3177 + }, + { + "x": 2.55, + "y": 1.4657 + }, + { + "x": 2.4306, + "y": 1.4705 + } + ], + "span": { + "offset": 602, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "Yet", + "polygon": [ + { + "x": 2.5834, + "y": 1.3129 + }, + { + "x": 2.7792, + "y": 1.3129 + }, + { + "x": 2.7792, + "y": 1.4657 + }, + { + "x": 2.5787, + "y": 1.4657 + } + ], + "span": { + "offset": 605, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "more", + "polygon": [ + { + "x": 2.8079, + "y": 1.3129 + }, + { + "x": 3.1374, + "y": 1.3129 + }, + { + "x": 3.1326, + "y": 1.4657 + }, + { + "x": 2.8079, + "y": 1.4657 + } + ], + "span": { + "offset": 609, + "length": 4 + }, + "confidence": 0.983 + }, + { + "content": "text.", + "polygon": [ + { + "x": 3.166, + "y": 1.3129 + }, + { + "x": 3.443, + "y": 1.3129 + }, + { + "x": 3.443, + "y": 1.4657 + }, + { + "x": 3.166, + "y": 1.4657 + } + ], + "span": { + "offset": 614, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 3.4716, + "y": 1.3129 + }, + { + "x": 3.7199, + "y": 1.3129 + }, + { + "x": 3.7199, + "y": 1.4657 + }, + { + "x": 3.4716, + "y": 1.4657 + } + ], + "span": { + "offset": 620, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "more", + "polygon": [ + { + "x": 3.7486, + "y": 1.3129 + }, + { + "x": 4.0781, + "y": 1.3129 + }, + { + "x": 4.0733, + "y": 1.4657 + }, + { + "x": 3.7486, + "y": 1.4657 + } + ], + "span": { + "offset": 624, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 4.1067, + "y": 1.3129 + }, + { + "x": 4.3933, + "y": 1.3177 + }, + { + "x": 4.3933, + "y": 1.4657 + }, + { + "x": 4.1067, + "y": 1.4657 + } + ], + "span": { + "offset": 629, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "And", + "polygon": [ + { + "x": 4.4267, + "y": 1.3177 + }, + { + "x": 4.6607, + "y": 1.3177 + }, + { + "x": 4.6607, + "y": 1.4657 + }, + { + "x": 4.4219, + "y": 1.4657 + } + ], + "span": { + "offset": 635, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 4.6941, + "y": 1.3177 + }, + { + "x": 5.0188, + "y": 1.3177 + }, + { + "x": 5.014, + "y": 1.4657 + }, + { + "x": 4.6893, + "y": 1.4657 + } + ], + "span": { + "offset": 639, + "length": 4 + }, + "confidence": 0.979 + }, + { + "content": "text.", + "polygon": [ + { + "x": 5.0475, + "y": 1.3177 + }, + { + "x": 5.3292, + "y": 1.3177 + }, + { + "x": 5.3244, + "y": 1.4657 + }, + { + "x": 5.0475, + "y": 1.4657 + } + ], + "span": { + "offset": 644, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "And", + "polygon": [ + { + "x": 0.9933, + "y": 1.48 + }, + { + "x": 1.2368, + "y": 1.48 + }, + { + "x": 1.2416, + "y": 1.6328 + }, + { + "x": 0.998, + "y": 1.6328 + } + ], + "span": { + "offset": 650, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "more", + "polygon": [ + { + "x": 1.2702, + "y": 1.48 + }, + { + "x": 1.5902, + "y": 1.48 + }, + { + "x": 1.5949, + "y": 1.6328 + }, + { + "x": 1.2702, + "y": 1.6328 + } + ], + "span": { + "offset": 654, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 1.6188, + "y": 1.48 + }, + { + "x": 1.9053, + "y": 1.48 + }, + { + "x": 1.9053, + "y": 1.6328 + }, + { + "x": 1.6236, + "y": 1.6328 + } + ], + "span": { + "offset": 659, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "And", + "polygon": [ + { + "x": 1.934, + "y": 1.48 + }, + { + "x": 2.1775, + "y": 1.48 + }, + { + "x": 2.1775, + "y": 1.6328 + }, + { + "x": 1.934, + "y": 1.6328 + } + ], + "span": { + "offset": 665, + "length": 3 + }, + "confidence": 0.994 + }, + { + "content": "more", + "polygon": [ + { + "x": 2.2062, + "y": 1.48 + }, + { + "x": 2.5309, + "y": 1.48 + }, + { + "x": 2.5309, + "y": 1.6328 + }, + { + "x": 2.211, + "y": 1.6328 + } + ], + "span": { + "offset": 669, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 2.5691, + "y": 1.48 + }, + { + "x": 2.8508, + "y": 1.4848 + }, + { + "x": 2.8556, + "y": 1.6328 + }, + { + "x": 2.5691, + "y": 1.6328 + } + ], + "span": { + "offset": 674, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 2.8795, + "y": 1.4848 + }, + { + "x": 3.1183, + "y": 1.4848 + }, + { + "x": 3.1183, + "y": 1.6328 + }, + { + "x": 2.8843, + "y": 1.6328 + } + ], + "span": { + "offset": 680, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 3.1565, + "y": 1.4848 + }, + { + "x": 3.4764, + "y": 1.4848 + }, + { + "x": 3.4812, + "y": 1.6328 + }, + { + "x": 3.1565, + "y": 1.6328 + } + ], + "span": { + "offset": 684, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 3.5051, + "y": 1.4848 + }, + { + "x": 3.7916, + "y": 1.4848 + }, + { + "x": 3.7916, + "y": 1.6328 + }, + { + "x": 3.5098, + "y": 1.6328 + } + ], + "span": { + "offset": 689, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 3.8202, + "y": 1.4848 + }, + { + "x": 4.0638, + "y": 1.4848 + }, + { + "x": 4.0638, + "y": 1.6328 + }, + { + "x": 3.8202, + "y": 1.6328 + } + ], + "span": { + "offset": 695, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "more", + "polygon": [ + { + "x": 4.0924, + "y": 1.4848 + }, + { + "x": 4.4171, + "y": 1.4848 + }, + { + "x": 4.4171, + "y": 1.6328 + }, + { + "x": 4.0924, + "y": 1.6328 + } + ], + "span": { + "offset": 699, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 4.4553, + "y": 1.4848 + }, + { + "x": 4.7371, + "y": 1.4848 + }, + { + "x": 4.7419, + "y": 1.6328 + }, + { + "x": 4.4553, + "y": 1.6328 + } + ], + "span": { + "offset": 704, + "length": 5 + }, + "confidence": 0.994 + }, + { + "content": "And", + "polygon": [ + { + "x": 4.7705, + "y": 1.4848 + }, + { + "x": 5.0045, + "y": 1.4848 + }, + { + "x": 5.0045, + "y": 1.6328 + }, + { + "x": 4.7705, + "y": 1.6328 + } + ], + "span": { + "offset": 710, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 5.0427, + "y": 1.4848 + }, + { + "x": 5.3626, + "y": 1.4848 + }, + { + "x": 5.3626, + "y": 1.6328 + }, + { + "x": 5.0427, + "y": 1.6328 + } + ], + "span": { + "offset": 714, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 0.9837, + "y": 1.6471 + }, + { + "x": 1.2607, + "y": 1.6471 + }, + { + "x": 1.2654, + "y": 1.7999 + }, + { + "x": 0.9837, + "y": 1.7999 + } + ], + "span": { + "offset": 719, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "Oh,", + "polygon": [ + { + "x": 1.2893, + "y": 1.6471 + }, + { + "x": 1.5138, + "y": 1.6471 + }, + { + "x": 1.5138, + "y": 1.7999 + }, + { + "x": 1.2941, + "y": 1.7999 + } + ], + "span": { + "offset": 725, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "how", + "polygon": [ + { + "x": 1.5424, + "y": 1.6471 + }, + { + "x": 1.7812, + "y": 1.6471 + }, + { + "x": 1.786, + "y": 1.7999 + }, + { + "x": 1.5424, + "y": 1.7999 + } + ], + "span": { + "offset": 729, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "boring", + "polygon": [ + { + "x": 1.8433, + "y": 1.6471 + }, + { + "x": 2.2348, + "y": 1.6471 + }, + { + "x": 2.2348, + "y": 1.7999 + }, + { + "x": 1.848, + "y": 1.7999 + } + ], + "span": { + "offset": 733, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "typing", + "polygon": [ + { + "x": 2.2635, + "y": 1.6471 + }, + { + "x": 2.6455, + "y": 1.6471 + }, + { + "x": 2.6503, + "y": 1.7999 + }, + { + "x": 2.2683, + "y": 1.7999 + } + ], + "span": { + "offset": 740, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "this", + "polygon": [ + { + "x": 2.6789, + "y": 1.6471 + }, + { + "x": 2.9081, + "y": 1.6471 + }, + { + "x": 2.9081, + "y": 1.7999 + }, + { + "x": 2.6789, + "y": 1.7999 + } + ], + "span": { + "offset": 747, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "stuff.", + "polygon": [ + { + "x": 2.9368, + "y": 1.6471 + }, + { + "x": 3.2472, + "y": 1.6471 + }, + { + "x": 3.252, + "y": 1.8047 + }, + { + "x": 2.9416, + "y": 1.7999 + } + ], + "span": { + "offset": 752, + "length": 6 + }, + "confidence": 0.995 + }, + { + "content": "But", + "polygon": [ + { + "x": 3.2806, + "y": 1.6471 + }, + { + "x": 3.4907, + "y": 1.6471 + }, + { + "x": 3.4907, + "y": 1.8047 + }, + { + "x": 3.2806, + "y": 1.8047 + } + ], + "span": { + "offset": 759, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "not", + "polygon": [ + { + "x": 3.5194, + "y": 1.6471 + }, + { + "x": 3.7295, + "y": 1.6471 + }, + { + "x": 3.7343, + "y": 1.8047 + }, + { + "x": 3.5242, + "y": 1.8047 + } + ], + "span": { + "offset": 763, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "as", + "polygon": [ + { + "x": 3.7629, + "y": 1.6471 + }, + { + "x": 3.9014, + "y": 1.6471 + }, + { + "x": 3.9014, + "y": 1.8047 + }, + { + "x": 3.7629, + "y": 1.8047 + } + ], + "span": { + "offset": 767, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "boring", + "polygon": [ + { + "x": 3.9348, + "y": 1.6471 + }, + { + "x": 4.336, + "y": 1.6471 + }, + { + "x": 4.336, + "y": 1.8047 + }, + { + "x": 3.9348, + "y": 1.8047 + } + ], + "span": { + "offset": 770, + "length": 6 + }, + "confidence": 0.994 + }, + { + "content": "as", + "polygon": [ + { + "x": 4.3742, + "y": 1.6471 + }, + { + "x": 4.5174, + "y": 1.6519 + }, + { + "x": 4.5174, + "y": 1.8047 + }, + { + "x": 4.3742, + "y": 1.8047 + } + ], + "span": { + "offset": 777, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "watching", + "polygon": [ + { + "x": 4.5461, + "y": 1.6519 + }, + { + "x": 5.1096, + "y": 1.6519 + }, + { + "x": 5.1096, + "y": 1.8047 + }, + { + "x": 4.5461, + "y": 1.8047 + } + ], + "span": { + "offset": 780, + "length": 8 + }, + "confidence": 0.995 + }, + { + "content": "paint", + "polygon": [ + { + "x": 0.9837, + "y": 1.8142 + }, + { + "x": 1.2893, + "y": 1.8142 + }, + { + "x": 1.2941, + "y": 1.9718 + }, + { + "x": 0.9885, + "y": 1.9718 + } + ], + "span": { + "offset": 789, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "dry.", + "polygon": [ + { + "x": 1.3228, + "y": 1.8142 + }, + { + "x": 1.5711, + "y": 1.8142 + }, + { + "x": 1.5758, + "y": 1.967 + }, + { + "x": 1.3275, + "y": 1.9718 + } + ], + "span": { + "offset": 795, + "length": 4 + }, + "confidence": 0.991 + }, + { + "content": "And", + "polygon": [ + { + "x": 1.5997, + "y": 1.8142 + }, + { + "x": 1.8433, + "y": 1.8142 + }, + { + "x": 1.848, + "y": 1.967 + }, + { + "x": 1.6045, + "y": 1.967 + } + ], + "span": { + "offset": 800, + "length": 3 + }, + "confidence": 0.996 + }, + { + "content": "more", + "polygon": [ + { + "x": 1.8719, + "y": 1.8142 + }, + { + "x": 2.2062, + "y": 1.8142 + }, + { + "x": 2.211, + "y": 1.967 + }, + { + "x": 1.8767, + "y": 1.967 + } + ], + "span": { + "offset": 804, + "length": 4 + }, + "confidence": 0.989 + }, + { + "content": "text.", + "polygon": [ + { + "x": 2.2348, + "y": 1.8142 + }, + { + "x": 2.5166, + "y": 1.8142 + }, + { + "x": 2.5213, + "y": 1.967 + }, + { + "x": 2.2396, + "y": 1.967 + } + ], + "span": { + "offset": 809, + "length": 5 + }, + "confidence": 0.991 + }, + { + "content": "And", + "polygon": [ + { + "x": 2.5452, + "y": 1.8142 + }, + { + "x": 2.7888, + "y": 1.8142 + }, + { + "x": 2.7888, + "y": 1.967 + }, + { + "x": 2.55, + "y": 1.967 + } + ], + "span": { + "offset": 815, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 2.8174, + "y": 1.8142 + }, + { + "x": 3.1469, + "y": 1.8142 + }, + { + "x": 3.1517, + "y": 1.967 + }, + { + "x": 2.8222, + "y": 1.967 + } + ], + "span": { + "offset": 819, + "length": 4 + }, + "confidence": 0.97 + }, + { + "content": "text.", + "polygon": [ + { + "x": 3.1803, + "y": 1.8142 + }, + { + "x": 3.4621, + "y": 1.8142 + }, + { + "x": 3.4621, + "y": 1.967 + }, + { + "x": 3.1803, + "y": 1.967 + } + ], + "span": { + "offset": 824, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "And", + "polygon": [ + { + "x": 3.4907, + "y": 1.8142 + }, + { + "x": 3.7295, + "y": 1.8142 + }, + { + "x": 3.7343, + "y": 1.967 + }, + { + "x": 3.4907, + "y": 1.967 + } + ], + "span": { + "offset": 830, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 3.7629, + "y": 1.8142 + }, + { + "x": 4.0924, + "y": 1.8142 + }, + { + "x": 4.0924, + "y": 1.9622 + }, + { + "x": 3.7629, + "y": 1.967 + } + ], + "span": { + "offset": 834, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 4.1211, + "y": 1.8142 + }, + { + "x": 4.4028, + "y": 1.8142 + }, + { + "x": 4.4076, + "y": 1.9622 + }, + { + "x": 4.1258, + "y": 1.9622 + } + ], + "span": { + "offset": 839, + "length": 5 + }, + "confidence": 0.992 + }, + { + "content": "And", + "polygon": [ + { + "x": 4.4362, + "y": 1.8142 + }, + { + "x": 4.675, + "y": 1.8142 + }, + { + "x": 4.675, + "y": 1.9622 + }, + { + "x": 4.4362, + "y": 1.9622 + } + ], + "span": { + "offset": 845, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "more", + "polygon": [ + { + "x": 4.7037, + "y": 1.8142 + }, + { + "x": 5.0379, + "y": 1.8142 + }, + { + "x": 5.0379, + "y": 1.9622 + }, + { + "x": 4.7084, + "y": 1.9622 + } + ], + "span": { + "offset": 849, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 5.0666, + "y": 1.8142 + }, + { + "x": 5.3388, + "y": 1.8142 + }, + { + "x": 5.3388, + "y": 1.9622 + }, + { + "x": 5.0666, + "y": 1.9622 + } + ], + "span": { + "offset": 854, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "Boring.", + "polygon": [ + { + "x": 0.9885, + "y": 1.9766 + }, + { + "x": 1.4612, + "y": 1.9813 + }, + { + "x": 1.466, + "y": 2.1389 + }, + { + "x": 0.9885, + "y": 2.1389 + } + ], + "span": { + "offset": 860, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "More,", + "polygon": [ + { + "x": 1.4947, + "y": 1.9813 + }, + { + "x": 1.8671, + "y": 1.9813 + }, + { + "x": 1.8719, + "y": 2.1389 + }, + { + "x": 1.4947, + "y": 2.1389 + } + ], + "span": { + "offset": 868, + "length": 5 + }, + "confidence": 0.993 + }, + { + "content": "a", + "polygon": [ + { + "x": 1.9006, + "y": 1.9813 + }, + { + "x": 1.9722, + "y": 1.9813 + }, + { + "x": 1.977, + "y": 2.1389 + }, + { + "x": 1.9006, + "y": 2.1389 + } + ], + "span": { + "offset": 874, + "length": 1 + }, + "confidence": 0.996 + }, + { + "content": "little", + "polygon": [ + { + "x": 2.0056, + "y": 1.9813 + }, + { + "x": 2.2635, + "y": 1.9813 + }, + { + "x": 2.2635, + "y": 2.1389 + }, + { + "x": 2.0056, + "y": 2.1389 + } + ], + "span": { + "offset": 876, + "length": 6 + }, + "confidence": 0.993 + }, + { + "content": "more", + "polygon": [ + { + "x": 2.2969, + "y": 1.9813 + }, + { + "x": 2.6169, + "y": 1.9813 + }, + { + "x": 2.6169, + "y": 2.1389 + }, + { + "x": 2.2969, + "y": 2.1389 + } + ], + "span": { + "offset": 883, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "text.", + "polygon": [ + { + "x": 2.6503, + "y": 1.9813 + }, + { + "x": 2.9416, + "y": 1.9813 + }, + { + "x": 2.9416, + "y": 2.1389 + }, + { + "x": 2.6503, + "y": 2.1389 + } + ], + "span": { + "offset": 888, + "length": 5 + }, + "confidence": 0.991 + }, + { + "content": "The", + "polygon": [ + { + "x": 2.9702, + "y": 1.9813 + }, + { + "x": 3.1994, + "y": 1.9813 + }, + { + "x": 3.1994, + "y": 2.1389 + }, + { + "x": 2.9702, + "y": 2.1389 + } + ], + "span": { + "offset": 894, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "end,", + "polygon": [ + { + "x": 3.2281, + "y": 1.9813 + }, + { + "x": 3.5194, + "y": 1.9813 + }, + { + "x": 3.5242, + "y": 2.1389 + }, + { + "x": 3.2329, + "y": 2.1389 + } + ], + "span": { + "offset": 898, + "length": 4 + }, + "confidence": 0.99 + }, + { + "content": "and", + "polygon": [ + { + "x": 3.5528, + "y": 1.9813 + }, + { + "x": 3.7725, + "y": 1.9813 + }, + { + "x": 3.7725, + "y": 2.1389 + }, + { + "x": 3.5528, + "y": 2.1389 + } + ], + "span": { + "offset": 903, + "length": 3 + }, + "confidence": 0.997 + }, + { + "content": "just", + "polygon": [ + { + "x": 3.8011, + "y": 1.9813 + }, + { + "x": 4.0399, + "y": 1.9766 + }, + { + "x": 4.0399, + "y": 2.1389 + }, + { + "x": 3.8011, + "y": 2.1389 + } + ], + "span": { + "offset": 907, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "as", + "polygon": [ + { + "x": 4.0733, + "y": 1.9766 + }, + { + "x": 4.2166, + "y": 1.9766 + }, + { + "x": 4.2166, + "y": 2.1389 + }, + { + "x": 4.0733, + "y": 2.1389 + } + ], + "span": { + "offset": 912, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "well.", + "polygon": [ + { + "x": 4.25, + "y": 1.9766 + }, + { + "x": 4.5413, + "y": 1.9766 + }, + { + "x": 4.5413, + "y": 2.1389 + }, + { + "x": 4.25, + "y": 2.1389 + } + ], + "span": { + "offset": 915, + "length": 5 + }, + "confidence": 0.994 + } + ], + "selection_marks": [], + "spans": [ + { + "offset": 560, + "length": 360 + } + ], + "kind": "document", + "annotations": [], + "barcodes": [], + "formulas": [], + "images": [] + } + ], + "paragraphs": [ + { + "role": null, + "content": "A Simple PDF File", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.8787, + "y": 0.6684 + }, + { + "x": 3.9635, + "y": 0.6684 + }, + { + "x": 3.9635, + "y": 1.0408 + }, + { + "x": 0.8787, + "y": 1.0408 + } + ] + } + ], + "spans": [ + { + "offset": 0, + "length": 17 + } + ] + }, + { + "role": null, + "content": "This is a small demonstration .pdf file -", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.9837, + "y": 1.3129 + }, + { + "x": 3.3669, + "y": 1.3177 + }, + { + "x": 3.3666, + "y": 1.4657 + }, + { + "x": 0.9834, + "y": 1.4609 + } + ] + } + ], + "spans": [ + { + "offset": 18, + "length": 41 + } + ] + }, + { + "role": null, + "content": "just for use in the Virtual Mechanics tutorials. More text. And more text. And more text. And more text. And more text.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.9837, + "y": 1.6424 + }, + { + "x": 5.0522, + "y": 1.6424 + }, + { + "x": 5.0522, + "y": 1.9527 + }, + { + "x": 0.9837, + "y": 1.9527 + } + ] + } + ], + "spans": [ + { + "offset": 60, + "length": 119 + } + ] + }, + { + "role": null, + "content": "And 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.", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.9837, + "y": 2.1437 + }, + { + "x": 5.377, + "y": 2.1437 + }, + { + "x": 5.377, + "y": 2.7786 + }, + { + "x": 0.9837, + "y": 2.7786 + } + ] + } + ], + "spans": [ + { + "offset": 180, + "length": 239 + } + ] + }, + { + "role": null, + "content": "And 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 ...", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.9789, + "y": 2.9696 + }, + { + "x": 5.3865, + "y": 2.9696 + }, + { + "x": 5.3865, + "y": 3.299 + }, + { + "x": 0.9789, + "y": 3.299 + } + ] + } + ], + "spans": [ + { + "offset": 420, + "length": 139 + } + ] + }, + { + "role": null, + "content": "Simple PDF File 2", + "bounding_regions": [ + { + "page_number": 2, + "polygon": [ + { + "x": 0.9024, + "y": 0.6732 + }, + { + "x": 3.9109, + "y": 0.635 + }, + { + "x": 3.9157, + "y": 1.0169 + }, + { + "x": 0.9073, + "y": 1.0551 + } + ] + } + ], + "spans": [ + { + "offset": 560, + "length": 17 + } + ] + }, + { + "role": null, + "content": "... 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.", + "bounding_regions": [ + { + "page_number": 2, + "polygon": [ + { + "x": 0.9789, + "y": 1.3129 + }, + { + "x": 5.3674, + "y": 1.3129 + }, + { + "x": 5.3674, + "y": 2.1341 + }, + { + "x": 0.9789, + "y": 2.1341 + } + ] + } + ], + "spans": [ + { + "offset": 578, + "length": 342 + } + ] + } + ], + "tables": [], + "key_value_pairs": [], + "styles": [], + "documents": [] +} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/azure_sample_pdf_3.json b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/azure_sample_pdf_3.json new file mode 100644 index 0000000000000000000000000000000000000000..c88c4cf0f8801ada4a09f96e1817b10c9a21f777 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/azure_sample_pdf_3.json @@ -0,0 +1,1216 @@ +{ + "api_version": "2023-02-28-preview", + "model_id": "prebuilt-document", + "content": "Table 1. This is an example table with two multicolumn headers\nHeader 1\nThis is a subheader\nValue 1\nValue 2\nVal 3", + "languages": [], + "pages": [ + { + "page_number": 1, + "angle": null, + "width": 8.2778, + "height": 11.6944, + "unit": "inch", + "lines": [ + { + "content": "Table 1. This is an example table with two multicolumn headers", + "polygon": [ + { + "x": 0.9694, + "y": 1.2029 + }, + { + "x": 5.2732, + "y": 1.2029 + }, + { + "x": 5.2732, + "y": 1.3806 + }, + { + "x": 0.9694, + "y": 1.3806 + } + ], + "spans": [ + { + "offset": 0, + "length": 62 + } + ] + }, + { + "content": "Header 1", + "polygon": [ + { + "x": 3.7963, + "y": 1.4923 + }, + { + "x": 4.4307, + "y": 1.4923 + }, + { + "x": 4.4307, + "y": 1.6445 + }, + { + "x": 3.7963, + "y": 1.6445 + } + ], + "spans": [ + { + "offset": 63, + "length": 8 + } + ] + }, + { + "content": "This is a subheader", + "polygon": [ + { + "x": 3.441, + "y": 1.8323 + }, + { + "x": 4.7961, + "y": 1.8323 + }, + { + "x": 4.7961, + "y": 1.9846 + }, + { + "x": 3.441, + "y": 1.9846 + } + ], + "spans": [ + { + "offset": 72, + "length": 19 + } + ] + }, + { + "content": "Value 1", + "polygon": [ + { + "x": 1.0455, + "y": 2.147 + }, + { + "x": 1.5936, + "y": 2.142 + }, + { + "x": 1.5936, + "y": 2.3247 + }, + { + "x": 1.0455, + "y": 2.3247 + } + ], + "spans": [ + { + "offset": 92, + "length": 7 + } + ] + }, + { + "content": "Value 2", + "polygon": [ + { + "x": 3.1365, + "y": 2.1623 + }, + { + "x": 3.6644, + "y": 2.1623 + }, + { + "x": 3.6694, + "y": 2.3094 + }, + { + "x": 3.1365, + "y": 2.3145 + } + ], + "spans": [ + { + "offset": 100, + "length": 7 + } + ] + }, + { + "content": "Val 3", + "polygon": [ + { + "x": 5.2123, + "y": 2.1673 + }, + { + "x": 5.5727, + "y": 2.1572 + }, + { + "x": 5.5727, + "y": 2.3044 + }, + { + "x": 5.2174, + "y": 2.3094 + } + ], + "spans": [ + { + "offset": 108, + "length": 5 + } + ] + } + ], + "words": [ + { + "content": "Table", + "polygon": [ + { + "x": 0.9998, + "y": 1.2029 + }, + { + "x": 1.35, + "y": 1.2029 + }, + { + "x": 1.35, + "y": 1.3806 + }, + { + "x": 0.9998, + "y": 1.3755 + } + ], + "span": { + "offset": 0, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "1.", + "polygon": [ + { + "x": 1.4059, + "y": 1.2029 + }, + { + "x": 1.5429, + "y": 1.2029 + }, + { + "x": 1.5429, + "y": 1.3806 + }, + { + "x": 1.4109, + "y": 1.3806 + } + ], + "span": { + "offset": 6, + "length": 2 + }, + "confidence": 0.882 + }, + { + "content": "This", + "polygon": [ + { + "x": 1.5784, + "y": 1.2029 + }, + { + "x": 1.8474, + "y": 1.2029 + }, + { + "x": 1.8525, + "y": 1.3806 + }, + { + "x": 1.5784, + "y": 1.3806 + } + ], + "span": { + "offset": 9, + "length": 4 + }, + "confidence": 0.988 + }, + { + "content": "is", + "polygon": [ + { + "x": 1.8829, + "y": 1.2029 + }, + { + "x": 2.02, + "y": 1.2029 + }, + { + "x": 2.02, + "y": 1.3857 + }, + { + "x": 1.8829, + "y": 1.3806 + } + ], + "span": { + "offset": 14, + "length": 2 + }, + "confidence": 0.995 + }, + { + "content": "an", + "polygon": [ + { + "x": 2.0555, + "y": 1.2029 + }, + { + "x": 2.2128, + "y": 1.2029 + }, + { + "x": 2.2128, + "y": 1.3857 + }, + { + "x": 2.0555, + "y": 1.3857 + } + ], + "span": { + "offset": 17, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "example", + "polygon": [ + { + "x": 2.2585, + "y": 1.2029 + }, + { + "x": 2.832, + "y": 1.2029 + }, + { + "x": 2.8371, + "y": 1.3857 + }, + { + "x": 2.2585, + "y": 1.3857 + } + ], + "span": { + "offset": 20, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "table", + "polygon": [ + { + "x": 2.8675, + "y": 1.2029 + }, + { + "x": 3.2177, + "y": 1.208 + }, + { + "x": 3.2228, + "y": 1.3857 + }, + { + "x": 2.8675, + "y": 1.3857 + } + ], + "span": { + "offset": 28, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "with", + "polygon": [ + { + "x": 3.2533, + "y": 1.208 + }, + { + "x": 3.5222, + "y": 1.208 + }, + { + "x": 3.5273, + "y": 1.3857 + }, + { + "x": 3.2533, + "y": 1.3857 + } + ], + "span": { + "offset": 34, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "two", + "polygon": [ + { + "x": 3.5578, + "y": 1.208 + }, + { + "x": 3.8065, + "y": 1.208 + }, + { + "x": 3.8115, + "y": 1.3806 + }, + { + "x": 3.5578, + "y": 1.3857 + } + ], + "span": { + "offset": 39, + "length": 3 + }, + "confidence": 0.994 + }, + { + "content": "multicolumn", + "polygon": [ + { + "x": 3.842, + "y": 1.208 + }, + { + "x": 4.6693, + "y": 1.208 + }, + { + "x": 4.6693, + "y": 1.3755 + }, + { + "x": 3.842, + "y": 1.3806 + } + ], + "span": { + "offset": 43, + "length": 11 + }, + "confidence": 0.983 + }, + { + "content": "headers", + "polygon": [ + { + "x": 4.6997, + "y": 1.208 + }, + { + "x": 5.2681, + "y": 1.2131 + }, + { + "x": 5.2732, + "y": 1.3654 + }, + { + "x": 4.7048, + "y": 1.3755 + } + ], + "span": { + "offset": 55, + "length": 7 + }, + "confidence": 0.994 + }, + { + "content": "Header", + "polygon": [ + { + "x": 3.8014, + "y": 1.4973 + }, + { + "x": 4.3292, + "y": 1.4973 + }, + { + "x": 4.3343, + "y": 1.6445 + }, + { + "x": 3.8014, + "y": 1.6496 + } + ], + "span": { + "offset": 63, + "length": 6 + }, + "confidence": 0.982 + }, + { + "content": "1", + "polygon": [ + { + "x": 4.3698, + "y": 1.4973 + }, + { + "x": 4.4307, + "y": 1.4973 + }, + { + "x": 4.4358, + "y": 1.6445 + }, + { + "x": 4.3749, + "y": 1.6445 + } + ], + "span": { + "offset": 70, + "length": 1 + }, + "confidence": 0.996 + }, + { + "content": "This", + "polygon": [ + { + "x": 3.4613, + "y": 1.8323 + }, + { + "x": 3.7354, + "y": 1.8374 + }, + { + "x": 3.7405, + "y": 1.9846 + }, + { + "x": 3.4664, + "y": 1.9897 + } + ], + "span": { + "offset": 72, + "length": 4 + }, + "confidence": 0.993 + }, + { + "content": "is", + "polygon": [ + { + "x": 3.7659, + "y": 1.8374 + }, + { + "x": 3.8927, + "y": 1.8374 + }, + { + "x": 3.8978, + "y": 1.9846 + }, + { + "x": 3.7709, + "y": 1.9846 + } + ], + "span": { + "offset": 77, + "length": 2 + }, + "confidence": 0.996 + }, + { + "content": "a", + "polygon": [ + { + "x": 3.9333, + "y": 1.8374 + }, + { + "x": 4.0145, + "y": 1.8374 + }, + { + "x": 4.0145, + "y": 1.9846 + }, + { + "x": 3.9384, + "y": 1.9846 + } + ], + "span": { + "offset": 80, + "length": 1 + }, + "confidence": 0.996 + }, + { + "content": "subheader", + "polygon": [ + { + "x": 4.0602, + "y": 1.8374 + }, + { + "x": 4.7961, + "y": 1.8323 + }, + { + "x": 4.7961, + "y": 1.9897 + }, + { + "x": 4.0653, + "y": 1.9846 + } + ], + "span": { + "offset": 82, + "length": 9 + }, + "confidence": 0.991 + }, + { + "content": "Value", + "polygon": [ + { + "x": 1.0658, + "y": 2.1572 + }, + { + "x": 1.4414, + "y": 2.147 + }, + { + "x": 1.4414, + "y": 2.3298 + }, + { + "x": 1.0709, + "y": 2.3247 + } + ], + "span": { + "offset": 92, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "1", + "polygon": [ + { + "x": 1.4972, + "y": 2.147 + }, + { + "x": 1.5835, + "y": 2.147 + }, + { + "x": 1.5886, + "y": 2.3298 + }, + { + "x": 1.5023, + "y": 2.3298 + } + ], + "span": { + "offset": 98, + "length": 1 + }, + "confidence": 0.995 + }, + { + "content": "Value", + "polygon": [ + { + "x": 3.1467, + "y": 2.1673 + }, + { + "x": 3.5172, + "y": 2.1623 + }, + { + "x": 3.5172, + "y": 2.3145 + }, + { + "x": 3.1517, + "y": 2.3145 + } + ], + "span": { + "offset": 100, + "length": 5 + }, + "confidence": 0.995 + }, + { + "content": "2", + "polygon": [ + { + "x": 3.5831, + "y": 2.1623 + }, + { + "x": 3.6593, + "y": 2.1623 + }, + { + "x": 3.6593, + "y": 2.3145 + }, + { + "x": 3.5831, + "y": 2.3145 + } + ], + "span": { + "offset": 106, + "length": 1 + }, + "confidence": 0.997 + }, + { + "content": "Val", + "polygon": [ + { + "x": 5.2377, + "y": 2.1623 + }, + { + "x": 5.461, + "y": 2.1572 + }, + { + "x": 5.4661, + "y": 2.3044 + }, + { + "x": 5.2377, + "y": 2.3094 + } + ], + "span": { + "offset": 108, + "length": 3 + }, + "confidence": 0.995 + }, + { + "content": "3", + "polygon": [ + { + "x": 5.4915, + "y": 2.1572 + }, + { + "x": 5.5625, + "y": 2.1572 + }, + { + "x": 5.5676, + "y": 2.3044 + }, + { + "x": 5.4965, + "y": 2.3044 + } + ], + "span": { + "offset": 112, + "length": 1 + }, + "confidence": 0.997 + } + ], + "selection_marks": [], + "spans": [ + { + "offset": 0, + "length": 113 + } + ], + "kind": "document", + "annotations": [], + "barcodes": [], + "formulas": [], + "images": [] + } + ], + "paragraphs": [ + { + "role": null, + "content": "Table 1. This is an example table with two multicolumn headers", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.9694, + "y": 1.2029 + }, + { + "x": 5.2732, + "y": 1.2029 + }, + { + "x": 5.2732, + "y": 1.3806 + }, + { + "x": 0.9694, + "y": 1.3806 + } + ] + } + ], + "spans": [ + { + "offset": 0, + "length": 62 + } + ] + }, + { + "role": null, + "content": "Header 1", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 1.0034, + "y": 1.4013 + }, + { + "x": 7.2404, + "y": 1.4013 + }, + { + "x": 7.2469, + "y": 1.7164 + }, + { + "x": 1.0034, + "y": 1.7164 + } + ] + } + ], + "spans": [ + { + "offset": 63, + "length": 8 + } + ] + }, + { + "role": null, + "content": "This is a subheader", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 1.0034, + "y": 1.7164 + }, + { + "x": 7.2469, + "y": 1.7164 + }, + { + "x": 7.2469, + "y": 2.0508 + }, + { + "x": 1.0034, + "y": 2.0572 + } + ] + } + ], + "spans": [ + { + "offset": 72, + "length": 19 + } + ] + }, + { + "role": null, + "content": "Value 1", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 1.0034, + "y": 2.0572 + }, + { + "x": 2.35, + "y": 2.0572 + }, + { + "x": 2.35, + "y": 2.3852 + }, + { + "x": 1.0034, + "y": 2.3852 + } + ] + } + ], + "spans": [ + { + "offset": 92, + "length": 7 + } + ] + }, + { + "role": null, + "content": "Value 2", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.35, + "y": 2.0572 + }, + { + "x": 4.9402, + "y": 2.0572 + }, + { + "x": 4.9402, + "y": 2.3852 + }, + { + "x": 2.35, + "y": 2.3852 + } + ] + } + ], + "spans": [ + { + "offset": 100, + "length": 7 + } + ] + }, + { + "role": null, + "content": "Val 3", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.9402, + "y": 2.0572 + }, + { + "x": 7.2469, + "y": 2.0508 + }, + { + "x": 7.2533, + "y": 2.3852 + }, + { + "x": 4.9402, + "y": 2.3852 + } + ] + } + ], + "spans": [ + { + "offset": 108, + "length": 5 + } + ] + } + ], + "tables": [ + { + "row_count": 3, + "column_count": 3, + "cells": [ + { + "kind": "content", + "row_index": 0, + "column_index": 0, + "row_span": 1, + "column_span": 3, + "content": "Header 1", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 1.0034, + "y": 1.4013 + }, + { + "x": 7.2404, + "y": 1.4013 + }, + { + "x": 7.2469, + "y": 1.7164 + }, + { + "x": 1.0034, + "y": 1.7164 + } + ] + } + ], + "spans": [ + { + "offset": 63, + "length": 8 + } + ] + }, + { + "kind": "content", + "row_index": 1, + "column_index": 0, + "row_span": 1, + "column_span": 3, + "content": "This is a subheader", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 1.0034, + "y": 1.7164 + }, + { + "x": 7.2469, + "y": 1.7164 + }, + { + "x": 7.2469, + "y": 2.0508 + }, + { + "x": 1.0034, + "y": 2.0572 + } + ] + } + ], + "spans": [ + { + "offset": 72, + "length": 19 + } + ] + }, + { + "kind": "content", + "row_index": 2, + "column_index": 0, + "row_span": 1, + "column_span": 1, + "content": "Value 1", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 1.0034, + "y": 2.0572 + }, + { + "x": 2.35, + "y": 2.0572 + }, + { + "x": 2.35, + "y": 2.3852 + }, + { + "x": 1.0034, + "y": 2.3852 + } + ] + } + ], + "spans": [ + { + "offset": 92, + "length": 7 + } + ] + }, + { + "kind": "content", + "row_index": 2, + "column_index": 1, + "row_span": 1, + "column_span": 1, + "content": "Value 2", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 2.35, + "y": 2.0572 + }, + { + "x": 4.9402, + "y": 2.0572 + }, + { + "x": 4.9402, + "y": 2.3852 + }, + { + "x": 2.35, + "y": 2.3852 + } + ] + } + ], + "spans": [ + { + "offset": 100, + "length": 7 + } + ] + }, + { + "kind": "content", + "row_index": 2, + "column_index": 2, + "row_span": 1, + "column_span": 1, + "content": "Val 3", + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 4.9402, + "y": 2.0572 + }, + { + "x": 7.2469, + "y": 2.0508 + }, + { + "x": 7.2533, + "y": 2.3852 + }, + { + "x": 4.9402, + "y": 2.3852 + } + ] + } + ], + "spans": [ + { + "offset": 108, + "length": 5 + } + ] + } + ], + "bounding_regions": [ + { + "page_number": 1, + "polygon": [ + { + "x": 0.9871, + "y": 1.3971 + }, + { + "x": 7.2599, + "y": 1.3999 + }, + { + "x": 7.2593, + "y": 2.3987 + }, + { + "x": 0.9861, + "y": 2.3961 + } + ] + } + ], + "spans": [ + { + "offset": 63, + "length": 50 + } + ] + } + ], + "key_value_pairs": [], + "styles": [], + "documents": [] +} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/complex_types_openai_spec.json b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/complex_types_openai_spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ebaf955630dcc2d64094e3f0f47431e8f14c0e08 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/complex_types_openai_spec.json @@ -0,0 +1,64 @@ +{ + "name": "processPayment", + "description": "Process a new payment using the specified payment method", + "parameters": { + "type": "object", + "properties": { + "transaction_amount": { + "type": "number", + "description": "The amount to be paid" + }, + "description": { + "type": "string", + "description": "A brief description of the payment" + }, + "payment_method_id": { + "type": "string", + "description": "The payment method to be used" + }, + "payer": { + "type": "object", + "description": "Information about the payer, including their name, email, and identification number", + "properties": { + "name": { + "type": "string", + "description": "The payer's name" + }, + "email": { + "type": "string", + "description": "The payer's email address" + }, + "identification": { + "type": "object", + "description": "The payer's identification number", + "properties": { + "type": { + "type": "string", + "description": "The type of identification document (e.g., CPF, CNPJ)" + }, + "number": { + "type": "string", + "description": "The identification number" + } + }, + "required": [ + "type", + "number" + ] + } + }, + "required": [ + "name", + "email", + "identification" + ] + } + }, + "required": [ + "transaction_amount", + "description", + "payment_method_id", + "payer" + ] + } +} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/complex_types_openapi_service.json b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/complex_types_openapi_service.json new file mode 100644 index 0000000000000000000000000000000000000000..3ea04f8aa35df2b2874aad2f0101b5daa0b2930e --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/complex_types_openapi_service.json @@ -0,0 +1,103 @@ +{ + "openapi": "3.0.0", + "info": { + "title": "Payment API", + "version": "1.0.0" + }, + "servers": [ + { + "url": "http://localhost:8080" + } + ], + "paths": { + "/new_payment": { + "post": { + "summary": "Process a new payment", + "description": "Process a new payment using the specified payment method", + "operationId": "processPayment", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "transaction_amount": { + "type": "number", + "description": "The amount to be paid" + }, + "description": { + "type": "string", + "description": "A brief description of the payment" + }, + "payment_method_id": { + "type": "string", + "description": "The payment method to be used" + }, + "payer": { + "$ref": "#/components/schemas/Payer" + } + }, + "required": [ + "transaction_amount", + "description", + "payment_method_id", + "payer" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Payment processed successfully" + }, + "400": { + "description": "Invalid request" + } + } + } + } + }, + "components": { + "schemas": { + "Payer": { + "type": "object", + "description": "Information about the payer, including their name, email, and identification number", + "properties": { + "name": { + "type": "string", + "description": "The payer's name" + }, + "email": { + "type": "string", + "description": "The payer's email address" + }, + "identification": { + "type": "object", + "description": "The payer's identification number", + "properties": { + "type": { + "type": "string", + "description": "The type of identification document (e.g., CPF, CNPJ)" + }, + "number": { + "type": "string", + "description": "The identification number" + } + }, + "required": [ + "type", + "number" + ] + } + }, + "required": [ + "name", + "email", + "identification" + ] + } + } + } +} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/github_compare_branch_openapi_spec.json b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/github_compare_branch_openapi_spec.json new file mode 100644 index 0000000000000000000000000000000000000000..8bd7c7ed80ecb59bfb6faa731f66a8a26b35a180 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/json/github_compare_branch_openapi_spec.json @@ -0,0 +1,562 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Github API", + "description": "Enables interaction with OpenAPI", + "version": "v1.0.0" + }, + "servers": [ + { + "url": "https://api.github.com" + } + ], + "paths": { + "/repos/{owner}/{repo}/compare/{basehead}": { + "get": { + "summary": "Compare two branches", + "description": "Compares two branches against one another.", + "tags": [ + "repos" + ], + "operationId": "compare_branches", + "externalDocs": { + "description": "API method documentation", + "url": "https://docs.github.com/enterprise-server@3.9/rest/commits/commits#compare-two-commits" + }, + "parameters": [ + { + "name": "basehead", + "description": "The base branch and head branch to compare. This parameter expects the format `BASE...HEAD`", + "in": "path", + "required": true, + "x-multi-segment": true, + "schema": { + "type": "string" + } + }, + { + "name": "owner", + "description": "The repository owner, usually a company or orgnization", + "in": "path", + "required": true, + "x-multi-segment": true, + "schema": { + "type": "string" + } + }, + { + "name": "repo", + "description": "The repository itself, the project", + "in": "path", + "required": true, + "x-multi-segment": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/commit-comparison" + } + } + } + } + }, + "x-github": { + "githubCloudOnly": false, + "enabledForGitHubApps": true, + "category": "commits", + "subcategory": "commits" + } + } + } + }, + "components": { + "schemas": { + "commit-comparison": { + "title": "Commit Comparison", + "description": "Commit Comparison", + "type": "object", + "properties": { + "url": { + "type": "string", + "format": "uri", + "example": "https://api.github.com/repos/octocat/Hello-World/compare/master...topic" + }, + "html_url": { + "type": "string", + "format": "uri", + "example": "https://github.com/octocat/Hello-World/compare/master...topic" + }, + "permalink_url": { + "type": "string", + "format": "uri", + "example": "https://github.com/octocat/Hello-World/compare/octocat:bbcd538c8e72b8c175046e27cc8f907076331401...octocat:0328041d1152db8ae77652d1618a02e57f745f17" + }, + "diff_url": { + "type": "string", + "format": "uri", + "example": "https://github.com/octocat/Hello-World/compare/master...topic.diff" + }, + "patch_url": { + "type": "string", + "format": "uri", + "example": "https://github.com/octocat/Hello-World/compare/master...topic.patch" + }, + "base_commit": { + "$ref": "#/components/schemas/commit" + }, + "merge_base_commit": { + "$ref": "#/components/schemas/commit" + }, + "status": { + "type": "string", + "enum": [ + "diverged", + "ahead", + "behind", + "identical" + ], + "example": "ahead" + }, + "ahead_by": { + "type": "integer", + "example": 4 + }, + "behind_by": { + "type": "integer", + "example": 5 + }, + "total_commits": { + "type": "integer", + "example": 6 + }, + "commits": { + "type": "array", + "items": { + "$ref": "#/components/schemas/commit" + } + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/diff-entry" + } + } + }, + "required": [ + "url", + "html_url", + "permalink_url", + "diff_url", + "patch_url", + "base_commit", + "merge_base_commit", + "status", + "ahead_by", + "behind_by", + "total_commits", + "commits" + ] + }, + "nullable-git-user": { + "title": "Git User", + "description": "Metaproperties for Git author/committer information.", + "type": "object", + "properties": { + "name": { + "type": "string", + "example": "\"Chris Wanstrath\"" + }, + "email": { + "type": "string", + "example": "\"chris@ozmm.org\"" + }, + "date": { + "type": "string", + "example": "\"2007-10-29T02:42:39.000-07:00\"" + } + }, + "nullable": true + }, + "nullable-simple-user": { + "title": "Simple User", + "description": "A GitHub user.", + "type": "object", + "properties": { + "name": { + "nullable": true, + "type": "string" + }, + "email": { + "nullable": true, + "type": "string" + }, + "login": { + "type": "string", + "example": "octocat" + }, + "id": { + "type": "integer", + "example": 1 + }, + "node_id": { + "type": "string", + "example": "MDQ6VXNlcjE=" + }, + "avatar_url": { + "type": "string", + "format": "uri", + "example": "https://github.com/images/error/octocat_happy.gif" + }, + "gravatar_id": { + "type": "string", + "example": "41d064eb2195891e12d0413f63227ea7", + "nullable": true + }, + "url": { + "type": "string", + "format": "uri", + "example": "https://api.github.com/users/octocat" + }, + "html_url": { + "type": "string", + "format": "uri", + "example": "https://github.com/octocat" + }, + "followers_url": { + "type": "string", + "format": "uri", + "example": "https://api.github.com/users/octocat/followers" + }, + "following_url": { + "type": "string", + "example": "https://api.github.com/users/octocat/following{/other_user}" + }, + "gists_url": { + "type": "string", + "example": "https://api.github.com/users/octocat/gists{/gist_id}" + }, + "starred_url": { + "type": "string", + "example": "https://api.github.com/users/octocat/starred{/owner}{/repo}" + }, + "subscriptions_url": { + "type": "string", + "format": "uri", + "example": "https://api.github.com/users/octocat/subscriptions" + }, + "organizations_url": { + "type": "string", + "format": "uri", + "example": "https://api.github.com/users/octocat/orgs" + }, + "repos_url": { + "type": "string", + "format": "uri", + "example": "https://api.github.com/users/octocat/repos" + }, + "events_url": { + "type": "string", + "example": "https://api.github.com/users/octocat/events{/privacy}" + }, + "received_events_url": { + "type": "string", + "format": "uri", + "example": "https://api.github.com/users/octocat/received_events" + }, + "type": { + "type": "string", + "example": "User" + }, + "site_admin": { + "type": "boolean" + }, + "starred_at": { + "type": "string", + "example": "\"2020-07-09T00:17:55Z\"" + } + }, + "required": [ + "avatar_url", + "events_url", + "followers_url", + "following_url", + "gists_url", + "gravatar_id", + "html_url", + "id", + "node_id", + "login", + "organizations_url", + "received_events_url", + "repos_url", + "site_admin", + "starred_url", + "subscriptions_url", + "type", + "url" + ], + "nullable": true + }, + "verification": { + "title": "Verification", + "type": "object", + "properties": { + "verified": { + "type": "boolean" + }, + "reason": { + "type": "string" + }, + "payload": { + "type": "string", + "nullable": true + }, + "signature": { + "type": "string", + "nullable": true + } + }, + "required": [ + "verified", + "reason", + "payload", + "signature" + ] + }, + "diff-entry": { + "title": "Diff Entry", + "description": "Diff Entry", + "type": "object", + "properties": { + "sha": { + "type": "string", + "example": "bbcd538c8e72b8c175046e27cc8f907076331401" + }, + "filename": { + "type": "string", + "example": "file1.txt" + }, + "status": { + "type": "string", + "enum": [ + "added", + "removed", + "modified", + "renamed", + "copied", + "changed", + "unchanged" + ], + "example": "added" + }, + "additions": { + "type": "integer", + "example": 103 + }, + "deletions": { + "type": "integer", + "example": 21 + }, + "changes": { + "type": "integer", + "example": 124 + }, + "blob_url": { + "type": "string", + "format": "uri", + "example": "https://github.com/octocat/Hello-World/blob/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt" + }, + "raw_url": { + "type": "string", + "format": "uri", + "example": "https://github.com/octocat/Hello-World/raw/6dcb09b5b57875f334f61aebed695e2e4193db5e/file1.txt" + }, + "contents_url": { + "type": "string", + "format": "uri", + "example": "https://api.github.com/repos/octocat/Hello-World/contents/file1.txt?ref=6dcb09b5b57875f334f61aebed695e2e4193db5e" + }, + "patch": { + "type": "string", + "example": "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test" + }, + "previous_filename": { + "type": "string", + "example": "file.txt" + } + }, + "required": [ + "additions", + "blob_url", + "changes", + "contents_url", + "deletions", + "filename", + "raw_url", + "sha", + "status" + ] + }, + "commit": { + "title": "Commit", + "description": "Commit", + "type": "object", + "properties": { + "url": { + "type": "string", + "format": "uri", + "example": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e" + }, + "sha": { + "type": "string", + "example": "6dcb09b5b57875f334f61aebed695e2e4193db5e" + }, + "node_id": { + "type": "string", + "example": "MDY6Q29tbWl0NmRjYjA5YjViNTc4NzVmMzM0ZjYxYWViZWQ2OTVlMmU0MTkzZGI1ZQ==" + }, + "html_url": { + "type": "string", + "format": "uri", + "example": "https://github.com/octocat/Hello-World/commit/6dcb09b5b57875f334f61aebed695e2e4193db5e" + }, + "comments_url": { + "type": "string", + "format": "uri", + "example": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/comments" + }, + "commit": { + "type": "object", + "properties": { + "url": { + "type": "string", + "format": "uri", + "example": "https://api.github.com/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e" + }, + "author": { + "$ref": "#/components/schemas/nullable-git-user" + }, + "committer": { + "$ref": "#/components/schemas/nullable-git-user" + }, + "message": { + "type": "string", + "example": "Fix all the bugs" + }, + "comment_count": { + "type": "integer", + "example": 0 + }, + "tree": { + "type": "object", + "properties": { + "sha": { + "type": "string", + "example": "827efc6d56897b048c772eb4087f854f46256132" + }, + "url": { + "type": "string", + "format": "uri", + "example": "https://api.github.com/repos/octocat/Hello-World/tree/827efc6d56897b048c772eb4087f854f46256132" + } + }, + "required": [ + "sha", + "url" + ] + }, + "verification": { + "$ref": "#/components/schemas/verification" + } + }, + "required": [ + "author", + "committer", + "comment_count", + "message", + "tree", + "url" + ] + }, + "author": { + "$ref": "#/components/schemas/nullable-simple-user" + }, + "committer": { + "$ref": "#/components/schemas/nullable-simple-user" + }, + "parents": { + "type": "array", + "items": { + "type": "object", + "properties": { + "sha": { + "type": "string", + "example": "7638417db6d59f3c431d3e1f261cc637155684cd" + }, + "url": { + "type": "string", + "format": "uri", + "example": "https://api.github.com/repos/octocat/Hello-World/commits/7638417db6d59f3c431d3e1f261cc637155684cd" + }, + "html_url": { + "type": "string", + "format": "uri", + "example": "https://github.com/octocat/Hello-World/commit/7638417db6d59f3c431d3e1f261cc637155684cd" + } + }, + "required": [ + "sha", + "url" + ] + } + }, + "stats": { + "type": "object", + "properties": { + "additions": { + "type": "integer" + }, + "deletions": { + "type": "integer" + }, + "total": { + "type": "integer" + } + } + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/diff-entry" + } + } + }, + "required": [ + "url", + "sha", + "node_id", + "html_url", + "comments_url", + "commit", + "author", + "committer", + "parents" + ] + } + }, + "securitySchemes": { + "apikey": { + "type": "apiKey", + "name": "x-api-key", + "in": "header" + } + } + } +} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/markdown/sample.md b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/markdown/sample.md new file mode 100644 index 0000000000000000000000000000000000000000..d39e32d44ebf5e023411ae8a727706a1965d15aa --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/markdown/sample.md @@ -0,0 +1,65 @@ +--- +type: intro +date: 1.1.2023 +--- +```bash +pip install farm-haystack +``` +## What to build with Haystack + +- **Ask questions in natural language** and find granular answers in your own documents. +- Perform **semantic search** and retrieve documents according to meaning not keywords +- Use **off-the-shelf models** or **fine-tune** them to your own domain. +- Use **user feedback** to evaluate, benchmark and continuously improve your live models. +- Leverage existing **knowledge bases** and better handle the long tail of queries that **chatbots** receive. +- **Automate processes** by automatically applying a list of questions to new documents and using the extracted answers. + +![Logo](https://raw.githubusercontent.com/deepset-ai/haystack/main/docs/img/logo.png) + + +## Core Features + +- **Latest models**: Utilize all latest transformer based models (e.g. BERT, RoBERTa, MiniLM) for extractive QA, generative QA and document retrieval. +- **Modular**: Multiple choices to fit your tech stack and use case. Pick your favorite database, file converter or modeling framework. +- **Open**: 100% compatible with HuggingFace's model hub. Tight interfaces to other frameworks (e.g. Transformers, FARM, sentence-transformers) +- **Scalable**: Scale to millions of docs via retrievers, production-ready backends like Elasticsearch / FAISS and a fastAPI REST API +- **End-to-End**: All tooling in one place: file conversion, cleaning, splitting, training, eval, inference, labeling ... +- **Developer friendly**: Easy to debug, extend and modify. +- **Customizable**: Fine-tune models to your own domain or implement your custom DocumentStore. +- **Continuous Learning**: Collect new training data via user feedback in production & improve your models continuously + +| | | +|-|-| +| :ledger: [Docs](https://haystack.deepset.ai/overview/intro) | Usage, Guides, API documentation ...| +| :beginner: [Quick Demo](https://github.com/deepset-ai/haystack/#quick-demo) | Quickly see what Haystack offers | +| :floppy_disk: [Installation](https://github.com/deepset-ai/haystack/#installation) | How to install Haystack | +| :art: [Key Components](https://github.com/deepset-ai/haystack/#key-components) | Overview of core concepts | +| :mortar_board: [Tutorials](https://github.com/deepset-ai/haystack/#tutorials) | Jupyter/Colab Notebooks & Scripts | +| :eyes: [How to use Haystack](https://github.com/deepset-ai/haystack/#how-to-use-haystack) | Basic explanation of concepts, options and usage | +| :heart: [Contributing](https://github.com/deepset-ai/haystack/#heart-contributing) | We welcome all contributions! | +| :bar_chart: [Benchmarks](https://haystack.deepset.ai/benchmarks/v0.9.0) | Speed & Accuracy of Retriever, Readers and DocumentStores | +| :telescope: [Roadmap](https://haystack.deepset.ai/overview/roadmap) | Public roadmap of Haystack | +| :pray: [Slack](https://haystack.deepset.ai/community/join) | Join our community on Slack | +| :bird: [Twitter](https://twitter.com/deepset_ai) | Follow us on Twitter for news and updates | +| :newspaper: [Blog](https://medium.com/deepset-ai) | Read our articles on Medium | + + +## Quick Demo + +The quickest way to see what Haystack offers is to start a [Docker Compose](https://docs.docker.com/compose/) demo application: + +**1. Update/install Docker and Docker Compose, then launch Docker** + +``` + # apt-get update && apt-get install docker && apt-get install docker-compose + # service docker start +``` + +**2. Clone Haystack repository** + +``` + # git clone https://github.com/deepset-ai/haystack.git +``` + +### 2nd level headline for testing purposes +#### 3rd level headline for testing purposes diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/pdf/sample_pdf_1.pdf b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/pdf/sample_pdf_1.pdf new file mode 100644 index 0000000000000000000000000000000000000000..87259b897f83b462f521276bf32d210ea008bcd3 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/pdf/sample_pdf_1.pdf differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/pdf/sample_pdf_2.pdf b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/pdf/sample_pdf_2.pdf new file mode 100644 index 0000000000000000000000000000000000000000..6384246e891c59abf174e7225ed7f793e814ed69 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/pdf/sample_pdf_2.pdf differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/pdf/sample_pdf_3.pdf b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/pdf/sample_pdf_3.pdf new file mode 100644 index 0000000000000000000000000000000000000000..c0d07eaa688f0d605a30580f8ca1b3d06d4b66a6 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/pdf/sample_pdf_3.pdf differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/txt/doc_1.txt b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/txt/doc_1.txt new file mode 100644 index 0000000000000000000000000000000000000000..4121890801fc8399d578d39fc430fa3b3cb669c6 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/txt/doc_1.txt @@ -0,0 +1,2 @@ +Some text for testing. +Two lines in here. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/txt/doc_2.txt b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/txt/doc_2.txt new file mode 100644 index 0000000000000000000000000000000000000000..6f950eedcf4a422689b5b79bf5578944a0bb683b --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/txt/doc_2.txt @@ -0,0 +1,3 @@ +This is a test line. +123 456 789 +987 654 321. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/txt/doc_3.txt b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/txt/doc_3.txt new file mode 100644 index 0000000000000000000000000000000000000000..a7c4fd5e55891a992046c64a34cce6a2f5fadf18 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/txt/doc_3.txt @@ -0,0 +1,11 @@ +That's yet another file! + +it contains + + + + +many + + +empty lines. diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/yaml/openapi_greeting_service.yml b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/yaml/openapi_greeting_service.yml new file mode 100644 index 0000000000000000000000000000000000000000..6a25fc9880e47fc6ffc22bd7ee9858be891bc5b6 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/yaml/openapi_greeting_service.yml @@ -0,0 +1,65 @@ +{ + "openapi": "3.0.0", + "info": { + "title": "Simple Greeting Service", + "version": "1.0.0", + "description": "API for performing greetings" + }, + "servers": [ + { + "url": "http://localhost:8080" + } + ], + "paths": { + "/greet/{name}": { + "post": { + "operationId": "greet", + "summary": "Greet a person with a message (Mixed params and body)", + "parameters": [ + { + "in": "path", + "name": "name", + "required": true, + "schema": { + "type": "string" + }, + "description": "Name of the person to greet" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "message": { + "type": "string", + "description": "Custom message to send" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Greeting delivered", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "greeting": { + "type": "string" + } + } + } + } + } + } + } + } + } + } +} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/yaml/test_pipeline.yaml b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/yaml/test_pipeline.yaml new file mode 100644 index 0000000000000000000000000000000000000000..945ef018ae60ec01cb2cd2ea5d83c2fe5e957ad0 --- /dev/null +++ b/SPFsmartGATE/LIVE/TMP/haystack/test/test_files/yaml/test_pipeline.yaml @@ -0,0 +1,14 @@ +components: + Comp1: + init_parameters: + an_init_param: null + type: test.core.pipeline.test_pipeline.FakeComponent + Comp2: + init_parameters: + an_init_param: null + type: test.core.pipeline.test_pipeline.FakeComponent +connections: +- receiver: Comp2.input_ + sender: Comp1.value +max_runs_per_component: 99 +metadata: {} diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/tracing/__pycache__/__init__.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/test/tracing/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45001aeebad4b7aed1ef43404dc7709c4da71b88 Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/test/tracing/__pycache__/__init__.cpython-312.pyc differ diff --git a/SPFsmartGATE/LIVE/TMP/haystack/test/tracing/__pycache__/utils.cpython-312.pyc b/SPFsmartGATE/LIVE/TMP/haystack/test/tracing/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e9b32f0c85851b44299a3a40ced19bc42063ecf Binary files /dev/null and b/SPFsmartGATE/LIVE/TMP/haystack/test/tracing/__pycache__/utils.cpython-312.pyc differ