JosephStoneCellAI commited on
Commit
9654935
·
verified ·
1 Parent(s): 11b5bb0

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/2170-pydantic-dataclasses.md +80 -0
  2. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3550-csv-converter.md +86 -0
  3. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3558-embedding_retriever.md +131 -0
  4. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3665-prompt-node.md +445 -0
  5. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3695-demo-repository.md +77 -0
  6. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3784-shaper.md +272 -0
  7. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3875-table-cell.md +238 -0
  8. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3925-mrkl-agent.md +380 -0
  9. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3959-json-converter.md +142 -0
  10. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4084-agent-demo.md +262 -0
  11. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4172-shaper-in-prompt-template.md +185 -0
  12. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4284-drop-basecomponent.md +950 -0
  13. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4370-documentstores-and-retrievers.md +239 -0
  14. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5289-recentness-ranker.md +185 -0
  15. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5390-embedders.md +249 -0
  16. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5540-llm-support-2.0.md +253 -0
  17. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5738-document-2.0.md +108 -0
  18. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5794-evaluation-haystack-2.md +227 -0
  19. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5794-evaluation-haystack-2.py +141 -0
  20. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6001-document-store-filter-rework.md +183 -0
  21. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6141-meta-field-ranker.md +68 -0
  22. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6784-integrations-for-eval-framworks.md +151 -0
  23. SPFsmartGATE/LIVE/TMP/haystack/proposals/text/7462-rag-evaluation.md +223 -0
  24. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-TEI-embedders-8c76593bc25a7219.yaml +28 -0
  25. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-answerbuilder-2.0-5dd255eeba68041f.yaml +4 -0
  26. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-apple-silicon-gpu-acceleration-38bf69781a933b95.yaml +4 -0
  27. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-apply_filter_policy-function-ae3152e6afe0ca57.yaml +4 -0
  28. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure-kwargs-6a5ab1358ef7f44c.yaml +6 -0
  29. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure_ocr_doc_converter-935130b3b243d236.yaml +4 -0
  30. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-batch_size_faiss_init-5e97c1fb9409f873.yaml +5 -0
  31. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-blob-type-2a9476a39841f54d.yaml +5 -0
  32. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-branch-joiner-037298459ca74077.yaml +14 -0
  33. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-calculate-metrics-metricsresults-03bf27ce8b16cff5.yaml +6 -0
  34. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-custom-filters-to-conditional-router-631eba8bab3c2ae7.yaml +6 -0
  35. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-default-value-to-input-socket-2e62116fc4be5214.yaml +5 -0
  36. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-document-writer-number-of-documents-written-2c57f3a5d6ae2131.yaml +4 -0
  37. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-dynamic-prompt-builder-e61c4b11405b8d80.yaml +5 -0
  38. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-exact-match-a7df21717238b771.yaml +8 -0
  39. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-f1-d54cc900bec753f7.yaml +8 -0
  40. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-huggingface-tgi-generator-9d7eed86f5246ea9.yaml +5 -0
  41. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-indexing-ready-made-pipeline-85c1da2f8f910f9d.yaml +4 -0
  42. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-keep-id-to-document-cleaner-2a9854b5f195bb78.yaml +4 -0
  43. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-link-content-fetcher-145915976f38e1e0.yaml +5 -0
  44. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-lost-in-the-middle-ranker-6ad7dda754fad5a9.yaml +18 -0
  45. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-lost-in-the-middle-ranker-976f2e9bf83c3c68.yaml +8 -0
  46. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-markdown-file-type-router-support-39a607faa5c1436f.yaml +4 -0
  47. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-metadata-HTMLToDocument-42dbd074a46c979e.yaml +4 -0
  48. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-metadata_router-2.0-63829ac5a0528e9d.yaml +4 -0
  49. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-min-top-k-top-p-sampler-dc65f97d420e70b0.yaml +4 -0
  50. SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-mrr-metric-362527e55e21c24c.yaml +5 -0
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/2170-pydantic-dataclasses.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--
2
+ NOTE: this document was imported from a different process and is not compliant with the proposal template. Do not
3
+ use it as a reference for new proposals.
4
+ -->
5
+ - Start Date: 2021-10-14
6
+ - Proposal PR: n/a
7
+ - Github Issue: https://github.com/deepset-ai/haystack/pull/1598
8
+ - Deciders: @tholor
9
+
10
+
11
+ ## Context and Problem Statement
12
+
13
+ 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.
14
+
15
+ ## Decision Drivers
16
+
17
+ * The Swagger autogenerated documentation for REST API in FastAPI was broken where the dataclasses include non-standard fields (`pd.dataframe` + `np.ndarray`)
18
+
19
+ ## Considered Options
20
+
21
+ * Switch to Pydantic `dataclasses` in our codebase as well.
22
+ * Staying with vanilla `dataclasses` and find a workaround for FastAPI to accept them in place of Pydantic's implementation.
23
+
24
+ ## Decision Outcome
25
+
26
+ Chosen option: **1**, because our initial concerns about speed proved negligible and Pydantic's implementation provided some additional functionality for free (see below).
27
+
28
+ ### Positive Consequences
29
+
30
+ * We can now inherit directly from the primitives in the REST API dataclasses, and overwrite the problematic fields with standard types.
31
+ * We now get runtime type checks "for free", as this is a core feature of Pydantic's implementation.
32
+
33
+ ### Negative Consequences
34
+
35
+ * Pydantic dataclasses are slower. See https://github.com/deepset-ai/haystack/pull/1598 for a rough performance assessment.
36
+ * 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:
37
+
38
+ ```python
39
+ if typing.TYPE_CHECKING:
40
+ from dataclasses import dataclass
41
+ else:
42
+ from pydantic.dataclasses import dataclass
43
+ ```
44
+
45
+ ## Pros and Cons of the Options
46
+
47
+ ### Switch to Pydantic `dataclasses`
48
+
49
+ * Good, because it solves the issue without having to find workarounds for FastAPI.
50
+ * Good, because it adds type checks at runtime.
51
+ * Bad, because mypy and autocomplete tools need assistance to parse its dataclasses properly. Example:
52
+
53
+ ```python
54
+ if typing.TYPE_CHECKING:
55
+ from dataclasses import dataclass
56
+ else:
57
+ from pydantic.dataclasses import dataclass
58
+ ```
59
+
60
+ * Bad, because it introduces an additional dependency to Haystack (negligible)
61
+ * Bad, because it adds some overhead on the creation of primitives (negligible)
62
+
63
+ ### Staying with vanilla `dataclasses`
64
+
65
+ * Good, because it's Python's standard way to generate data classes
66
+ * Good, because mypy can deal with them without plugins or other tricks.
67
+ * Good, because it's faster than Pydantic's implementation.
68
+ * Bad, because does not play well with FastAPI and Swagger (critical).
69
+ * Bad, because it has no validation at runtime (negligible)
70
+
71
+ ## Links <!-- optional -->
72
+
73
+ * https://pydantic-docs.helpmanual.io/usage/dataclasses/
74
+ * https://github.com/deepset-ai/haystack/pull/1598
75
+ * https://github.com/deepset-ai/haystack/issues/1593
76
+ * https://github.com/deepset-ai/haystack/issues/1582
77
+ * https://github.com/deepset-ai/haystack/pull/1398
78
+ * https://github.com/deepset-ai/haystack/issues/1232
79
+
80
+ <!-- markdownlint-disable-file MD013 -->
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3550-csv-converter.md ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Start Date: 2022-11-28
2
+ - Proposal PR: [#3638](https://github.com/deepset-ai/haystack/issues/3638)
3
+ - Github Issue: [#3550](https://github.com/deepset-ai/haystack/issues/3550)
4
+
5
+ # Summary
6
+
7
+ Using Haystack for questions answering pipelines is prettier easy, but most of the time users have CSV files containing
8
+ their knowledge base with questions and there associated answers.
9
+ Unfortunately there is no easy way to dynamically update the knowledge base or import new data from CSV though rest API
10
+ using YAML, as there are no CSV parser.
11
+
12
+ Having a basic way to dynamically index a CSV file always requires development of a new nodes.
13
+
14
+ # Basic example
15
+
16
+ To define an FAQ query and **indexing** pipeline we would then simply do :
17
+ ```yaml
18
+ # To allow your IDE to autocomplete and validate your YAML pipelines, name them as <name of your choice>.haystack-pipeline.yml
19
+
20
+ version: ignore
21
+
22
+ components: # define all the building-blocks for Pipeline
23
+ - name: DocumentStore
24
+ type: ElasticsearchDocumentStore
25
+ params:
26
+ host: localhost
27
+ embedding_field: question_emb
28
+ embedding_dim: 384
29
+ excluded_meta_data:
30
+ - question_emb
31
+ similarity: cosine
32
+ - name: Retriever
33
+ type: EmbeddingRetriever
34
+ params:
35
+ document_store: DocumentStore # params can reference other components defined in the YAML
36
+ embedding_model: sentence-transformers/all-MiniLM-L6-v2
37
+ scale_score: False
38
+ - name: CSVConverter
39
+ type: CsvTextConverter
40
+
41
+ pipelines:
42
+ - name: indexing
43
+ nodes:
44
+ - name: CSVConverter
45
+ inputs: [File]
46
+ - name: Retriever
47
+ inputs: [ CSVConverter ]
48
+ - name: DocumentStore
49
+ inputs: [ Retriever ]
50
+ ```
51
+
52
+ # Motivation
53
+
54
+ Using YAML pipeline description it's not possible to describe a CSV FAQ indexing pipeline that takes CSV files as input
55
+ containing questions and answers and index them. It's a basic usage that still requires coding.
56
+
57
+ As we are presenting a tutorial `Utilizing Existing FAQs for Question Answering` it would be great to have this basic
58
+ node so that anyone can quickly run an FAQ Question Answering pipeline using only a YAML description and import their
59
+ CSV though REST API.
60
+
61
+ # Detailed design
62
+
63
+ I've added a new node: **`CsvTextConverter`** . It takes a file input, parse it as FAQ CSV file having `question` and `answer` column
64
+ and outputs `Document`s.
65
+
66
+ For now the node is very simple: can only handle a fixed CSV format and no other tabular data. It also
67
+ can't produce documents that are not of type `text`. These shortcomings can be addressed in later enhancements.
68
+
69
+ # Drawbacks
70
+
71
+ We could consider that developing this custom node is easy and a good way to learn Haystack,
72
+ but casual users shouldn't need to know this much before being able to index CSV files.
73
+
74
+ # Alternatives
75
+
76
+ Didn't consider any other design.
77
+
78
+ # Adoption strategy
79
+
80
+ It doesn't introduce any breaking change, any users having FAQs pipeline would be able to use the official nodes instead
81
+ of their existing ones.
82
+
83
+ # How we teach this
84
+
85
+ This may require updating this tutorial [Utilizing Existing FAQs for Question Answering](https://haystack.deepset.ai/tutorials/04_faq_style_qa)
86
+ and to document those 2 nodes.
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3558-embedding_retriever.md ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Start Date: 2022-11-11
2
+ - Proposal PR: https://github.com/deepset-ai/haystack/pull/3558
3
+ - Github Issue:
4
+
5
+ > ⚠️ Superseded by https://github.com/deepset-ai/haystack/blob/main/proposals/text/5390-embedders.md
6
+
7
+ # Summary
8
+
9
+ - Current EmbeddingRetriever doesn't allow Haystack users to provide new embedding methods and is
10
+ currently constricted to farm, transformers, sentence transformers, OpenAI and Cohere based
11
+ embedding approaches. Any new encoding methods need to be explicitly added to Haystack
12
+ and registered with the EmbeddingRetriever.
13
+
14
+
15
+ - We should allow users to easily plug-in new embedding methods to EmbeddingRetriever. For example, a Haystack user should be able to
16
+ add custom embeddings without having to commit additional code to Haystack repository.
17
+
18
+ # Basic example
19
+ EmbeddingRetriever is instantiated with:
20
+
21
+ ``` python
22
+ retriever = EmbeddingRetriever(
23
+ document_store=document_store,
24
+ embedding_model="sentence-transformers/multi-qa-mpnet-base-dot-v1",
25
+ model_format="sentence_transformers",
26
+ )
27
+ ```
28
+ - The current approach doesn't provide a pluggable abstraction point of composition but
29
+ rather attempts to satisfy various embedding methodologies by having a lot of
30
+ parameters which keep ever expanding.
31
+
32
+
33
+ - The new approach allows creation of the underlying embedding mechanism (EmbeddingEncoder)
34
+ which is then in turn plugged into EmbeddingRetriever. For example:
35
+
36
+ ``` python
37
+ encoder = SomeNewFancyEmbeddingEncoder(api_key="asdfklklja",
38
+ query_model="text-search-query",
39
+ doc_model="text-search-doc")
40
+ ```
41
+
42
+ - EmbeddingEncoder is then used for the creation of EmbeddingRetriever. EmbeddingRetriever
43
+ init method doesn't get polluted with additional parameters as all of the peculiarities
44
+ of a particular encoder methodology are contained on in its abstraction layer.
45
+
46
+ ``` python
47
+ retriever = EmbeddingRetriever(
48
+ document_store=document_store,
49
+ encoder=encoder
50
+ )
51
+ ```
52
+
53
+ # Motivation
54
+
55
+ - Why are we doing this? What use cases does it support? What is the expected outcome?
56
+
57
+ We could certainly keep the current solution as is; it does implement a decent level
58
+ of composition/decoration to lower coupling between EmbeddingRetriever and the underlying
59
+ mechanism of embedding (sentence transformers, OpenAI, etc). However, the current mechanism
60
+ in place basically hard-codes available embedding implementations and prevents our users from
61
+ adding new embedding mechanism by themselves outside of Haystack repository. We also might
62
+ want to have a non-public dC embedding mechanism in the future. In the current design a non-public
63
+ dC embedding mechanism would be impractical. In addition, the more underlying implementations we
64
+ add we'll continue to "pollute" EmbeddingRetriever init method with more and more parameters.
65
+ This is certainly less than ideal long term.
66
+
67
+
68
+ - EmbeddingEncoder classes should be subclasses of BaseComponent! As subclasses of BaseComponent,
69
+ we can use them outside the EmbeddingRetriever context in indexing pipelines, generating the
70
+ embeddings. We are currently employing a kludge of using Retrievers which is quite counter-intuitive
71
+ and confusing for our users.
72
+
73
+
74
+ - EmbeddingEncoder classes might sound overly complicated, especially with a distinguishing mechanism
75
+ name pre-appended (i.e CohereEmbeddingEncoder). Therefore, we'll adopt <specific>Embedder
76
+ naming scheme, i.e. CohereEmbedder, SentenceTransformerEmbedder and so on.
77
+
78
+ # Detailed design
79
+
80
+ - Our new EmbeddingRetriever would still wrap the underlying encoding mechanism in the form of
81
+ _BaseEmbedder. _BaseEmbedder still needs to implement methods:
82
+ - embed_queries
83
+ - embed_documents
84
+
85
+
86
+ - The new design approach differs is in the creation of EmbeddingRetriever - rather than hiding the underlying encoding
87
+ mechanism one could simply create the EmbeddingRetriever with a specific encoder directly. For example:
88
+
89
+ ```
90
+ retriever = EmbeddingRetriever(
91
+ document_store=document_store,
92
+ encoder=OpenAIEmbedder(api_key="asdfklklja", model="ada"),
93
+ #additional EmbeddingRetriever-abstraction-level parameters
94
+ )
95
+ ```
96
+
97
+ - If the "two-step approach" of EmbeddingRetriever initialization is no longer the ideal solution (issues with current
98
+ schema generation and loading/saving via YAML pipelines) we might simply add the EmbeddingRetriever
99
+ class for every supported encoding approach. For example, we could have OpenAIEmbeddingRetriever, CohereEmbeddingRetriever,
100
+ SentenceTransformerEmbeddingRetriever and so on. Each of these retrievers will delegate the bulk of the work to an
101
+ existing EmbeddingRetriever with a per-class-specific Embedder set in the class constructor (for that custom
102
+ encoding part). We'll get the best of both worlds. Each <Specific>EmeddingRetriever will have only the relevant primitives
103
+ parameters for the **init()** constructor; the underlying EmbeddingRetriever attribute in <Specific>EmeddingRetriever
104
+ will handle most of the business logic of retrieving, yet each retriever will use an appropriate per-class-specific
105
+ Embedder for the custom encoding part.
106
+
107
+
108
+
109
+ # Drawbacks
110
+ - The main shortcoming are:
111
+ - The "two-step approach" in EmbeddingRetriever initialization
112
+ - Likely be an issue for the current schema generation and loading/saving via YAML pipelines (see solution above)
113
+ - It is a API breaking change so it'll require code update for all EmbeddingRetriever usage both in our codebase and for Haystack users
114
+ - Can only be done in major release along with other breaking changes
115
+
116
+ # Alternatives
117
+
118
+ We could certainly keep everything as is :-)
119
+
120
+ # Adoption strategy
121
+ - As it is a breaking change, we should implement it for the next major release.
122
+
123
+ # How do we teach this?
124
+ - This change would require only a minor change in documentation.
125
+ - The concept of embedding retriever remains, just the mechanics are slightly changed
126
+ - All docs and tutorials need to be updated
127
+ - Haystack users are informed about a possibility to create and use their own embedders for embedding retriever.
128
+ - # Unresolved questions
129
+
130
+ Optional, but suggested for first drafts. What parts of the design are still
131
+ TBD?
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3665-prompt-node.md ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Start Date: 2022-12-04
2
+ - Proposal PR: https://github.com/deepset-ai/haystack/pull/3665
3
+ - Github Issue: https://github.com/deepset-ai/haystack/issues/3306
4
+ - Example Colab notebook: https://colab.research.google.com/drive/1bOIxb8cnpTrpMtTSBArY9FJlL59Ar4K_?usp=sharing
5
+
6
+ # Summary
7
+
8
+ - The PromptNode class is the central abstraction in Haystack's large language model (LLM) support.
9
+ Such a component supports multiple NLP tasks out-of-the-box. PromptNode allows users to
10
+ perform multiple tasks, such as summarization, question answering, question generation etc. using a single,
11
+ unified model within the Haystack framework.
12
+
13
+
14
+ - One of the benefits of PromptNode is that it allows users to define and add additional tasks
15
+ that are supported by the model. This can enable users to extend the capabilities of the model and
16
+ to use it for a wider range of NLP tasks within the Haystack ecosystem.
17
+
18
+
19
+ # Basic example
20
+
21
+ PromptNode is instantiated with the underlying LLM model and prompted by using natural language:
22
+
23
+ ``` python
24
+ from haystack.nodes.llm import PromptNode
25
+ pn = PromptNode(model_name_or_path="google/flan-t5-base")
26
+ pn("What is the capital of Germany?")
27
+
28
+ ----------------------------------------------------------------------------
29
+ ['berlin']
30
+ ```
31
+
32
+ # Motivation
33
+
34
+
35
+ - The use of large language models (LLMs) has become increasingly popular in natural language
36
+ processing (NLP) due to their ability to capture complex and nuanced patterns in language.
37
+ PromptNode allows users to leverage the power of LLMs in the Haystack ecosystem, and
38
+ to perform multiple NLP tasks using a single, unified model. This provides a flexible and efficient
39
+ tool for NLP in Haystack, and can enable users to improve the performance and reliability of their applications.
40
+
41
+
42
+ - Modern LLM support hundreds if not thousands of tasks. Aside from PromptNode we'll define prompt templates for
43
+ dozen or so most popular NLP tasks and allow users to register prompt templates for additional tasks. The
44
+ extensible and modular approach would allow users to extend the capabilities of the model and to use
45
+ it for a wider range of NLP tasks within the Haystack ecosystem. Prompt engineers would define templates
46
+ for each NLP task and register them with the PromptNode. The burden of defining the best templates for each task
47
+ would be on the prompt engineers and not on the users.
48
+
49
+
50
+ - The use of templates to define NLP tasks can make it easier for users to use PromptNode, as
51
+ they do not need to know the details of how the model works or how to define tasks for it. This can
52
+ reduce the learning curve and make it easier for users to get started with PromptNode and
53
+ to leverage the power of LLMs in Haystack.
54
+
55
+
56
+ - The extensible and modular approach of PromptNode allows users to easily add support for
57
+ additional templates, even on-the-fly, which can enable them to extend the capabilities of the model and to use it for
58
+ a wider range of NLP tasks. This can provide users with more flexibility and control over the model,
59
+ and can enable them to tailor it to their specific needs and applications.
60
+
61
+ # Detailed design
62
+
63
+ - The PromptNode class is the most important abstraction in Haystack's large language model (LLM) support.
64
+ In addition to PromptNode class, we'll also define a set of prompt templates for the most popular NLP tasks.
65
+
66
+
67
+ - NLP prompt templates will be represented by `PromptTemplate` class.
68
+
69
+ ``` python
70
+ class PromptTemplate(BaseTemplate):
71
+
72
+ name: str
73
+ prompt_text: str
74
+ input_variables: List[str]
75
+
76
+ ````
77
+
78
+ PromptNode would, out-of-the-box, support 10-20 default NLP tasks defined by PromptTemplate instances. However, it would
79
+ allow registering additional templates with PromptNode.
80
+
81
+
82
+ - The prompt templates for default tasks (question-answering,question-generation, summarization etc.) could be examined by the user
83
+ using `get_prompt_templates_names` class method of the PromptNode. For example:
84
+
85
+ ``` python
86
+ from haystack.nodes.llm import PromptNode
87
+ PromptNode.get_prompt_templates_names()
88
+
89
+ ----------------------------------------------------------------------------
90
+ ['question-answering',
91
+ 'question-generation',
92
+ 'conditioned-question-generation',
93
+ 'summarization',
94
+ 'question-answering-check']
95
+ ```
96
+
97
+
98
+ - PromptNode supports natural language prompting (using `prompt` method) by specifying prompt template method parameter. For example:
99
+
100
+ ``` python
101
+ from haystack.nodes.llm import PromptNode
102
+ pn = PromptNode(model_name_or_path="google/flan-t5-base")
103
+ pn.prompt("question-generation", documents=["Berlin is the capital of Germany."])
104
+
105
+ ----------------------------------------------------------------------------
106
+ ['What is the capital of Germany?']
107
+ ```
108
+
109
+ - PromptNode supports selecting a particular default template for a certain task (e.g. question-generation) and then subsequently
110
+ using the selected template until user changes the current template. For example:
111
+
112
+ ``` python
113
+ qa = pn.use_prompt_template("deepset/question-generation-v2")
114
+ qa(documents=["Berlin is the capital of Germany."])
115
+
116
+ ----------------------------------------------------------------------------
117
+ ['What is the capital of Germany?']
118
+ ```
119
+
120
+ - The addition of new prompt templates is supported by the `add_prompt_template` method. For example:
121
+
122
+ ``` python
123
+ from haystack.nodes.llm import PromptNode
124
+ PromptNode.add_prompt_template(PromptTemplate(name="sentiment-analysis",
125
+ prompt_text="Please give a sentiment for this context. Answer with positive, "
126
+ "negative or neutral. Context: $documents; Answer:",
127
+ input_variables=["documents"]))
128
+ PromptNode.get_prompt_templates_names()
129
+
130
+ ----------------------------------------------------------------------------
131
+ ['question-answering',
132
+ 'question-generation',
133
+ 'conditioned-question-generation',
134
+ 'summarization',
135
+ 'question-answering-check',
136
+ 'sentiment-analysis']
137
+ ```
138
+
139
+ - Users can inspect registered prompt templates with two class methods: `get_prompt_templates_names` and `get_prompt_templates`. The first
140
+ method, as we have seen, simply lists the names of the supported templates while the second method returns the list of `PromptTemplate`
141
+ instances, in readable format, allowing users to inspect the actual prompt template used and the templates input parameters.
142
+
143
+ ``` python
144
+ from haystack.nodes.llm import PromptNode
145
+ PromptNode.get_prompt_templates()
146
+
147
+ ----------------------------------------------------------------------------
148
+ [PromptTemplate(name="sentiment-analysis",
149
+ prompt_text="Please give a sentiment for this context. Answer with positive, "
150
+ "negative or neutral. Context: $documents; Answer:",
151
+ input_variables=["documents"], ...]
152
+ ```
153
+
154
+
155
+
156
+ - However, aside from existing templates, users should also be able to use "on-the-fly" templates without registering them first. For example:
157
+
158
+ ``` python
159
+ from haystack.nodes.llm import PromptNode
160
+ pn = PromptNode(model_name_or_path="google/flan-t5-base")
161
+ prompt_template = PromptTemplate(name="sentiment-analysis",
162
+ prompt_text="Please give a sentiment for this context. "
163
+ "Answer with positive, negative or neutral. Context: $documents; Answer:",
164
+ input_variables=["documents"])
165
+ pn.prompt(prompt_template, documents=["I really enjoyed the recent movie."])
166
+
167
+ ----------------------------------------------------------------------------
168
+ ['positive']
169
+ ```
170
+ This, "on-the-fly" approach might be handy if users want to simply try stuff out
171
+
172
+
173
+ - Therefore, the most central API method of the PromptNode class would be the `prompt` method with the following signature:
174
+ ``` python
175
+ def prompt(self, prompt_template: Union[str, PromptTemplate] = None, *args, **kwargs) -> List[str]:
176
+ ```
177
+
178
+
179
+ - PromptNode class `__init__` constructor, aside from the `model_name_or_path` parameter would also have a
180
+ `prompt_template` parameter which would serve as the current and default template of the PromptNode.
181
+
182
+ - ``` python
183
+ def __init__(self, model_name_or_path: str = "google/flan-t5-base", prompt_template: Union[str, PromptTemplate] = None):
184
+ ```
185
+
186
+ If the `prompt_template` is not specified in the `PromptNode` init method then user is required to specify the
187
+ template in the prompt method:
188
+
189
+ ``` python
190
+ from haystack.nodes.llm import PromptNode
191
+ pn = PromptNode(model_name_or_path="google/flan-t5-base")
192
+ pn.prompt("question-generation", documents=["Berlin is the capital of Germany."])
193
+
194
+ ----------------------------------------------------------------------------
195
+ ['What is the capital of Germany?']
196
+ ```
197
+
198
+ Otherwise, when the `PromptNode` is initialized with a prompt template user can invoke the `PromptNode` directly
199
+
200
+ ``` python
201
+ from haystack.nodes.llm import PromptNode
202
+ pn = PromptNode(model_name_or_path="google/flan-t5-base", prompt_template="question-generation")
203
+ pn(documents=["Berlin is the capital of Germany."])
204
+
205
+ ----------------------------------------------------------------------------
206
+ ['What is the capital of Germany?']
207
+ ```
208
+
209
+ - Template parameters verification
210
+
211
+ All template input parameters will be verified to match the template definition and the corresponding runtime
212
+ parameters for the input variables will be checked for type and value. For example:
213
+
214
+ ``` python
215
+ from haystack.nodes.llm import PromptNode
216
+ on = PromptNode(model_name_or_path="google/flan-t5-base")
217
+ on.prompt("question-generation", some_unknown_param=["Berlin is the capital of Germany."])
218
+
219
+ ----------------------------------------------------------------------------
220
+ ValueError Traceback (most recent call last)
221
+ <ipython-input-16-369cca52e960> in <module>
222
+ 1 # tasks parameters are checked
223
+ ----> 2 sa(some_param=[Document("Berlin is the capital of Germany.")])
224
+
225
+ 2 frames
226
+ /usr/local/lib/python3.8/dist-packages/haystack/nodes/llm/multi_task.py in __call__(self, *args, **kwargs)
227
+ 34 if set(template_dict.keys()) != set(self.input_variables):
228
+ 35 available_params = set(list(template_dict.keys()) + list(set(kwargs.keys())))
229
+ ---> 36 raise ValueError(f"Expected prompt params {self.input_variables} but got {list(available_params)}")
230
+ 37
231
+ 38 template_dict["prompt_template"] = self.prompt_text
232
+
233
+ ValueError: Expected prompt params ['documents'] but got ['some_unknown_param']
234
+ ```
235
+
236
+ - Pipelines
237
+
238
+ Even though we can use PromptNode directly its real power lies in using pipelines and Haystack. For example, we
239
+ can retrieve documents from the document store using the query and then inject the retrieved documents into documents
240
+ as a parameter to the selected PromptNode template. For example:
241
+
242
+ ``` python
243
+ from haystack.pipelines import PromptNode
244
+ top_k = 3
245
+ query = "Who are the parents of Arya Stark?"
246
+ retriever = EmbeddingRetriever(...)
247
+ pn = PromptNode(model_name_or_path="google/flan-t5-base", prompt_template="question-answering")
248
+
249
+ pipe = Pipeline()
250
+ pipe.add_node(component=retriever, name="Retriever", inputs=["Query"])
251
+ pipe.add_node(component=pn, name="prompt_node", inputs=["Retriever"])
252
+
253
+ output = pipe.run(query=query,
254
+ params={"Retriever": {"top_k": top_k}},
255
+ questions=[query for n in range(0, top_k)],
256
+ #documents parameter we need for this task will be automatically populated by the retriever
257
+ )
258
+
259
+ output["results"]
260
+ ```
261
+
262
+ - However, we are still not utilizing the full power of Haystack pipelines. What if we could use more than
263
+ one PromptNode in the pipeline? Perhaps we could first retrieve documents from the retriever, pass it
264
+ to first PromptNode that will generate questions from these documents, and then add a
265
+ second PromptNode component that will answer those generated questions given the documents as the
266
+ context. Here is how we can do exactly that:
267
+
268
+ ``` python
269
+ top_k = 3
270
+ query = "Who are the parents of Arya Stark?"
271
+ retriever = EmbeddingRetriever(...)
272
+ model = PromptModel(model_name_or_path="google/flan-t5-small")
273
+
274
+ qg = PromptNode(prompt_template="question-generation", prompt_model=model, output_variable="questions")
275
+ qa = PromptNode(prompt_template="question-answering", prompt_model=model)
276
+
277
+ pipe = Pipeline()
278
+ pipe.add_node(component=retriever, name="Retriever", inputs=["Query"])
279
+ pipe.add_node(component=qg, name="qg", inputs=["Retriever"])
280
+ pipe.add_node(component=qa, name="qa", inputs=["qg"])
281
+
282
+ result = pipe.run(query=query)
283
+
284
+ print(result["results"])
285
+
286
+ ```
287
+
288
+ The above example shows how we can use PromptNode in a pipeline and how we can bind the results of one
289
+ PromptNode to the input of another PromptNode. The `output_variable` parameter used in the constructor of the
290
+ question answering node, and assigned value `questions` indicates that variable `questions` could be resolved by any
291
+ downstream pipeline node. In this particular case, the output of the question generation node will be passed to downstream
292
+ nodes, and answering node will use that `questions` variable to inject its stored value into the `questions` parameter of
293
+ the question answering template.
294
+
295
+ A careful reader of this proposal will also notice that we are using the same PromptModel instance for both PromptNodes.
296
+ This is done mainly for reuse as the PromptModel instance could be a locally run LLM and we don't want to load it
297
+ multiple times.
298
+
299
+ As LLMs are very resource intensive we can also envision a scenario where we would like to use a remote LLM service.
300
+ In such cases we can use multiple instances of a PromptNode in a pipeline directly thus bypassing PromptModel altogether.
301
+
302
+
303
+ - Pipeline YAML config file
304
+
305
+ Let's recreate the above pipeline using a YAML config file and a declarative way of defining a pipeline.
306
+
307
+ ```yaml
308
+
309
+ components:
310
+
311
+ # can go in pipeline
312
+ - name: prompt_node
313
+ params:
314
+ prompt_template: template
315
+ model_name_or_path: model
316
+ output_variable: "questions"
317
+ type: PromptNode
318
+
319
+ # can go in pipeline
320
+ - name: prompt_node_2
321
+ params:
322
+ prompt_template: "question-answering"
323
+ model_name_or_path: deepset/model-name
324
+ type: PromptNode
325
+
326
+ # not in pipeline - only needed if you're reusing the model across multiple PromptNode in a pipeline
327
+ # and hidden from users in the Python beginner world
328
+ - name: model
329
+ params:
330
+ model_name_or_path: google/flan-t5-xl
331
+ type: PromptModel
332
+
333
+ # not in pipeline
334
+ - name: template
335
+ params:
336
+ name: "question-generation-v2"
337
+ prompt_text: "Given the following $documents, please generate a question. Question:"
338
+ input_variables: documents
339
+ type: PromptTemplate
340
+
341
+ pipelines:
342
+ - name: question-generation-answering-pipeline
343
+ nodes:
344
+ - name: EmbeddingRetriever
345
+ inputs: [Query]
346
+ - name: prompt_node
347
+ inputs: [EmbeddingRetriever]
348
+ - name: prompt_node_2
349
+ inputs: [prompt_node]
350
+ ```
351
+ First of all, notice how we reuse the resource heavy PromptModel instance across multiple PromptNode instances. And
352
+ although we could have used already registered `question-generation` prompt template, we decided to define a new one
353
+ called `question-generation-v2` and as such set it as the default template for the first PromptNode. We also defined
354
+ the output of the first PromptNode as `questions` and used that variable in the second PromptNode.
355
+
356
+ In conclusion, we can see that the YAML config file is a mirror image of the previous code centric pipeline
357
+ example and also a very powerful way of defining a pipeline.
358
+
359
+
360
+
361
+ - Default tasks/prompts to be added to PromptNode
362
+
363
+ [Muffin]:
364
+ - Summarization
365
+ - Natural Language Inference
366
+ - Multiple-Choice QA
367
+ - Translation
368
+ - Sentiment Analysis
369
+ - Extractive QA
370
+ - Structured Data to Text
371
+ - Coreference Resolution
372
+ - Code Repair
373
+ - Code Error Generation
374
+ - Dialogue Context Generation
375
+ - Closed-Book QA
376
+ - Next Sentence Prediction
377
+ - Paraphrasing Identification
378
+ - Conversational Question Answering
379
+ - Topic Classification
380
+ - Mathematical QA
381
+ - Dialog Next Turn Prediction
382
+ - Grammatical Acceptability
383
+ - Punctuation fixing
384
+
385
+ [T0-SF]:
386
+ - Adversarial QA
387
+ - Question Generation
388
+ - Commonsense Reasoning
389
+ - Title Generation
390
+ - Dialogue Turn Prediction
391
+ - Predict Span Indices
392
+ - Context Generation
393
+
394
+ [NIV2]:
395
+ - Program Execution
396
+ - Text Matching
397
+ - Toxic Language Detection
398
+ - Cause Effect Classification
399
+ - Information Extraction
400
+ - Textual Entailment
401
+ - Wrong Candidate Generation
402
+ - Named Entity Recognition
403
+ - Commonsense Classification
404
+ - Fill-in-the-blank
405
+ - Text Completion
406
+ - Sentence Composition
407
+ - Question Understanding
408
+
409
+ [CoT Reasoning]:
410
+ - Explanation Generation
411
+ - Generate Question And Answer
412
+ - Grade School Math Word Problems
413
+ - Algebraic Question Answering
414
+ - Common Sense Reasoning Over Entities
415
+ - Common Sense Reasoning For QA
416
+ - Passage Based Question Answering
417
+ - Sense-Making And Explanation
418
+
419
+ # Drawbacks
420
+ - One potential drawback of PromptNode is that it may require a significant amount of computational resources
421
+ to use. This may limit its use in applications or environments where there are constraints on the available hardware
422
+ or software resources.
423
+
424
+
425
+ - Due to current pipeline design limitations PromptTemplate has to be a subclass of BaseComponent. This might slightly
426
+ confuse some users who are already familiar with Haystack components. We will mitigate this issue in subsequent releases
427
+ as we refactor the pipeline design. All in all, PromptTemplate will be a thin class with minimal inheritance signature from some base class.
428
+
429
+
430
+
431
+ # Alternatives
432
+
433
+ - One alternative to PromptNode is to continue to use separate models for each NLP task in Haystack. This
434
+ can enable users to tailor the model to the specific requirements of each task, and to potentially improve the
435
+ performance of the model for that task by additional fine-tuning or model adaptation via GPL. However, using separate
436
+ models may require these complex and computationally intensive training and deployment processes, and may not be as
437
+ efficient or flexible as using a single, unified model.
438
+
439
+ # Adoption strategy
440
+ - This is not a breaking change proposal and we should implement it immediately.
441
+
442
+ # How do we teach this?
443
+ - This change would require change in documentation.
444
+ - We can provide examples of how to use PromptNode in Haystack pipelines via tutorials.
445
+ - Docs and tutorials need to be updated
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3695-demo-repository.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Start Date: 2022-12-12
2
+ - Proposal PR: https://github.com/deepset-ai/haystack/pull/3695
3
+ - Github Issue: (if available, link the issue containing the original request for this change)
4
+
5
+ # Summary
6
+
7
+ A new git repository is created to host NLP applications showcasing Haystack's features.
8
+
9
+ # Basic example
10
+
11
+ A git repository was already created on Github as an example:
12
+
13
+ https://github.com/deepset-ai/haystack-demos
14
+
15
+ # Motivation
16
+
17
+ NLP applications showcasing Haystack's capabilities can be an invaluable learning resource
18
+ for its users, but at this moment we don't fully take advantage of the only one demo we have
19
+ as a documentation source.
20
+
21
+ This proposal aims at overcoming that limitation in two ways:
22
+ - Define better requirements for a demo application so that users can learn from it.
23
+ - Make it easier to add more demo applications showcasing Haystack.
24
+
25
+ # Detailed design
26
+
27
+ Every demo has a descriptive name that will be used as its identifier.
28
+
29
+ Every demo lives in a dedicated folder named after its identifier at the root of the repo, and
30
+ provides all the resources needed to understand the code, run the application locally or deploy it
31
+ remotely on a server.
32
+
33
+ Every demo provides a README.md file containing the following information:
34
+ - A brief description of the application and what's its goal.
35
+ - Explicit mention of which NLP use case is implemented: for example "QA", or "Document Retrieval".
36
+ - Detailed instructions about how to run the application locally.
37
+ - Any hardware requirement and the limitations when not provided (for example, a GPU device).
38
+ - How to modify and test the code, and how to contribute changes.
39
+
40
+ The code of a demo application should be tested whenever possible, and at least some of the
41
+ tests should be able to run in the repo CI system. Every demo has a dedicated Workflow defined
42
+ in a file named after its identifier. The workflow runs only when files in the demo folder are
43
+ modified.
44
+
45
+ In case the CI is needed for continuous deployment, or for building artifacts, a demo can have
46
+ more than one workflow file defined, named after its identifier plus a descriptive suffix, for
47
+ example: `my_demo_identifier.yml` for tests, `my_demo_identifier_docker.yml` for building a
48
+ Docker image, `my_demo_identifier_deploy.yml` for continuous delivery.
49
+
50
+ # Drawbacks
51
+
52
+ - The code of the existing demo would be removed from Haystack and potentially become harder to
53
+ find for existing contributors.
54
+ - The proposed design dictates a list of new requirements for a demo that will take time to
55
+ implement.
56
+
57
+ # Alternatives
58
+
59
+ - Leave things as they are
60
+ - Implement the design proposal to a subfolder of Haystack's git repository
61
+
62
+ # Adoption strategy
63
+
64
+ Adoption will be mostly driven by communicating the changes to the community and monitoring the
65
+ traffic in the new Github repository: interacting with the existing demo will not be affected
66
+ but accessing the code would.
67
+
68
+ # How we teach this
69
+
70
+ - A link to the demo repository will be added to the web page of the [demo itself](https://haystack-demo.deepset.ai/).
71
+ - Haystack's README and documentation will mention where to find the code for the demos.
72
+ - [Haystack Home](https://haystack.deepset.ai) will host a whole section dedicated to Haystack demos
73
+ (detailing the aforementioned section is out of scope for this proposal).
74
+
75
+ # Unresolved questions
76
+
77
+ N/A.
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3784-shaper.md ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: Shaper
2
+ - Decision driver: Vladimir
3
+ - Start Date: 2022-12-29
4
+ - Proposal PR: https://github.com/deepset-ai/haystack/pull/3784/
5
+
6
+ # Summary
7
+
8
+ Input/Output Shaper (Shaper) is a new pipeline component that can invoke arbitrary, registered functions, on the
9
+ invocation context (query, documents etc.) of a pipeline and pass the new/modified variables further down the pipeline.
10
+
11
+ # Basic example
12
+
13
+ In the following example, we'll use Shaper to add a new variable `questions` to the invocation context.
14
+ `questions` is a copy of query variable. This functionality of Shaper is useful when we simply want to
15
+ rename a variable in the invocation context e.g. in cases where the PromptNode template is expecting a variable
16
+ 'questions' rather than 'query'.
17
+
18
+
19
+ ```python
20
+
21
+ from haystack import Pipeline, Document
22
+
23
+ with open("tmp_config.yml", "w") as tmp_file:
24
+ tmp_file.write(
25
+ f"""
26
+ version: ignore
27
+ components:
28
+ - name: shaper
29
+ params:
30
+ inputs:
31
+ query:
32
+ output: questions
33
+ type: Shaper
34
+ pipelines:
35
+ - name: query
36
+ nodes:
37
+ - name: shaper
38
+ inputs:
39
+ - Query
40
+ """
41
+ )
42
+ pipeline = Pipeline.load_from_yaml(path="tmp_config.yml")
43
+ result = pipeline.run(
44
+ query="What can you tell me about Berlin?",
45
+ documents=[Document("Berlin is an amazing city."), Document("I love Berlin.")],
46
+ )
47
+ assert result
48
+ # query has been renamed to questions
49
+ assert isinstance(result["meta"]["invocation_context"]["questions"], str)
50
+
51
+
52
+ ```
53
+
54
+ # Motivation
55
+
56
+ We need Shaper to support the use cases where we want to easily add new variables to the pipeline invocation context.
57
+ These new variables hold values which are a result of some arbitrary function invocation on the existing variables
58
+ in the invocation context.
59
+
60
+ Shaper is especially useful when combined with PromptNode(s). Aside from simply renaming variables to match
61
+ the templates of PromptNodes, we can also use Shaper to add new variables to the invocation context. Often
62
+ these new variables are the result of some arbitrary function invocation on the existing variables in the
63
+ invocation context.
64
+
65
+ The original idea for Shaper is related to question answering use case using PromptNode. In QA, query string variable
66
+ passed to a pipeline run method needs to be expanded to a list of strings with the list size matching the size of the
67
+ documents list. Therefore, we can use the query as the question to pose to all the documents in the documents list.
68
+
69
+ The expected outcome of using Shaper is that we can easily add new variables to the invocation context so they can
70
+ match the prompt templates of PromptNodes. Multiple Shaper components can be used in a pipeline to modify the
71
+ invocation context as needed.
72
+
73
+
74
+ # Detailed design
75
+
76
+ The Shaper component is most often defined in pipelines YAML file. The YAML component definition consists of the
77
+ params block:
78
+
79
+ ```yaml
80
+ components:
81
+ - name: shaper
82
+ params:
83
+ inputs:
84
+ query:
85
+ func: expand
86
+ output: questions
87
+ params:
88
+ expand_target: query
89
+ size:
90
+ func: len
91
+ params:
92
+ - documents
93
+ documents:
94
+ func: concat
95
+ params:
96
+ docs: documents
97
+ delimiter: " "
98
+ type: Shaper
99
+ pipelines:
100
+ - name: query
101
+ nodes:
102
+ - name: shaper
103
+ inputs:
104
+ - Query
105
+ ```
106
+
107
+ The params block consists of the inputs list. Each item in the inputs list is a dictionary with the key being the
108
+ invocation context variable that we want to modify.
109
+
110
+ In the example above, we have two items in the inputs list. The first item is a dictionary with the key `query` and the
111
+ second item is a dictionary with the key `documents`.
112
+
113
+ For the query variable, we want to invoke the function `expand` and store the result in the variable `questions`.
114
+ The `expand` function takes two keyword parameters: `expand_target` and `size`. The `expand_target` parameter is the
115
+ name of the variable in the invocation context that we want to expand. The `size`parameter is a result of the `len`
116
+ function invocation on the variable `documents`.
117
+
118
+ For the documents variable, we want to invoke the function `concat` and store the result in the same variable.
119
+ Therefore, after the invocation, the documents variable will hold a result of `concat` function invocation while
120
+ we'll also have a new variable `questions` in the invocation context. The questions variable will hold a result of
121
+ `expand` function invocation.
122
+
123
+ The important thing to note here is that we can invoke functions with both keyword and positional parameters. Function
124
+ `len` is an example of a function that takes non-keyword positional parameters. The `concat` and `expand` function
125
+ take keyword parameters. These functions can also be invoked with positional parameters but that is not recommended.
126
+
127
+
128
+ ### Default parameters
129
+
130
+ The Shaper component can also be configured with default parameters. Default parameters are used when we
131
+ don't specify the parameters for a function invocation. The default parameters are specified in the function definition.
132
+
133
+ For example, in the YAML snippet definition below, we have a function `expand` that takes two keyword parameters:
134
+ `expand_target` and `size`. However, we haven't specified either of these parameters in the YAML config. This is
135
+ possible because we assume that the first parameter is always the variable we want to invoke the function on. In this
136
+ case, the variable `query`. The second parameter is the `size` of the list we want to expand the variable to. Here we
137
+ have also defined a helper function in Shaper called `expand:size` that calculates the default value of
138
+ this parameter - `len(documents)`.
139
+
140
+ Therefore, the `expand` function, described below, will be invoked with the following parameters: `query`
141
+ and `len(documents)`
142
+
143
+ ```yaml
144
+ components:
145
+ - name: shaper
146
+ params:
147
+ inputs:
148
+ query:
149
+ func: expand
150
+ output: questions
151
+ type: Shaper
152
+ pipelines:
153
+ - name: query
154
+ nodes:
155
+ - name: shaper
156
+ inputs:
157
+ - Query
158
+
159
+ ```
160
+
161
+ We need the "default parameter" functionality to support YAML files definitions that are more concise and less
162
+ error-prone.
163
+
164
+
165
+ ### Omitting output parameter
166
+
167
+ The output parameter is optional. If it is omitted, the result of the function invocation will be stored in
168
+ the corresponding input variable. In the example below, the output of expand function will be stored in the
169
+ query variable.
170
+
171
+ ```yaml
172
+ components:
173
+ - name: shaper
174
+ params:
175
+ inputs:
176
+ query:
177
+ func: expand
178
+ type: Shaper
179
+ pipelines:
180
+ - name: query
181
+ nodes:
182
+ - name: shaper
183
+ inputs:
184
+ - Query
185
+
186
+ ```
187
+
188
+ ### Order of function invocation
189
+
190
+ The order of function invocation is important. The functions are invoked in the order they are defined in the YAML.
191
+ In the example below, we have two input variables: `query` and `documents`. The `query` variable is expanded to a
192
+ list of strings and stored in the variable `questions`. The `documents` variable is then contracted and the
193
+ variable `questions` is immediately used as the `num_tokens` keyword parameter to the `concat` function.
194
+
195
+ ```yaml
196
+ components:
197
+ - name: shaper
198
+ params:
199
+ inputs:
200
+ query:
201
+ func: expand
202
+ output: questions
203
+ params:
204
+ expand_target: query
205
+ size:
206
+ func: len
207
+ params:
208
+ - documents
209
+ documents:
210
+ func: concat
211
+ output: documents
212
+ params:
213
+ docs: documents
214
+ delimiter: " "
215
+ num_tokens:
216
+ func: len
217
+ params:
218
+ - questions
219
+ type: Shaper
220
+ pipelines:
221
+ - name: query
222
+ nodes:
223
+ - name: shaper
224
+ inputs:
225
+ - Query
226
+ ```
227
+
228
+ ### Security
229
+
230
+ The Shaper component prevents arbitrary code execution. There should be no dangerous `exec` or `eval` Python calls. Only
231
+ the functions we have specified in the Shaper component are allowed to be invoked. The functions are specified in the
232
+ constructor using immutable data structures.
233
+
234
+ This security measure might be relaxed in the future to allow users to specify their own functions. However, this
235
+ change will require a more thorough security review.
236
+
237
+ # Drawbacks and other considerations
238
+
239
+ Although a "normal use" of PromptNodes would not trigger a need for Shaper there are cases where its
240
+ use is necessary. In cases where we can only use pipeline definitions to configure the pipeline (via YAML),
241
+ we need to use it.
242
+
243
+
244
+ - Implementation and maintenance cost should not be high.
245
+ - Shaper is not really useful outside of Haystack pipeline.
246
+ - Shaper could turn out to be useful in other use cases as well - i.e. declarative pre/post processing.
247
+ - Shaper integrates well with PromptNodes and other components.
248
+ - No braking changes to existing components.
249
+
250
+
251
+ # Alternatives
252
+
253
+ A better solution would likely be a more general run method for components. This would allow us to arbitrarily
254
+ define the pipeline invocation context. However even in those cases we'll need to use Shaper to modify
255
+ existing variables in invocation context as needed.
256
+
257
+ # Adoption strategy
258
+
259
+ Haystack users can start using Shaper in their pipelines immediately. There are no breaking changes to
260
+ existing components or pipelines.
261
+
262
+
263
+ # How we teach this
264
+
265
+ We will need docs update to teach users how to use Shaper. The docs will need to explain the
266
+ motivation using Shaper and PromptNode examples. We also need to show the usage via tutorials.
267
+
268
+
269
+ # Unresolved questions
270
+
271
+ Optional, but suggested for first drafts. What parts of the design are still
272
+ TBD?
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3875-table-cell.md ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: TableCell Dataclass
2
+ - Decision driver: Sebastian Lee
3
+ - Start Date: 2023-01-17
4
+ - Proposal PR: https://github.com/deepset-ai/haystack/pull/3875
5
+ - Github Issue: https://github.com/deepset-ai/haystack/issues/3616
6
+
7
+ # Summary
8
+
9
+ When returning answers for a TableQA pipeline we would like to return the column and row index as the answer location
10
+ within the table since the table is either returned as a list of lists in Haystack.
11
+ This would allow users to easily look up the answer in the returned table to fetch the text directly from the table,
12
+ identify the row or column labels for that answer, or generally perform operations on the table near or around the
13
+ answer cell.
14
+
15
+ # Basic Example
16
+
17
+ When applicable, write a snippet of code showing how the new feature would be used.
18
+ ```python
19
+ import pandas as pd
20
+ from haystack.nodes import TableReader
21
+ from haystack import Document
22
+
23
+ data = {
24
+ "actors": ["brad pitt", "leonardo di caprio", "george clooney"],
25
+ "age": ["58", "47", "60"],
26
+ "number of movies": ["87", "53", "69"],
27
+ "date of birth": ["18 december 1963", "11 november 1974", "6 may 1961"],
28
+ }
29
+ table_doc = Document(content=pd.DataFrame(data), content_type="table")
30
+ reader = TableReader(model_name_or_path="google/tapas-base-finetuned-wtq", max_seq_len=128)
31
+ prediction = reader.predict(query="Who was in the most number of movies?", documents=[table_doc])
32
+ answer = prediction["answers"][0]
33
+
34
+ # New feature
35
+ # answer.context -> [["actor", "age", "number of movies"], ["Brad Pitt",...], [...]]
36
+ # answer.offsets_in_context[0] -> (row=1, col=1)
37
+ print(answer.context[answer.offsets_in_context[0].row][answer.offsets_in_context[0].col])
38
+ ```
39
+
40
+ # Motivation
41
+
42
+ ## Why do we need this feature?
43
+ To allow users to easily look up the answer cell in the returned table to fetch the answer text
44
+ directly from the table, identify the row or column labels for that answer, or generally perform operations on the table
45
+ near or around the answer cell.
46
+
47
+ Currently, we return the location of the answer in the **linearized** version of the table, so we can use the
48
+ `Span` dataclass. The `Span` dataclass is reproduced below:
49
+ ```python
50
+ @dataclass
51
+ class Span:
52
+ start: int
53
+ end: int
54
+ """
55
+ Defining a sequence of characters (Text span) or cells (Table span) via start and end index.
56
+ For extractive QA: Character where answer starts/ends
57
+ For TableQA: Cell where the answer starts/ends (counted from top left to bottom right of table)
58
+
59
+ :param start: Position where the span starts
60
+ :param end: Position where the span ends
61
+ """
62
+ ```
63
+ This is inconvenient for users because they would need to know how the table is linearized (column major or row major)
64
+ so they could reconstruct the column and row indices of the answer before they could locate the answer cell in the table.
65
+
66
+ ## What use cases does it support?
67
+ Some examples are already stated above but to recap, to easily perform operations on the table near or around the answer cell.
68
+
69
+ ## What's the expected outcome?
70
+ The addition of a new dataclass called `TableCell` that would look like
71
+ ```python
72
+ @dataclass
73
+ class TableCell:
74
+ row: int
75
+ col: int
76
+ """
77
+ Defining a table cell via the row and column index.
78
+
79
+ :param row: Row index of the cell
80
+ :param col: Column index of the cell
81
+ """
82
+ ```
83
+
84
+ # Detailed design
85
+
86
+ **New terminology:** `TableCell`, the new name for the dataclass to
87
+ store the column and row index of the answer cell.
88
+
89
+ **Basic Example:** [Above Basic Example](#basic-example)
90
+
91
+ ## Code changes
92
+ - Addition of `TableCell` dataclass to https://github.com/deepset-ai/haystack/blob/main/haystack/schema.py
93
+ ```python
94
+ @dataclass
95
+ class TableCell:
96
+ row: int
97
+ col: int
98
+ """
99
+ Defining a table cell via the row and column index.
100
+
101
+ :param row: Row index of the cell
102
+ :param col: Column index of the cell
103
+ """
104
+ ```
105
+
106
+ - Updating code (e.g. schema objects, classes, functions) that use `Span` to also support `TableCell` where appropriate.
107
+ This includes:
108
+ - Updating the `Answer` dataclass to support `TableCell` as a valid type for `offsets_in_document` and `offsets_in_context`
109
+ ```python
110
+ @dataclass
111
+ class Answer:
112
+ answer: str
113
+ type: Literal["generative", "extractive", "other"] = "extractive"
114
+ score: Optional[float] = None
115
+ context: Optional[Union[str, List[List]]] = None
116
+ offsets_in_document: Optional[List[Span], List[TableCell]] = None
117
+ offsets_in_context: Optional[List[Span], List[TableCell]] = None
118
+ document_id: Optional[str] = None
119
+ meta: Optional[Dict[str, Any]] = None
120
+ ```
121
+ - 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
122
+ when multiple `TableCell`s are returned to form a final answer.
123
+ - Updating any functions that accept table answers as input to use the new `col` and `row` variables instead of `start` and `end` variables.
124
+ This type of check for table answers is most likely already done by checking if the `context` is of type `pd.DataFrame`.
125
+ - `TableReader` and `RCIReader` to return `TableCell` objects instead of `Span`.
126
+
127
+ Changes related to the Edge Case/Bug below
128
+ - Update `Document.content` and `Answer.context` to use `List[List]` instead of `pd.DataFrame`.
129
+ - Update `TableReader` nodes to convert table from `List[List]` into `pd.DataFrame` before inputting to the model.
130
+
131
+ ## Edge Case/Bug
132
+ Internally, Haystack stores a table as a pandas DataFrame in the `Answer` dataclass, which does not treat the column
133
+ labels as the first row in the table.
134
+ However, in Haystack's rest-api the table is converted into a list of lists format where the column labels are
135
+ stored as the first row, which can be seen [here](https://github.com/deepset-ai/haystack/pull/3872), which is consistent
136
+ with the `Document.to_dict()` method seen [here](https://github.com/deepset-ai/haystack/blob/6af4f14fe0d375a1ae0ced18930a9239401231c7/haystack/schema.py#L164-L165).
137
+
138
+ This means that the current `Span` and (new) `TableCell` dataclass point to the wrong location when the table is
139
+ converted to a list of lists.
140
+
141
+ For example, the following code
142
+ ```python
143
+ import pandas as pd
144
+ from haystack import Document
145
+
146
+ data = {
147
+ "actors": ["brad pitt", "leonardo di caprio", "george clooney"],
148
+ "age": ["58", "47", "60"],
149
+ "number of movies": ["87", "53", "69"],
150
+ "date of birth": ["18 december 1963", "11 november 1974", "6 may 1961"],
151
+ }
152
+ table_doc = Document(content=pd.DataFrame(data), content_type="table")
153
+ span = (0, 0)
154
+ print(table_doc.content.iloc[span]) # prints "brad pitt"
155
+
156
+ dict_table_doc = table_doc.to_dict()
157
+ print(dict_table_doc["content"][span[0]][span[1]]) # prints "actors"
158
+ ```
159
+
160
+ 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).
161
+
162
+ # Drawbacks
163
+
164
+ Look at the feature from the other side: what are the reasons why we should _not_ work on it? Consider the following:
165
+
166
+ - What's the implementation cost, both in terms of code size and complexity?
167
+
168
+ I don't believe this will require too much code change since we already check for Table like answers by checking if the
169
+ returned context is of type string or pandas Dataframe.
170
+
171
+ - Can the solution you're proposing be implemented as a separate package, outside of Haystack?
172
+
173
+ Technically yes, but since it affects core classes like `TableReader`, and `RCIReader` it makes sense to implement in
174
+ Haystack.
175
+
176
+ - Does it teach people more about Haystack?
177
+
178
+ It would update already existing documentation and tutorials of Haystack.
179
+
180
+ - How does this feature integrate with other existing and planned features?
181
+
182
+ This feature directly integrates and impacts the TableQA feature of Haystack.
183
+
184
+ - What's the cost of migrating existing Haystack pipelines (is it a breaking change?)?
185
+
186
+ Yes there are breaking changes that would affect end users.
187
+ 1. The way to access the offsets in returned Answers would be different.
188
+ Following the deprecation policy we will support both `Span` and `TableCell` (can be toggled between using a boolean flag)
189
+ for 2 additional versions of Haystack.
190
+ 2. Tables in Haystack Documents and Answers will change from type pandas Dataframe to a list of lists.
191
+
192
+ # Alternatives
193
+
194
+ ## What's the impact of not adding this feature?
195
+ Requiring users to figure out how to interpret the linearized answer cell coordinates to reconstruct the row and column indices
196
+ to be able to access the answer cell in the returned table.
197
+
198
+ ## Other designs
199
+ 1. Expand `Span` dataclass to have optional `col` and `row` fields. This would require a similar check as `TableCell`, but instead
200
+ require checking for which of the elements are populated, which seems unnecessarily complex.
201
+ ```python
202
+ @dataclass
203
+ class Span:
204
+ start: int = None
205
+ end: int = None
206
+ col: int = None
207
+ row: int = None
208
+ ```
209
+ 2. Use the existing `Span` dataclass and put the row index and column index as the `start` and `end` respectively.
210
+ This may be confusing to users since it is not obvious that `start` should refer to `row` and `end` should refer to `column`.
211
+ ```python
212
+ answer_cell_offset = Span(start=row_idx, end=col_idx)
213
+ ```
214
+ 3. Provide a convenience function shown [here](https://github.com/deepset-ai/haystack/issues/3616#issuecomment-1361300067)
215
+ to help users convert the linearized `Span` back to row and column indices. I believe this solution is non-ideal since it would
216
+ require a user of the rest_api to access a python function to convert the linearized indices back into row and column indices.
217
+
218
+ # Adoption strategy
219
+
220
+ ## How will the existing Haystack users adopt it?
221
+ Haystack users would immediately experience this change once they update their installation of Haystack if they were using
222
+ the TableQA reader. This would be a breaking change since it would change the `offsets_in_document` and
223
+ `offsets_in_context` in the returned `Answer`. I'm not sure if there would be a straightforward way to write a migration
224
+ script for this change.
225
+
226
+ # How we teach this
227
+
228
+ Would implementing this feature mean the documentation must be re-organized
229
+ or updated? Does it change how Haystack is taught to new developers at any level?
230
+
231
+ - The API docs for `TableCell` would need to be added.
232
+ - The documentation page for [Table Question Answering](https://docs.haystack.deepset.ai/docs/table_qa) would need to be updated.
233
+ - Update the (TableQa tutorial)[https://github.com/deepset-ai/haystack-tutorials/blob/main/tutorials/15_TableQA.ipynb]
234
+ to reflect the `Span` is no longer linearzied.
235
+
236
+ # Unresolved questions
237
+
238
+ No more unresolved questions.
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3925-mrkl-agent.md ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: MRKLAgent
2
+ - Decision driver: @julian-risch (in close collaboration with @vblagoje )
3
+ - Start Date: 2023-01-27
4
+ - Proposal PR: https://github.com/deepset-ai/haystack/pull/3925
5
+ - Github Issue or Discussion: https://github.com/deepset-ai/haystack/issues/3753
6
+
7
+ # Summary
8
+ The Agent class answers queries by choosing between different tools, which are implemented as pipelines or nodes.
9
+ 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.
10
+ Based on the result returned by an action/tool (used interchangeably), the Agent has two options.
11
+ It can either stop if it knows the answer now or repeat the process of 1) thought, 2) action choice, 3) action input.
12
+
13
+ The Agent can be used for questions containing multiple subquestions that can be answered step-by-step (Multihop QA).
14
+ Combined with tools like the PythonRuntime or SerpAPIComponent we imagine for Haystack, the Agent can query the web and do calculations.
15
+
16
+ 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.
17
+ The notebook is based on the branch https://github.com/deepset-ai/haystack/compare/main...mrkl-pipeline (no pull request)
18
+
19
+ # Basic example
20
+
21
+ An example of an Agent could use two tools: a web search engine and a calculator.
22
+
23
+ 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:
24
+ 1) Searching the web for the name of Olivia Wilde's boyfriend
25
+ 2) Searching the web for the age of that boyfriend
26
+ 3) Calculating that age raised to the 0.23 power
27
+
28
+ 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.
29
+
30
+
31
+ # Motivation
32
+
33
+ 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.
34
+
35
+ 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.
36
+
37
+ # Detailed design
38
+
39
+ **Glossary**
40
+ - 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.
41
+ - 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.
42
+ - 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.
43
+ - Observation: The output generated by a tool and sent back to the Agent.
44
+
45
+ The Agent consists of a PromptNode that generates thoughts, chooses actions, and generates action inputs.
46
+ 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.
47
+ Tools need to be added to an Agent so that it can use them, just like nodes need to be added to pipelines.
48
+ 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.
49
+
50
+ 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.
51
+ An example application of this is MultiHopQA, where multiple subquestions need to be answered step-by-step.
52
+ 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:
53
+
54
+ ```
55
+ Answer the following questions as best as you can. You have access to the following tools:
56
+
57
+ Search: useful for when you need to answer questions about current events. You should ask targeted questions
58
+ Calculator: useful for when you need to answer questions about math
59
+
60
+ Use the following format:
61
+
62
+ Question: the input question you must answer
63
+ Thought: you should always think about what to do
64
+ Action: the action to take, should be one of [Search, Calculator]
65
+ Action Input: the input to the action
66
+ Observation: the result of the action
67
+ ... (this Thought/Action/Action Input/Observation can repeat N times)
68
+ Thought: I now know the final answer
69
+ Final Answer: the final answer to the original input question
70
+
71
+ Begin!
72
+ Question: Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?
73
+ Thought: I need to do some research to answer this question.
74
+ Action: Search
75
+ Action Input: Olivia Wilde's boyfriend
76
+ 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.
77
+ Thought: I need to find out his age
78
+ Action: Search
79
+ Action Input: Jason Sudeikis age
80
+ Observation: 47 years
81
+ Thought: I need to raise it to the 0.23 power
82
+ Action: Calculator
83
+ Action Input: 47^0.23
84
+ Observation: 2.4242784855673896
85
+ Thought: I now know the final answer
86
+ Final Answer: Jason Sudeikis, Olivia Wilde's boyfriend, is 47 years old and his age raised to the 0.23 power is 2.4242784855673896.
87
+ ```
88
+
89
+ ## Agent steps breakdown
90
+ 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.
91
+
92
+ ### Step 1:
93
+
94
+ We start with a prompt where we instruct LLM on what we want. The first prompt we send to LLM is the following:
95
+ ```
96
+ Answer the following questions as best as you can. You have access to the following tools:
97
+
98
+ Search: useful for when you need to answer questions about current events. You should ask targeted questions
99
+ Calculator: useful for when you need to answer questions about math
100
+
101
+ Use the following format:
102
+
103
+ Question: the input question you must answer
104
+ Thought: you should always think about what to do
105
+ Action: the action to take, should be one of [Search, Calculator]
106
+ Action Input: the input to the action
107
+ Observation: the result of the action
108
+ ... (this Thought/Action/Action Input/Observation can repeat N times)
109
+ Thought: I now know the final Answer
110
+ Final Answer: the final Answer to the original input question
111
+
112
+ Begin!
113
+ Question: Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?
114
+ Thought:
115
+ ```
116
+
117
+ 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.
118
+ 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.
119
+ As we also instruct the model to stop generating a response with stop words being `Observation:` the model response for this step is:
120
+
121
+ ```
122
+ I need to do some research to answer this question.
123
+ Action: Search
124
+ Action Input: Olivia Wilde's boyfriend
125
+ ```
126
+
127
+ 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."
128
+
129
+ We append the tool response under the `Observation:`
130
+
131
+ LLM generation above and the response from the Search action (added under Observation) are appended to the initial prompt.
132
+
133
+ ### Step 2:
134
+
135
+ We start this step with the following prompt:
136
+
137
+ ```
138
+ Answer the following questions as best as you can. You have access to the following tools:
139
+
140
+ Search: useful for when you need to answer questions about current events. You should ask targeted questions
141
+ Calculator: useful for when you need to answer questions about math
142
+
143
+ Use the following format:
144
+
145
+ Question: the input question you must answer
146
+ Thought: you should always think about what to do
147
+ Action: the action to take, should be one of [Search, Calculator]
148
+ Action Input: the input to the action
149
+ Observation: the result of the action
150
+ ... (this Thought/Action/Action Input/Observation can repeat N times)
151
+ Thought: I now know the final Answer
152
+ Final Answer: the final Answer to the original input question
153
+
154
+ Begin!
155
+ Question: Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?
156
+ Thought: I need to do some research to answer this question.
157
+ Action: Search
158
+ Action Input: Olivia Wilde's boyfriend
159
+ 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.
160
+ Thought:
161
+ ```
162
+
163
+ 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:
164
+
165
+ ```
166
+ I need to find out his age
167
+ Action: Search
168
+ Action Input: Jason Sudeikis age
169
+ ```
170
+
171
+ 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.
172
+
173
+ ### Step 3:
174
+
175
+ 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.
176
+ The last part of the prompt is the following:
177
+ ```
178
+ Thought: I need to find out his age
179
+ Action: Search
180
+ Action Input: Jason Sudeikis age
181
+ Observation: 47 years
182
+ Thought:
183
+ ```
184
+
185
+ The LLM-generated response is:
186
+
187
+ ```
188
+ I need to raise it to the 0.23 power
189
+ Action: Calculator
190
+ Action Input: 47^0.23
191
+ ```
192
+
193
+ In this step, we invoke a new tool - The calculator with specified input. The calculator response is 2.4242784855673896
194
+ We added the calculator response to the prompt history under the Observation keyword.
195
+
196
+
197
+ ### Step 4:
198
+
199
+ 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:
200
+ ```
201
+ I need to raise it to the 0.23 power
202
+ Action: Calculator
203
+ Action Input: 47^0.23
204
+ Observation: 2.4242784855673896
205
+ Thought:
206
+ ```
207
+
208
+ The LLM-generated response is:
209
+ ```
210
+ I now know the final answer
211
+ Final Answer: Jason Sudeikis, Olivia Wilde's boyfriend, is 47 years old and his age raised to the 0.23 power is 2.4242784855673896.
212
+ ```
213
+
214
+ 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.
215
+ 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.
216
+
217
+ ## Agent Creation
218
+
219
+ The Agent can be either created programmatically or loaded from a YAML file.
220
+ In the following example, one tool is a node for searching the web. The other tool is a pipeline for doing calculations in python.
221
+
222
+ **Example programmatic creation:**
223
+ ```python
224
+ search = SerpAPIComponent(api_key=os.environ.get("SERPAPI_API_KEY"), name="Serp", inputs=["Query"])
225
+
226
+ prompt_model=PromptModel(model_name_or_path="text-davinci-003", api_key=os.environ.get("OPENAI_API_KEY"))
227
+
228
+ calculator = Pipeline()
229
+ calculator.add_node(PromptNode(
230
+ model_name_or_path=prompt_model,
231
+ default_prompt_template=PromptTemplate(prompt_text="Write a simple python function that calculates..."),
232
+ output_variable="python_runtime_input") # input
233
+ calculator.add_node(PythonRuntime()) # actual calculator
234
+
235
+ prompt_node = PromptNode(
236
+ model_name_or_path=prompt_model,
237
+ stop_words=["Observation:"]
238
+ )
239
+
240
+ agent = Agent(prompt_node=prompt_node)
241
+ # Nodes and pipelines can be added as tools to the agent. Just as nodes can be added to pipelines with add_node()
242
+ agent.add_tool("Search", search, "useful for when you need to answer questions about current events. You should ask targeted questions")
243
+ agent.add_tool("Calculator", calculator, "useful for when you need to answer questions about math")
244
+
245
+ result = agent.run("What is 2 to the power of 3?")
246
+ ```
247
+
248
+ **Example YAML file:**
249
+ ```yaml
250
+ version: ignore
251
+
252
+ components:
253
+ - name: AgentPromptNode
254
+ type: PromptNode
255
+ params:
256
+ model_name_or_path: DavinciModel
257
+ stop_words: ['Observation:']
258
+ - name: DavinciModel
259
+ type: PromptModel
260
+ params:
261
+ model_name_or_path: 'text-davinci-003'
262
+ api_key: 'XYZ'
263
+ - name: Serp
264
+ type: SerpAPIComponent
265
+ params:
266
+ api_key: 'XYZ'
267
+ - name: CalculatorInput
268
+ type: PromptNode
269
+ params:
270
+ model_name_or_path: DavinciModel
271
+ default_prompt_template: CalculatorTemplate
272
+ output_variable: python_runtime_input
273
+ - name: Calculator
274
+ type: PythonRuntime
275
+ - name: CalculatorTemplate
276
+ type: PromptTemplate
277
+ params:
278
+ name: calculator
279
+ prompt_text: |
280
+ # Write a simple python function that calculates
281
+ # $query
282
+ # Do not print the result; invoke the function and assign the result to final_result variable
283
+ # Start with import statement
284
+
285
+ pipelines:
286
+ - name: calculator_pipeline
287
+ nodes:
288
+ - name: CalculatorInput
289
+ inputs: [Query]
290
+ - name: Calculator
291
+ inputs: [CalculatorInput]
292
+
293
+ agents:
294
+ - name: agent
295
+ params:
296
+ prompt_node: AgentPromptNode
297
+ tools:
298
+ - name: Search
299
+ pipeline_or_node: Serp
300
+ description: >
301
+ useful for when you need to answer questions about current events.
302
+ You should ask targeted questions
303
+ - name: Calculator
304
+ pipeline_or_node: calculator_pipeline
305
+ description: >
306
+ useful for when you need to answer questions about math
307
+ ```
308
+
309
+ and loading from the YAML file into an Agent:
310
+
311
+ ```python
312
+ agent = Agent.load_from_yaml(
313
+ "test.mrkl.haystack-pipeline.yml", agent_name="agent"
314
+ )
315
+ ```
316
+
317
+ Pipelines, agents, nodes, and tools all implement `run` and `run_batch` methods, which is the minimal contract.
318
+ 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.
319
+
320
+ # Drawbacks
321
+
322
+ Although the scope of the initial Agent is limited, it can grow into a full-fledged framework consisting of
323
+ 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.
324
+
325
+ One of the central building blocks of an Agent are the PromptNode and set "neural attachments" extending the agent's capabilities.
326
+ Many tools like Search, Calculator, Notion and API connectors are somewhat different conceptually from the existing Haystack components.
327
+ On the other hand, some of the existing Haystack components fit naturally into the framework of tools, for example, DocumentStore, Retriever, and Reader.
328
+
329
+ There is a non-negligible potential for a growing implementation cost of such an agent framework that might
330
+ stretch the resource away from the existing Haystack core. However, as LLM-based agents are an exciting and
331
+ rapidly growing field, they may raise Haystack awareness significantly.
332
+
333
+ # Alternatives
334
+
335
+ We have considered an alternative design where the Agent is just another node or a pipeline.
336
+ However, we decided to introduce it as a separate concept because of user-friendliness / clear code.
337
+ While a Pipeline is a collection of Nodes, an Agent is a collection of Pipelines.
338
+ 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.
339
+
340
+ Regarding the name *Agent*, we considered several alternatives and prefer *Agent* for its simplicity.
341
+ Alternative names:
342
+ - MRKLAgent
343
+ - LLMOrchestrator
344
+ - LLMChain
345
+ - Toolchain (fits nicely with tools and [toolchains](https://en.wikipedia.org/wiki/Toolchain) in software)
346
+ - PipelineComposer / LLMComposer
347
+ - PipelineComposition / LLMComposition
348
+ - Interesting naming tidbits:
349
+ - MRKL [paper](https://arxiv.org/pdf/2205.00445.pdf) never uses word agent, only system
350
+ - ReAct [paper](https://arxiv.org/pdf/2210.03629.pdf) uses agent almost exclusively
351
+
352
+
353
+ # Adoption strategy
354
+
355
+ 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.
356
+
357
+ 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.
358
+
359
+ Using an Agent requires an OpenAI api key and some tools require additional api keys, for example SerpAPI but there are free trials.
360
+
361
+ 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.
362
+
363
+ # How we teach this
364
+
365
+ 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.
366
+
367
+ 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.
368
+
369
+ # Unresolved questions
370
+
371
+ **Name of the parameter pipeline_or_node**
372
+ * When we add a tool to the agent, we need to specify the name of the pipeline or node (component) to add.
373
+ This parameter could be called `pipeline_or_node` or `pipeline_or_component_name` etc.
374
+
375
+ **Umbrella Term for Pipeline and Agent**
376
+ * We need a term that captures pipelines and agents for communication with users (NLP application, flow, system, service, engine ...).
377
+ Let's have that conversation separately from this proposal.
378
+
379
+ **Tools we imagine in the near future**
380
+ * Tools will be discussed in a separate proposal.
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/3959-json-converter.md ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: Addition of a `JsonConverter` node
2
+ - Decision driver: @bglearning
3
+ - Start Date: 2023-01-26
4
+ - Proposal PR: #3959
5
+
6
+ # Summary
7
+
8
+ Right now we don't have a node that can take json files as input to be fed into a pipeline.
9
+
10
+ Proposal: Add a `JsonConverter` node that takes in a json file, parses it, and generates `Document`s.
11
+ It would also support the `jsonl` format with one line corresponding to one document.
12
+
13
+ # Basic example
14
+
15
+ ```python
16
+ from haystack.nodes import JsonConverter
17
+
18
+ converter = JsonConverter()
19
+
20
+ # Receive back List[Document]
21
+ docs = converter.convert("data_file.json")
22
+ ```
23
+
24
+ With the `data_file.json` as a list of json representation of documents:
25
+
26
+ ```json
27
+ [
28
+ {
29
+ "content": "...",
30
+ "content_type": "text", "meta": {...}
31
+ },
32
+ {
33
+ "content": [["h1", "h2"], ["val1", "val2"]],
34
+ "content_type": "table", "meta": {...}
35
+ }
36
+ ]
37
+ ```
38
+
39
+ Alternatively, the data can also be `jsonl`.
40
+ By default, the converter will try to auto-detect between `json` and `jsonl`.
41
+
42
+ The main use case would be to be able to include this directly in the YAML specification
43
+
44
+ ```yaml
45
+ ...
46
+
47
+ pipelines:
48
+ - name: indexing
49
+ nodes:
50
+ - name: JsonConverter
51
+ inputs: [File]
52
+ - name: Retriever
53
+ inputs: [JsonConverter]
54
+ - name: DocumentStore
55
+ inputs: [Retriever]
56
+ ```
57
+
58
+ # Motivation
59
+
60
+ 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.
61
+
62
+ For many such processing, json is a convenient intermediate format as it allows for things like specifying the metadata.
63
+
64
+ 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.
65
+
66
+ 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.
67
+
68
+ # Detailed design
69
+
70
+ The converter would primarily be a wrapper around `Document.from_dict`.
71
+
72
+ The schema accepted would be the a list of json dictionary of Documents.
73
+ So, the following, with `content` being the only compulsory field.
74
+
75
+ ```
76
+ [
77
+ {
78
+ "content": str or list[list],
79
+ "content_type": str,
80
+ "meta": dict,
81
+ "id_hash_keys": list,
82
+ "score": float,
83
+ "embedding": array
84
+ },
85
+ ...
86
+ ]
87
+ ```
88
+
89
+ ```python
90
+ class JsonConverter(BaseConverter):
91
+ def __init__(self, ...):
92
+ ...
93
+
94
+ def convert(
95
+ self,
96
+ file_path: Path,
97
+ meta: Optional[Dict[str, str]] = None,
98
+ encoding: Optional[str] = "UTF-8",
99
+ id_hash_keys: Optional[List[str]] = None,
100
+ ...
101
+ ) -> List[Document]:
102
+ if id_hash_keys is None:
103
+ id_hash_keys = self.id_hash_keys
104
+
105
+ documents = []
106
+ with open(file_path, encoding=encoding, errors="ignore") as f:
107
+ data = json.load(f)
108
+ for doc_dict in data:
109
+ doc_dict = dict(doc_dict)
110
+ doc_dict['id_hash_keys'] = id_hash_keys
111
+ doc_dict['meta'] = doc_dict.get('meta', dict())
112
+
113
+ if meta:
114
+ doc_dict['meta'].update(meta)
115
+
116
+ documents.append(Document.from_dict(doc_dict))
117
+
118
+ return documents
119
+ ```
120
+
121
+ # Drawbacks
122
+
123
+ - It would add another node that needs to be maintained and documented.
124
+
125
+ # Alternatives
126
+
127
+ - 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.
128
+ - 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.
129
+
130
+ # Adoption strategy
131
+
132
+ It doesn't introduce a breaking change and wouldn't require changes in existing pipelines.
133
+
134
+ # How we teach this
135
+
136
+ It would be good to have this be part of the Guide (perhaps under File Converters).
137
+
138
+ 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".
139
+
140
+ # Unresolved questions
141
+
142
+ - 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.
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4084-agent-demo.md ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: Agent tools
2
+ - Decision driver: Vladimir Blagojevic (with Julian Risch)
3
+ - Start Date: 2023-02-06
4
+ - Proposal PR: https://github.com/deepset-ai/haystack/pull/4084
5
+
6
+
7
+ # Summary
8
+
9
+ Agent system consists of an extendable set of modules (aka experts/tools) and a "router" dispatching natural
10
+ language input to a module that can best respond to the given input. These modules can be:
11
+
12
+ • Neural, including the general-purpose LLMs as well as other smaller, specialized LMs.
13
+
14
+ • Symbolic, for example a math calculator, a currency converter, or an API call to a search engine.
15
+
16
+
17
+ Current Haystack pipeline design approach fits nicely with these extension modules/tools. They can be tested in
18
+ isolation and subsequently integrated into the agent. The agent can register these tools, understand their objectives
19
+ and route the user input to the appropriate tool. The tools can be either Haystack pipelines or components.
20
+
21
+
22
+ A demo idea for the new Agent is to demonstrate Question Answering on Technical Documentation (using the example of
23
+ Haystack). It should be useful and impressive, and it determines what tools we will implement first.
24
+
25
+ **Example Questions:**
26
+ - "Why am I seeing duplicate answers being returned?" based on indexed FAQ documentation
27
+ - "Which organizations use Haystack?" based on web search and Wikipedia returning answers via SearchEngine
28
+ - "How can I choose the model for PromptNode?" based on retrieving documents via WebRetriever
29
+ - "How can I make overwrite_with_env_variables work in RayPipeline" based on an open issue found with GitHub API or web search
30
+
31
+ If an answer cannot be found in indexed files, the Agent will use self reflection to rephrase the question and/or search the
32
+ web. It will give updates while searching, for example print thoughts: “Found nothing in indexed documentation. Will continue
33
+ with web search.” If still nothing can be found, the Agent will generate a link to a pre-filled and pre-tagged issue template
34
+ like this that the user can choose to create. Tools required for the demo: SearchEngine, GitHubAPI, Self Reflection Module, WebRetriever.
35
+
36
+ We also need to demonstrate how the Agent uses a combination of multiple tools to answer a question instead of just trying
37
+ them sequentially.
38
+
39
+ **Example Question:**
40
+ - "Is there an open issue about any of the nodes in a standard QA pipeline not working?"
41
+
42
+ Here the LLM might first use documentation to find out more about what nodes are part of standard QA pipelines and then
43
+ searches on GitHub for open issues that mention retriever or reader.
44
+
45
+ We propose the following tools to be developed for the MVP version of our agent (#3925):
46
+
47
+ - SearchEngine
48
+ - Self reflection module (query rephrasing)
49
+ - WebRetriever
50
+ - Top-p (nucleus) sampling
51
+ - Agent memory
52
+ - deepset Cloud API
53
+
54
+ # Basic example
55
+
56
+ No code examples are provided, but a high-level overview of how the feature would be used.
57
+
58
+ There is also a [colab notebook](https://colab.research.google.com/drive/1oJf4gxkokIazLN26NNt6XsewMvCmVrz8?usp=sharing)
59
+ demonstrating how to use an agent with tools and a [branch](https://github.com/deepset-ai/haystack/compare/main...mrkl-pipeline)
60
+ for demo purposes (no pull request).
61
+
62
+ # Motivation
63
+
64
+ Agent tools are the main and essential building block of the agent system. They are the modules extending the
65
+ agent's capabilities. Agent, when it relies only on itself, is not as powerful as when it can leverage the
66
+ external modules (tools) that are highly specialized in their respective domains. Agent can't do, for example, lookup of
67
+ restaurants in our neighbourhood, but it can use SearchEngine to do that. When it comes to complex math calculations, LLM
68
+ would be a poor choice, but a math calculator would be a good fit, and so on.
69
+
70
+ Combining the power of LLMs with the power of external tools is the key ingredient to the success of the agent framework.
71
+
72
+
73
+ # Detailed design
74
+
75
+ In the following sections, we list essential agent tools required for agent MVP. We start with the general design
76
+ principles and then describe each tool in detail.
77
+
78
+ Each tool is defined as a Python class that inherits from the BaseComponent class. The base class acts as a wrapper
79
+ around the actual tool implementation.
80
+
81
+ The main Agent modules/tools are:
82
+
83
+ ## SearchEngine
84
+
85
+ SearchEngine is a symbolic API module allowing programmatic interaction with Google and other search engines. We'll have
86
+ multiple providers of SearchEngine including https://serper.dev, https://www.searchapi.io/ and https://serpapi.com as initial providers.
87
+
88
+ SearchEngine will return a list of results (e.g. List[Document]), the content of each document being a "snippet" of the
89
+ single search result, while all other attributes of the search results (e.g. title, url link, etc.) will
90
+ be metadata of the document.
91
+
92
+ ### SearchEngine scoping
93
+
94
+ A great feature of SearchEngine is that it can be scoped to a particular domain. Therefore, in our demo, if so desired,
95
+ we can search through Haystack documentation on docs.haystack.com, github.com/deepset-ai/haystack and so on.
96
+
97
+ ## Self reflection module
98
+
99
+ SRM is a neural module that aims to improve the agent's overall robustness. Agents can sometimes be very fragile
100
+ in their execution steps. As a core component, the motivation for the self-reflection module (SRM) is to improve the
101
+ robustness of the agent's execution. Agents can be fragile in their execution steps due to the non-deterministic nature
102
+ of LLM inferencing and their sensitivity to the chosen prompts.
103
+
104
+ SRM relies on instruction following LLM and operates in two lock-step sequences. Given any other agent module/tool,
105
+ its description, and its input and output - SRM does the following:
106
+
107
+ 1. It checks if the module description (objective), the input, and the output are aligned/congruent.
108
+ 2. If they are not aligned, it rephrases the input (while retaining semantic meaning) and attempts to elicit an aligned
109
+ output.
110
+
111
+ SRM can improve the robustness of any module. For example, SearchEngine can sometimes be very sensitive to query wording.
112
+ If we are searching for "Olivia Wilde's boyfriend", the results might not be as precise as if we search for "Who is
113
+ Olivia Wilde's current boyfriend?". SRM can rephrase the query to the latter form if the former form doesn't return
114
+ an aligned answer.
115
+
116
+ It is still an open question of how to implement SRM. We can make it an internal component or another pipeline. The
117
+ former approach is more efficient and has tight coupling, and the latter is more flexible. We'll carefully weigh
118
+ the pros and cons of each approach and decide on the best approach.
119
+
120
+ One idea how to integrate SRM into an existing Agent and its tools is that every tool can set a parameter indicating
121
+ 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,
122
+ otherwise it will check at least once for alignment/congruency and optionally rephrase. This will repeat but not
123
+ more often than the parameter allows.
124
+
125
+ One possible implementation of SRM could be https://arxiv.org/abs/2203.11171
126
+
127
+ The main motivation for addition of SRM (and self-consistency ideas in general) is the finding from
128
+ https://arxiv.org/abs/2210.03629 Google Brain researchers discovered that "Wrong reasoning trace (including failing
129
+ to recover from repetitive steps)" accounts for 47% of agent errors.
130
+
131
+ ## WebRetriever
132
+
133
+ WebRetriever is a symbolic module that allows users to query the web for relevant documents. It is a wrapper around
134
+ SearchEngine that produces a list of Haystack Documents.
135
+
136
+ WebRetriever will operate in two modes:
137
+
138
+ - snippet mode: WebRetriever will return a list of Documents, each Document being a snippet of the search result
139
+ - document mode: WebRetriever will return a list of Documents, each Document being a full HTML stripped document of the search result
140
+
141
+ In document mode, given a user query passed via the run method, SearchEngine first fetches the top_k relevant URL hits, which are
142
+ downloaded and processed. The processing involves stripping irrelevant HTML tags and producing clean raw text. WebRetriever
143
+ then splits raw text into paragraph-long Documents of the desired size.
144
+
145
+ In the future, we'll develop WebRetriever variants with DocumentStore that caches documents with some expiration
146
+ setting. The enhanced WebRetreiever versions will allow us to avoid downloading the same documents from the web
147
+ multiple times.
148
+
149
+ However, for the first version of the agent, we'll strive to keep WebRetriever as simple as possible.
150
+
151
+ ## Top-p (nucleus) sampling
152
+
153
+ Although very useful, top-k ranking is sometimes inferior to top-p ranking. Instead of filtering only from the most
154
+ likely k hits, in top-p sampling we choose the smallest possible set of documents whose cumulative probability of
155
+ relevance exceeds the probability p (usually close to 1). The relevance could be calculated via sbert.net CrossEncoder using
156
+ query and the document content.
157
+
158
+ In web search, this is a very useful feature as it allows us to avoid query irrelevant documents and be super precise
159
+ in our search results. We'll implement top-p sampling as a separate module that WebRetriever can use. Other components
160
+ in Haystack can use it as well.
161
+
162
+ The main motivation for addition of top-p sampling is the finding from https://arxiv.org/abs/2210.03629 Google Brain
163
+ researchers found that "Search result error" is the main cause in 23% of the cases of agent failure. Top-p sampling
164
+ can help us minimize this point of failure.
165
+
166
+ Note that one can still use top-k filtering via Ranker and top-p filtering via TopPSampler in combination.
167
+
168
+ ## Agent memory
169
+
170
+ Although we currently support only so-called ReAct agents, it is not hard to envision a future where we'll have
171
+ additional agent types including conversational agents.
172
+
173
+ Due to LLMs one-shot-forget nature of inferencing, conversational agents might need to remember the context of the
174
+ conversation. To support conversational agents, we'll need Agent memory component. The memory component will initially contain
175
+ two submodules: entity extraction and summarization
176
+
177
+ Entity extraction is a neural module extracting entities from the provided conversation transcript (raw text).
178
+ The entities are best thought of as an outcome of Named-entity recognition task; for example, people, places, organizations etc.
179
+
180
+ Entity summarization is a neural module that summarizes the entities extracted by the entity extraction module.
181
+
182
+ Entity extraction and summarization are run in the background as the conversation progresses. The
183
+ frequency of extraction and summarization updates will be configurable.
184
+
185
+ The extracted entities along with relevant summaries will be stored in the Agent memory. Agent memory implementation
186
+ details are out of scope of this proposal; they could be various short or long term memory storage options.
187
+
188
+ For the first version of the agent, we'll strive to keep the memory component as simple as possible; we'll
189
+ only implement entity extraction and summarization while we'll use runtime memory for storing entities.
190
+
191
+ ### Future improvements:
192
+
193
+ As we have limited token payload for model inferencing, we'll need to implement a mechanism for decaying memory.
194
+
195
+ If we have many entities in the memory, we'll also need to implement a mechanism for entities selection.
196
+ We'll likely need no summaries for well-known entities like "Elon Musk" or "New York".
197
+
198
+ Information related to the entities could become stale over time (e.g."I'm currently in New York") and we'll
199
+ need to implement a mechanism for updating the entities.
200
+
201
+ The mechanism for decaying memory, prioritizing and updating entities is out of scope of this proposal.
202
+
203
+
204
+ ## deepset Cloud API
205
+ The Agent should be able to use pipelines deployed on deepset Cloud as a tool.
206
+ To this end, the text question needs to be send via REST API to
207
+ 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.
208
+
209
+ In the demo, the Agent will use this tool for question answering on indexed documents of the Haystack documentation,
210
+ such as documentation web pages or tutorials.
211
+
212
+
213
+ # Drawbacks
214
+
215
+ One of the main reasons why we should not work on implementing this proposal is that it is a rather large
216
+ undertaking requiring substantial resources. This naturally carries significant risks. We should carefully weigh
217
+ the pros and cons of tools we want to implement and prioritize them. The current priority criteria is that the tool
218
+ should be useful for the agents MVP, the majority of early adopters and that it should be relatively easy to
219
+ implement. We can always add more tools in the future.
220
+
221
+ Another priority guidance is the demo we intend to build. We want to build a demo that showcases the agent's
222
+ capabilities in a use case that is relevant to the majority of early adopters (current Haystack users).
223
+
224
+
225
+ # Alternatives
226
+
227
+ We also considered the following demo alternatives:
228
+
229
+ - Medical QA: We can build a demo that answers medical questions. This is a very interesting use case but also
230
+ fraught with risks. A question one might ask in such a demo is “Which antibiotic should I use for urinary tract infections?”.
231
+ A factoid-based QA system might (reasonably) return the answer “trimethoprim 200mg”. However, a “correct” answer is not
232
+ sufficient to translate into clinical use. There were other recent demos but they were not very successful.
233
+ See https://twitter.com/GlassHealthHQ/status/1620092094034620421 for more details.
234
+
235
+ - Public Healthcare QA: a bit less risky proposal than the medical QA. We can build a demo that answers questions about
236
+ healthy diet, cooking recipes, vitamines etc. This demo would use almost exactly the same tools as the main demo proposal
237
+ and we can potentially switch to this demo if needed.
238
+
239
+ - Financial Domain (earnings transcript): we can build a demo that answers questions about earnings transcripts. However,
240
+ 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.
241
+
242
+
243
+ # Adoption strategy
244
+
245
+ An adoption strategy for this proposal is not needed as much and the objective is to demo the capabilities of the agent
246
+ and inspire early adopters to use the agent and the main tools we are going to implement.
247
+
248
+
249
+ # Demo
250
+
251
+ See the Summary section for the demo description.
252
+
253
+ # How we teach this
254
+
255
+ We intend to use the demo to teach users about the agent's capabilities. We'll subsequently add more documentation about
256
+ core components used in the demo and the agent in general. This demo would be mainly used to promote Haystack Agents and
257
+ to generate interest in the agent.
258
+
259
+ # Unresolved questions
260
+
261
+ Optional, but suggested for first drafts. What parts of the design are still
262
+ TBD?
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4172-shaper-in-prompt-template.md ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: Shapers in Prompt Templates
2
+ - Decision driver: tstadel
3
+ - Start Date: 2023-02-15
4
+ - Proposal PR: (fill in after opening the PR)
5
+ - Github Issues or Discussion:
6
+ - spike: https://github.com/deepset-ai/haystack/pull/4061
7
+ - solved issues:
8
+ - https://github.com/deepset-ai/haystack/issues/3877
9
+ - https://github.com/deepset-ai/haystack/issues/4053
10
+ - https://github.com/deepset-ai/haystack/issues/4047
11
+
12
+ # Summary
13
+
14
+ 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:
15
+ - output: support Shapers in PromptTemplates to enable the user to define how the output to the prompt template should be shaped
16
+ - input: extend the prompt syntax to support the usage of functions that can be applied to input variables
17
+
18
+ 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.
19
+
20
+ # Basic example
21
+
22
+ A generative QA pipeline would be as easy as this:
23
+
24
+ ```python
25
+ from haystack import Pipeline
26
+ from haystack.document_store import InMemoryDocumentStore
27
+ from haystack.nodes import PromptNode, EmbeddingRetriever
28
+
29
+ document_store = InMemoryDocumentStore()
30
+ retriever = EmbeddingRetriever(document_store=document_store, ...)
31
+ pn = PromptNode(default_prompt_template="question-answering-with-references")
32
+
33
+ p = Pipeline()
34
+ p.add_node(component=retriever, name="Retriever", inputs=["Query"])
35
+ p.add_node(component=pn, name="Prompt", inputs=["Retriever"])
36
+ ```
37
+
38
+ As a result we get a pipeline that uses PromptNode as a drop-in replacement for Generators:
39
+
40
+ ```python
41
+ p.run(
42
+ query="What is the most popular drink?"
43
+ )
44
+ ```
45
+
46
+ ```python
47
+ {'answers': [<Answer {'answer': 'Potable water is the most popular drink, followed by tea and beer as stated in Document[5].', 'type': 'generative', 'score': None, 'context': None, 'offsets_in_document': None, 'offsets_in_context': None, 'document_ids': ['fcd62336fb380a69c2d655f8cd072995'], 'meta': {}}>],
48
+ 'invocation_context': {'query': 'What is the most popular drink?',
49
+ 'documents': [<Document: {'content': '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]', 'content_type': 'text', 'score': None, 'meta': {}, 'id_hash_keys': ['content'], 'embedding': None, 'id': 'fcd62336fb380a69c2d655f8cd072995'}>],
50
+ 'answers': [<Answer {'answer': 'Potable water is the most popular drink, followed by tea and beer as stated in Document[5].', 'type': 'generative', 'score': None, 'context': None, 'offsets_in_document': None, 'offsets_in_context': None, 'document_ids': ['fcd62336fb380a69c2d655f8cd072995'], 'meta': {}}>]},
51
+ '_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: ']}}},
52
+ 'root_node': 'Query',
53
+ 'params': {},
54
+ 'query': 'What is the most popular drink?',
55
+ 'documents': [<Document: {'content': '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]', 'content_type': 'text', 'score': None, 'meta': {}, 'id_hash_keys': ['content'], 'embedding': None, 'id': 'fcd62336fb380a69c2d655f8cd072995'}>],
56
+ 'node_id': 'PromptNode'}
57
+ ```
58
+
59
+ The corresponding prompt template would look like this (provided `join_documents` and `strings_to_answers` Shaper functions are extended a bit):
60
+
61
+ ```python
62
+ PromptTemplate(
63
+ name="question-answering-with-references",
64
+ prompt_text="Create a concise and informative answer (no more than 50 words) for a given question "
65
+ "based solely on the given documents. You must only use information from the given documents. "
66
+ "Use an unbiased and journalistic tone. Do not repeat text. Cite the documents using Document[number] notation. "
67
+ "If multiple documents contain the answer, cite those documents like ‘as stated in Document[number,number,etc]’. "
68
+ "If the documents do not contain the answer to the question, say that ‘answering is not possible given the available information.’\n"
69
+ "{join(documents, '\n', '\nDocument[$idx]: $content', {'\n': ' ', '[': '(', ']': ')'})} \n Question: {query}; Answer: ",
70
+ output_shapers=[
71
+ Shaper(
72
+ func="strings_to_answers",
73
+ inputs={"strings": "results", "documents": "documents"},
74
+ outputs=["answers"],
75
+ )
76
+ ],
77
+ output_variable="answers",
78
+ )
79
+ ```
80
+
81
+ 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
82
+
83
+ ```python
84
+ DELIMITER = "\n"
85
+ PATTERN = "$content" # parsable by StringTemplate using data from document.content, document.meta and the index of the document
86
+ CHAR_REPLACEMENT = {"[": "(", "}": ")"} # just an example what could be passed here
87
+ ```
88
+
89
+ would do.
90
+
91
+ 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).
92
+
93
+ # Motivation
94
+
95
+ Currently using PromptNode is a bit cumbersome as:
96
+ - 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
97
+ - 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.
98
+ - 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.
99
+
100
+
101
+ # Detailed design
102
+
103
+ ## General changes
104
+ PromptTemplate gets one new attribute: `output_shapers`. These are lists of Shaper objects that are applied to the output of the prompt.
105
+ PromptTemplate's syntax is extended to allow for the usage of shaping functions on input variables. These shaping functions are predefined.
106
+
107
+ ## Basic flow:
108
+ PromptNode calls `PromptTemplate.prepare` before executing the prompt. `PromptTemplate.prepare` applies the shaping functions (if present) to the arguments of the `invocation_context`.
109
+ PromptNode invokes the prompt on the prepared `invocation_context`.
110
+ PromptNode calls `PromptTemplate.post_process` after executing the prompt. `PromptTemplate.post_process` makes all `output_shapers` run on the `invocation_context`.
111
+
112
+ ## Shaping functions
113
+ 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.
114
+ 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).
115
+ 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`.
116
+ Here is a basic (and incomplete) example how the parsing logic could look like:
117
+
118
+ ```python
119
+
120
+ # template allowing basic list comprehensions to create the wanted string
121
+ template = """
122
+ Create a concise and informative answer (no more than 50 words) for a given question
123
+ based solely on the given documents. You must only use information from the given documents.
124
+ Use an unbiased and journalistic tone. Do not repeat text. Cite the documents using Document[number] notation.
125
+ If multiple documents contain the answer, cite those documents like ‘as stated in Document[number,number,etc]’.
126
+ If the documents do not contain the answer to the question, say that ‘answering is not possible given the available information.
127
+ {join(documents, new_line)} \n Question: {query}; Answer:
128
+ """
129
+
130
+ for group in re.findall(r'\{(.*?)\}', template):
131
+ if "(" in group and ")" in group:
132
+ function_to_call = group[:group.index("(")].strip()
133
+ variables_for_function = [var.strip() for var in group[group.index("(")+1:group.index(")")].split(",")]
134
+ print(f"Found function '{function_to_call}' with vars '{variables_for_function}'")
135
+ else:
136
+ print("Found single variable:", group)
137
+
138
+ # Returns
139
+ # >>> Found function 'join' with vars '['documents', 'new_line']'
140
+ # >>> Found single variable: query
141
+ ```
142
+
143
+ ## Prompt engineering with Haystack Pipelines
144
+ 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`.
145
+
146
+ ## Misc
147
+ Note, that `Shapers` are still usable in Pipelines as before.
148
+
149
+ # Drawbacks
150
+
151
+ Look at the feature from the other side: what are the reasons why we should _not_ work on it? Consider the following:
152
+
153
+ - What's the implementation cost, both in terms of code size and complexity? A good day
154
+ - Can the solution you're proposing be implemented as a separate package, outside of Haystack? No
155
+ - Does it teach people more about Haystack? No, but it makes it easier to use especially for beginners.
156
+ - How does this feature integrate with other existing and planned features? It doesn't change any existing features and should nicely integrate with agents.
157
+ - What's the cost of migrating existing Haystack pipelines (is it a breaking change?)? None
158
+
159
+ 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.
160
+
161
+ 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.
162
+
163
+ # Alternatives
164
+
165
+ 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.
166
+
167
+ 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.
168
+ # Adoption strategy
169
+
170
+ As the syntax for input variables in `PromptTemplate` changes we can do the following:
171
+ - raise an error if the old syntax is used and tell the user to use the new syntax
172
+ - support the old syntax for a while and raise a deprecation warning
173
+
174
+ # How we teach this
175
+
176
+ We should show how:
177
+ - predefined PromptTemplates can be used
178
+ - predefined PromptTemplates can be customized
179
+ - custom PromptTemplates can be created
180
+
181
+ # Unresolved questions
182
+
183
+ How does `OpenAIAnswerGenerator` make use of input shaping functions and output shapers?
184
+ - output shapers: it doesn't use them
185
+ - input shaping functions: it uses them if they are present. If not it uses its own default functions.
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4284-drop-basecomponent.md ADDED
@@ -0,0 +1,950 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: Drop `BaseComponent` and reimplement `Pipeline`.
2
+ - Decision driver: @ZanSara
3
+ - Start Date: 27/02/2023
4
+ - Proposal PR: #4284
5
+ - Github Issue or Discussion: #2807
6
+
7
+ # Summary
8
+
9
+ Haystack Pipelines are very powerful objects, but they still have a number of unnecessary limitations, by design and by implementation.
10
+
11
+ 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`.
12
+
13
+
14
+ # Motivation
15
+
16
+ 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.
17
+
18
+ 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:
19
+
20
+ - DAGs. DAGs are safe, but loops could enable many more usecases, like `Agents`.
21
+
22
+ - `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:
23
+ - https://github.com/deepset-ai/haystack/pull/2593
24
+ - https://github.com/deepset-ai/haystack/pull/2981#issuecomment-1207850632
25
+ - https://github.com/deepset-ai/haystack/issues/2999#issuecomment-1210382151
26
+
27
+ - `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.
28
+
29
+ - 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.
30
+
31
+ - `Pipeline`s are often required to have a `DocumentStore` _somewhere_ (see below), even in situation where it wouldn't be needed.
32
+ - For example, `Pipeline` has a `get_document_store()` method which iterates over all nodes looking for a `Retriever`.
33
+
34
+ - 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.
35
+
36
+ - 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.
37
+
38
+ In addition, there are a number of known bugs that makes the current Pipeline implementation hard to work with. Some of these include:
39
+
40
+ - Branching and merging logic is known to be buggy even where it's supported.
41
+ - Nodes can't be added twice to the same pipeline in different locations, limiting their reusability.
42
+ - 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.
43
+ - Being forced to use a schema for YAML validation makes impossible to validate the graph in advance.
44
+
45
+ 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:
46
+
47
+ - `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.
48
+ - 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.
49
+
50
+ This proposal tries to address all the above point by taking a radical stance with:
51
+
52
+ - 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.
53
+
54
+ - Dropping the concept of `BaseComponent` and introducing the much lighter concept of `Node` in its place.
55
+
56
+ - Define a clear contract between `Pipeline` and the `Node`s.
57
+
58
+ - Define a clear place for `DocumentStore`s with respect to `Pipeline`s that doesn't forcefully involve `Retriever`s.
59
+
60
+ - Redesign the YAML representation of `Pipeline`s.
61
+
62
+ # Basic example
63
+
64
+ 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.
65
+
66
+ 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
67
+
68
+ ## Simple example
69
+
70
+ This is a very simplified example that performs some mathematical operations. See below for more realistic examples.
71
+
72
+ ```python
73
+ from typing import Dict, Any, List, Tuple
74
+ from haystack.pipeline import Pipeline
75
+ from haystack.nodes import node
76
+
77
+ # A Haystack Node. See below for details about this contract.
78
+ # Crucial components are the @node decorator and the `run()` method
79
+ @node
80
+ class AddValue:
81
+ def __init__(self, add: int = 1, input_name: str = "value", output_name: str = "value"):
82
+ self.add = add
83
+ self.init_parameters = {"add": add}
84
+ self.inputs = [input_name]
85
+ self.outputs = [output_name]
86
+
87
+ def run(
88
+ self,
89
+ name: str,
90
+ data: List[Tuple[str, Any]],
91
+ parameters: Dict[str, Any],
92
+ stores: Dict[str, Any],
93
+ ):
94
+ my_parameters = parameters.get(name, {})
95
+ add = my_parameters.get("add", self.add)
96
+
97
+ for _, value in data:
98
+ value += add
99
+
100
+ return ({self.outputs[0]: value}, parameters)
101
+
102
+
103
+ @node
104
+ class Double:
105
+ def __init__(self, input_edge: str = "value"):
106
+ self.init_parameters = {"input_edge": input_edge}
107
+ self.inputs = [input_edge]
108
+ self.outputs = [input_edge]
109
+
110
+ def run(
111
+ self,
112
+ name: str,
113
+ data: List[Tuple[str, Any]],
114
+ parameters: Dict[str, Any],
115
+ stores: Dict[str, Any],
116
+ ):
117
+ for _, value in data:
118
+ value *= 2
119
+
120
+ return ({self.outputs[0]: value}, parameters)
121
+
122
+
123
+ pipeline = Pipeline()
124
+
125
+ # Nodes can be initialized as standalone objects.
126
+ # These instances can be added to the Pipeline in several places.
127
+ addition = AddValue(add=1)
128
+
129
+ # Nodes are added with a name and an node. Note the lack of references to any other node.
130
+ pipeline.add_node("first_addition", addition, parameters={"add": 3}) # Nodes can store default parameters per node.
131
+ pipeline.add_node("second_addition", addition) # Note that instances can be reused
132
+ pipeline.add_node("double", Double())
133
+
134
+ # Nodes are the connected as input node: [list of output nodes]
135
+ pipeline.connect(connect_from="first_addition", connect_to="double")
136
+ pipeline.connect(connect_from="double", connect_to="second_addition")
137
+
138
+ pipeline.draw("pipeline.png")
139
+
140
+ # Pipeline.run() accepts 'data' and 'parameters' only. Such dictionaries can contain
141
+ # anything, depending on what the first node(s) of the pipeline requires.
142
+ # Pipeline does not validate the input: the first node(s) should do so.
143
+ results = pipeline.run(
144
+ data={"value": 1},
145
+ parameters = {"second_addition": {"add": 10}} # Parameters can be passed at this stage as well
146
+ )
147
+ assert results == {"value": 18}
148
+ ```
149
+
150
+ The result of `Pipeline.draw()`:
151
+
152
+ ![image](images/4284-drop-basecomponent/pipeline.png)
153
+
154
+
155
+ ## Query Pipeline
156
+
157
+ 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
158
+
159
+
160
+ <details>
161
+ <summary>RetrieveByBM25</summary>
162
+
163
+ ```python
164
+ from typing import Dict, Any, List, Tuple
165
+
166
+ import logging
167
+
168
+ from haystack.data import TextQuery
169
+ from haystack.nodes import node
170
+
171
+
172
+ @node
173
+ class RetrieveByBM25:
174
+ """
175
+ Simple dummy BM25 Retriever that works with MemoryStore.
176
+ Supports batch processing.
177
+ """
178
+ def __init__(self,
179
+ input_name: str = "query",
180
+ output_name: str = "documents_by_query",
181
+ default_store: str = "documents",
182
+ default_top_k: int = 10
183
+ ):
184
+ self.default_store = default_store
185
+ self.default_top_k = default_top_k
186
+
187
+ # Pipelne's contract:
188
+ self.init_parameters = {
189
+ "input_name": input_name,
190
+ "output_name": output_name,
191
+ "default_store": default_store,
192
+ "default_top_k": default_top_k
193
+ }
194
+ self.inputs = [input_name]
195
+ self.outputs = [output_name]
196
+
197
+ def run(
198
+ self,
199
+ name: str,
200
+ data: List[Tuple[str, Any]],
201
+ parameters: Dict[str, Any],
202
+ stores: Dict[str, Any],
203
+ ):
204
+ my_parameters = parameters.get(name, {})
205
+ store_name = my_parameters.get("store", self.default_store)
206
+ top_k = my_parameters.get("top_k", self.default_top_k)
207
+
208
+ # This can be done safely, because Nodes expect the Pipeline to respect their contract.
209
+ # Errors here are Pipeline's responsibility, so Nodes should not care.
210
+ queries = data[0][1]
211
+
212
+ # Batch support is not the pipeline's business, but the node's
213
+ if isinstance(queries, TextQuery):
214
+ queries = [queries]
215
+ elif queries and not (
216
+ isinstance(queries, list) and
217
+ all(isinstance(query, TextQuery) for query in queries)
218
+ ):
219
+ raise ValueError(f"'{data[0][0]}' can only contain TextQuery objects. '{data[0][0]}' contains: {queries}")
220
+
221
+ if not store_name in stores.keys():
222
+ raise ValueError(f"No store called '{store_name}'.")
223
+
224
+ results = stores[store_name].get_relevant_documents(queries=queries, top_k=top_k)
225
+
226
+ return ({self.outputs[0]: results}, parameters)
227
+ ```
228
+
229
+ </details>
230
+
231
+
232
+ <details>
233
+ <summary>ReadByTransformers</summary>
234
+
235
+ ```python
236
+ from typing import Dict, Any, List, Tuple
237
+
238
+ from haystack.data import TextAnswer, Span
239
+ from haystack import node
240
+
241
+
242
+ @node
243
+ class ReadByTransformers:
244
+ """
245
+ Simple dummy Transformers Reader.
246
+ Supports batch processing.
247
+ """
248
+ def __init__(self,
249
+ model_name_or_path: str,
250
+ default_top_k: int = 5,
251
+ default_no_answer: bool = True,
252
+ default_max_seq_len: int = 256,
253
+ default_doc_stride: int = 128,
254
+ default_batch_size: int = 16,
255
+ default_context_window_size: int = 70,
256
+ input_name: str = "documents_by_query",
257
+ output_name: str = "answers_by_query",
258
+ ):
259
+ self.model_name_or_path = model_name_or_path
260
+ self.default_top_k = default_top_k
261
+ self.default_no_answer = default_no_answer
262
+ self.default_max_seq_len = default_max_seq_len
263
+ self.default_doc_stride = default_doc_stride
264
+ self.default_batch_size = default_batch_size
265
+ self.default_context_window_size = default_context_window_size
266
+ self.model = None
267
+
268
+ self.init_parameters = {
269
+ "input_name": input_name,
270
+ "output_name": output_name,
271
+ "model_name_or_path": model_name_or_path,
272
+ "default_top_k": default_top_k,
273
+ "default_no_answer": default_no_answer,
274
+ "default_max_seq_len": default_max_seq_len,
275
+ "default_doc_stride": default_doc_stride,
276
+ "default_batch_size": default_batch_size,
277
+ "default_context_window_size": default_context_window_size,
278
+ }
279
+ self.inputs = [input_name]
280
+ self.outputs = [output_name]
281
+
282
+ def warm_up(self):
283
+ try:
284
+ from transformers import pipeline
285
+ except Exception as e:
286
+ raise ImportError("Can't import 'transformers': this node won't work.") from e
287
+
288
+ if not self.model:
289
+ self.model = pipeline(
290
+ "question-answering",
291
+ model=self.model_name_or_path,
292
+ )
293
+
294
+ def run(
295
+ self,
296
+ name: str,
297
+ data: List[Tuple[str, Any]],
298
+ parameters: Dict[str, Any],
299
+ stores: Dict[str, Any],
300
+ ):
301
+ my_parameters = parameters.get(name, {})
302
+ top_k = my_parameters.get("top_k", self.default_top_k)
303
+ no_answer = my_parameters.get("no_answer", self.default_no_answer)
304
+ max_seq_len = my_parameters.get("max_seq_len", self.default_max_seq_len)
305
+ doc_stride = my_parameters.get("doc_stride", self.default_doc_stride)
306
+ batch_size = my_parameters.get("batch_size", self.default_batch_size)
307
+ context_window_size = my_parameters.get("context_window_size", self.default_context_window_size)
308
+
309
+ documents_for_queries = data[0][1]
310
+
311
+ inputs = []
312
+ for query, documents in documents_for_queries.items():
313
+ inputs.extend([
314
+ self.model.create_sample(question=query.content, context=doc.content) # type: ignore
315
+ for doc in documents
316
+ ])
317
+
318
+ # Inference
319
+ predictions = self.model( # type: ignore
320
+ inputs,
321
+ top_k=top_k,
322
+ handle_impossible_answer=no_answer,
323
+ max_seq_len=max_seq_len,
324
+ doc_stride=doc_stride,
325
+ batch_size=batch_size,
326
+ )
327
+
328
+ # Builds the TextAnswer object
329
+ answers_for_queries = {query: [] for query in documents_for_queries.keys()}
330
+ for query, documents in documents_for_queries.items():
331
+ documents = list(documents) # FIXME consume here the iterator for now
332
+ docs_len = len(documents)
333
+ relevant_predictions = predictions[:docs_len]
334
+ predictions = predictions[docs_len:]
335
+
336
+ for document, prediction in zip(documents, relevant_predictions):
337
+ if prediction.get("answer", None):
338
+ context_start = max(0, prediction["start"] - context_window_size)
339
+ context_end = min(len(document.content), prediction["end"] + context_window_size)
340
+ answers_for_queries[query].append(
341
+ TextAnswer(
342
+ content=prediction["answer"],
343
+ score=prediction["score"],
344
+ context=document.content[context_start:context_end],
345
+ offset_in_document=Span(start=prediction["start"], end=prediction["end"]),
346
+ offset_in_context=Span(start=prediction["start"] - context_start, end=prediction["end"] - context_start),
347
+ document_id=document.id,
348
+ meta=document.meta,
349
+ )
350
+ )
351
+ elif no_answer:
352
+ answers_for_queries[query].append(
353
+ TextAnswer(
354
+ content="",
355
+ score=prediction["score"],
356
+ meta=document.meta,
357
+ )
358
+ )
359
+ answers_for_queries[query] = sorted(answers_for_queries[query], reverse=True)[:top_k]
360
+ return ({self.outputs[0]: answers_for_queries}, parameters)
361
+ ```
362
+
363
+ </details>
364
+
365
+ ```python
366
+ import json
367
+ from pathlib import Path
368
+
369
+ from haystack.pipeline import Pipeline
370
+ from haystack.stores import MemoryDocumentStore
371
+ from haystack.data import TextQuery, TextDocument
372
+ from haystack.nodes import RetrieveByBM25, ReadByTransformers
373
+
374
+ import logging
375
+
376
+ logging.basicConfig(level=logging.DEBUG)
377
+
378
+
379
+ def test_pipeline():
380
+ document_store = MemoryDocumentStore()
381
+ document_store.write_documents([
382
+ TextDocument(content="My name is Anna and I live in Paris."),
383
+ TextDocument(content="My name is Serena and I live in Rome."),
384
+ TextDocument(content="My name is Julia and I live in Berlin."),
385
+ ])
386
+ pipeline = Pipeline()
387
+ pipeline.connect_store("my_documents", document_store)
388
+ pipeline.add_node("retriever", RetrieveByBM25(default_store="my_documents"))
389
+ pipeline.add_node("reader", ReadByTransformers(model_name_or_path="distilbert-base-uncased-distilled-squad"))
390
+
391
+ pipeline.connect(connect_from="retriever", connect_to="reader")
392
+ pipeline.draw("query_pipeline.png")
393
+
394
+ results = pipeline.run({"query": TextQuery(content="Who lives in Berlin?")})
395
+
396
+ print(results)
397
+
398
+
399
+ if __name__ == "__main__":
400
+ test_pipeline()
401
+ ```
402
+ Pipeline diagram:
403
+
404
+ ![image](images/4284-drop-basecomponent/query_pipeline.png)
405
+
406
+ Output:
407
+ ```
408
+ {
409
+ "answers_by_query": {
410
+ "TextQuery('Who lives in Berlin?')": [
411
+ "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')"
412
+ ]
413
+ }
414
+ }
415
+ ```
416
+
417
+ **IMPORTANT NOTE:** This is an example meant to showcase the concept. However, it has a major flaw: it is coupling queries and documents tightly.
418
+
419
+ 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.
420
+
421
+ 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.
422
+
423
+ 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.
424
+
425
+ # Detailed design
426
+
427
+ 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
428
+
429
+ ## The Pipeline API
430
+
431
+ These are the core features that drove the design of the revised Pipeline API:
432
+
433
+ - An execution graph that is more flexible than a DAG.
434
+ - A clear place for `DocumentStore`s
435
+
436
+ Therefore, the revised Pipeline object has the following API:
437
+
438
+ - Core functions:
439
+ - `__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.
440
+ - `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.
441
+ - `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.
442
+ - Graph building:
443
+ - `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.
444
+ - `get_node(name)`: returns the node's information stored in the graph
445
+ - `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.
446
+ - Docstore management:
447
+ - `add_store(name, store)`: adds a DocumentStore to the stores that are passed down to the nodes through the `stores` variable.
448
+ - `list_stores()`: returns all connected stores.
449
+ - `get_store(name)`: returns a specific document store by name.
450
+
451
+ Example pipeline topologies supported by the new implementation (images taken from the test suite):
452
+
453
+ <details>
454
+ <summary>Merging pipeline</summary>
455
+
456
+ ![image](images/4284-drop-basecomponent/merging_pipeline.png)
457
+
458
+ 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`.
459
+
460
+ </details>
461
+
462
+ <details>
463
+ <summary>Branching pipeline with branch skipping</summary>
464
+
465
+ ![image](images/4284-drop-basecomponent/decision_pipeline.png)
466
+
467
+ 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`.
468
+
469
+ </details>
470
+
471
+ <details>
472
+ <summary>Branching pipeline with parallel branch execution</summary>
473
+
474
+ ![image](images/4284-drop-basecomponent/parallel_branches_pipeline.png)
475
+
476
+ 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`.
477
+
478
+ </details>
479
+
480
+ <details>
481
+ <summary>Branching pipeline with branch skipping and merge</summary>
482
+
483
+ ![image](images/4284-drop-basecomponent/decision_and_merge_pipeline.png)
484
+
485
+ 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`.
486
+
487
+ </details>
488
+
489
+ <details>
490
+ <summary>Looping pipeline</summary>
491
+
492
+ ![image](images/4284-drop-basecomponent/looping_pipeline.png)
493
+
494
+ This is a pipeline with a loop and a counter that statefully counts how many times it has been called.
495
+
496
+ 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.
497
+
498
+ </details>
499
+
500
+ <details>
501
+ <summary>Looping pipeline with merge</summary>
502
+
503
+ ![image](images/4284-drop-basecomponent/looping_and_merge_pipeline.png)
504
+
505
+ 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`.
506
+
507
+ </details>
508
+
509
+ <details>
510
+ <summary>Arbitrarily complex pipeline</summary>
511
+
512
+ ![image](images/4284-drop-basecomponent/complex_pipeline.png)
513
+
514
+ This is an example of how complex Pipelines the new objects can support. This pipeline combines all cases above:
515
+ - Multiple inputs
516
+ - Multiple outputs
517
+ - Decision nodes and branches skipped due to a selection
518
+ - Distribution nodes and branches executed in parallel
519
+ - Merge nodes where it's unclear how many edges will actually carry values
520
+ - Merge nodes with repeated inputs (`sum` takes three `value` edges) or distinct inputs (`diff` takes `value` and `sum`)
521
+ - Loops along a branch
522
+ </details>
523
+
524
+ 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
525
+
526
+ ## The Node contract
527
+
528
+ A Haystack node is any class that abides the following contract:
529
+
530
+ ```python
531
+ # This decorator does very little, but is necessary for Pipelines to recognize
532
+ # this class as a Haystack node. Check its implementation for details.
533
+ @node
534
+ class MyNode:
535
+
536
+ def __init__(self, model_name: str: "deepset-ai/a-model-name"):
537
+ """
538
+ Haystack nodes should have an `__init__` method where they define:
539
+
540
+ - `self.inputs = [<input_name(s)>]`:
541
+ A list with all the edges they can possibly receive input from
542
+
543
+ - `self.outputs = [<output_name(s)>]`:
544
+ A list with the edges they might possibly produce as output
545
+
546
+ - `self.init_parameters = {<init parameters>}`:
547
+ Any state they wish to be persisted in their YAML serialization.
548
+ These values will be given to the `__init__` method of a new instance
549
+ when the pipeline is deserialized.
550
+
551
+ The `__init__` must be extremely lightweight, because it's a frequent
552
+ operation during the construction and validation of the pipeline. If a node
553
+ has some heavy state to initialize (models, backends, etc...) refer to the
554
+ `warm_up()` method.
555
+ """
556
+ # Lightweight state can be initialized here, for example storing the model name
557
+ # to be loaded later. See self.warm_up()
558
+ self.model = None
559
+ self.model_name = model_name
560
+ self.how_many_times_have_I_been_called = 0
561
+
562
+ # Contract - all three are mandatory.
563
+ self.init_parameters = {"model_name": model_name}
564
+ self.inputs = ["input_name"]
565
+ self.outputs = ["output_name"]
566
+
567
+ def warm_up(self):
568
+ """
569
+ Optional method.
570
+
571
+ This method is called by Pipeline before the graph execution.
572
+ Make sure to avoid double-initializations, because Pipeline will not keep
573
+ track of which nodes it called `warm_up` on.
574
+ """
575
+ if not self.model:
576
+ self.model = AutoModel.load_from_pretrained(self.model_name)
577
+
578
+ def run(
579
+ self,
580
+ name: str,
581
+ data: List[Tuple[str, Any]],
582
+ parameters: Dict[str, Any],
583
+ stores: Dict[str, Any],
584
+ ):
585
+ """
586
+ Mandatory method.
587
+
588
+ This is the method where the main functionality of the node should be carried out.
589
+ It's called by `Pipeline.run()`, which passes the following parameters to it:
590
+
591
+ - `name: str`: the name of the node. Allows the node to find its own parameters in the `parameters` dictionary (see below).
592
+
593
+ - `data: List[Tuple[str, Any]]`: the input data.
594
+ Pipeline guarantees that the following assert always passes: `assert self.inputs == [name for name, value in data]`,
595
+ which means that:
596
+ - `data` is of the same length as `self.inputs`.
597
+ - `data` contains one tuple for each string stored in `self.inputs`.
598
+ - no guarantee is given on the values of these tuples: notably, if there was a decision node upstream, some values might be `None`.
599
+ For example, if a node declares `self.inputs = ["value", "value"]` (think of a Sum node), `data` might look like:
600
+ - `[("value", 1), ("value", 10)]`
601
+ - `[("value", None), ("value", 10)]`
602
+ - `[("value", None), ("value", None)]`, or even
603
+ - `[("value", 1), ("value", ["something", "unexpected"])]`
604
+ but it will never look like:
605
+ - `[("value", 1), ("value", 10), ("value", 100)]`,
606
+ - `[("value": 15)]` or
607
+ - `[("value": 15), ("unexpected", 10)]`.
608
+
609
+ - `parameters: Dict[str, Dict[str, Any]]`: a dictionary of dictionaries with all the parameters for all nodes.
610
+ Note that all nodes have access to all parameters for all other nodes: this might come handy to nodes like `Agent`s, that
611
+ want to influence the behavior of nodes downstream.
612
+ Nodes can access their own parameters using `name`, but they must not assume their name is present in the dictionary.
613
+ Therefore the best way to get the parameters is with `my_parameters = parameters.get(name, {})`
614
+
615
+ - `stores`: a dictionary of all the (Document)Stores connected to this pipeline.
616
+
617
+ Pipeline expect the output of this function to be a tuple in the following format:
618
+
619
+ `( {edge: value for edge in <subset of self.outputs>}, {the parameters dictionary})
620
+
621
+ Which means that:
622
+ - Nodes are not forced to produce output on all the expected outputs: for example nodes taking a decision, like classifiers,
623
+ can produce output on a subset of the expected output edges and Pipeline will figure out the rest.
624
+ - Nodes must not add any key in the data dictionary that is not present in `self.outputs`,
625
+ - Nodes can alter the content of `parameters` and their changes will be propagated downstream.
626
+ """
627
+ self.how_many_times_have_I_been_called += 1
628
+
629
+ value = data[0][1]
630
+ 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}")
631
+
632
+ return ({self.outputs[0]: value}, parameters)
633
+ ```
634
+
635
+ This contract is stored in the docstring of `@node` and acts as the single source of truth.
636
+
637
+ Note how there are a few fundamental shifts from the old concept of pipelines and nodes:
638
+
639
+ - There's no base class for nodes anymore. A node is whatever object is decorated with `@node`.
640
+
641
+ - 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.
642
+
643
+ - 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.
644
+ - For example, if `node_a` outputs `value_1` and `value_2`, both these edges can be given to a `sum` node.
645
+
646
+ - There's no more naming ambiguity between nodes and components.
647
+
648
+ ### Nodes discovery logic
649
+
650
+ 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.
651
+
652
+ 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.
653
+
654
+ Name collisions are handled by prefixing the node name with the name of the module it was imported from.
655
+
656
+ ## Validation
657
+
658
+ 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.
659
+
660
+ 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.
661
+
662
+ For example, let's imagine we have two nodes with the following I/O declared:
663
+
664
+ ```python
665
+ @node
666
+ class NodeA:
667
+
668
+ def __init__(self):
669
+ self.inputs = ["input"]
670
+ self.outputs = ["intermediate_value"]
671
+
672
+ def run(self):
673
+ pass
674
+
675
+ @node
676
+ class NodeB:
677
+
678
+ def __init__(self):
679
+ self.inputs = ["intermediate_value"]
680
+ self.outputs = ["output"]
681
+
682
+ def run(self):
683
+ pass
684
+ ```
685
+
686
+ This is the behavior of `Pipeline.connect()`:
687
+
688
+ ```python
689
+ pipeline.connect('node_a', 'node_b')
690
+ # Succeeds: no output
691
+
692
+ pipeline.connect('node_a', 'node_a')
693
+ # Traceback (most recent call last):
694
+ # File "/home/sara/work/haystack-2/example.py", line 29, in <module>
695
+ # pipeline.connect('node_a', 'node_a')
696
+ # File "/home/sara/work/haystack-2/new-haystack/haystack/pipeline/pipeline.py", line 224, in connect
697
+ # raise PipelineConnectError(
698
+ # 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.
699
+ # Upstream node 'node_a' declared these outputs:
700
+ # - intermediate_value (free)
701
+ # Downstream node 'node_a' declared these inputs:
702
+ # - input (free)
703
+
704
+ pipeline.connect('node_b', 'node_a')
705
+ # Traceback (most recent call last):
706
+ # File "/home/sara/work/haystack-2/example.py", line 29, in <module>
707
+ # pipeline.connect('node_b', 'node_a')
708
+ # File "/home/sara/work/haystack-2/new-haystack/haystack/pipeline/pipeline.py", line 224, in connect
709
+ # raise PipelineConnectError(
710
+ # haystack.pipeline._utils.PipelineConnectError: Cannot connect 'node_b' with 'node_a' with an edge named 'output': their declared inputs and outputs do not match.
711
+ # Upstream node 'node_b' declared these outputs:
712
+ # - output (free)
713
+ # Downstream node 'node_a' declared these inputs:
714
+ # - input (free)
715
+ ```
716
+
717
+ 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).
718
+
719
+ 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.
720
+
721
+ 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.
722
+
723
+ Other features planned for addition are:
724
+ - automatically connect nodes if matching edges are found, even if the match is partial
725
+ - double check for unconnected nodes and edges
726
+
727
+ ### Parameters hierarchy
728
+
729
+ Parameters can be passed to nodes at several stages, and they have different priorities. Here they're listed from least priority to top priority.
730
+
731
+ 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.
732
+ 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
733
+ 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.
734
+ 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.
735
+
736
+ Example:
737
+
738
+ ```python
739
+
740
+ class Node:
741
+ def __init__(self, value_1: int = 1, value_2: int = 1, value_3: int = 1, value_4: int = 1):
742
+ ...
743
+
744
+ node = Node(value_2=2, value_3=2, value_4=2)
745
+ pipeline = Pipeline()
746
+ pipeline.add_node("node", node, parameters={"value_3": 3, "value_4": 3})
747
+ ...
748
+ pipeline.run(data={...}, parameters={"node": {"value_4": 4}})
749
+
750
+ # Node will receive {"value_1": 1, "value_2": 2, "value_3": 3,"value_4": 4}
751
+ ```
752
+
753
+ ### Debug mode
754
+
755
+ The strategy towards debugging:
756
+
757
+ - Pipelines are aware of debug mode, Nodes aren't.
758
+ - Pipeline will produce debug output entirely through machine-readable logs.
759
+
760
+ 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).
761
+
762
+ 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.
763
+
764
+ ### Evaluation
765
+
766
+ 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.
767
+
768
+ ### Pipeline Serialization
769
+
770
+ _(Disclaimer: no draft implementation available yet)_
771
+
772
+ 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.
773
+
774
+ In code, saving and loading pipelines will look like this:
775
+
776
+ ```python
777
+ from haystack.pipelines import Pipeline, save_pipelines, load_pipelines
778
+
779
+ query_pipeline = Pipeline()
780
+ indexing_pipeline = Pipeline()
781
+ # .. assemble the pipelines ...
782
+
783
+ # Save the pipelines
784
+ save_pipelines(
785
+ pipelines={
786
+ "query": query_pipeline,
787
+ "indexing": indexing_pipeline,
788
+ },
789
+ path="my_pipelines.json",
790
+ writer=json.dumps
791
+ )
792
+
793
+ # Load the pipelines
794
+ new_pipelines = load_pipelines(
795
+ path="my_pipelines.json",
796
+ reader=json.loads
797
+ )
798
+
799
+ assert new_pipelines["query"] == query_pipeline
800
+ assert new_pipelines["indexing"] == indexing_pipeline
801
+ ```
802
+
803
+ 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.
804
+
805
+ This is how the resulting file will look like, assuming a JSON writer was chosen.
806
+
807
+ `my_pipeline.json`
808
+
809
+ ```json
810
+ {
811
+ # A list of "dependencies" for the application.
812
+ # Used to ensure all external nodes are present when loading.
813
+ "dependencies" : [
814
+ "haystack == 2.0.0",
815
+ "my_custom_node_module == 0.0.1",
816
+ ],
817
+
818
+ # Stores are defined here, outside single pipeline graphs.
819
+ # All pipelines have access to all these docstores.
820
+ "stores": {
821
+ # Nodes will be able to access them by the name defined here,
822
+ # in this case `my_first_store` (see the retrievers below).
823
+ "my_first_store": {
824
+ # class_name is mandatory
825
+ "class_name": "InMemoryDocumentStore",
826
+ # Then come all the additional parameters for the store
827
+ "use_bm25": true
828
+ },
829
+ "my_second_store": {
830
+ "class_name": "InMemoryDocumentStore",
831
+ "use_bm25": false
832
+ }
833
+ },
834
+
835
+ # Nodes are defined here, outside single pipeline graphs as well.
836
+ # All pipelines can use these nodes. Instances are re-used across
837
+ # Pipelines if they happen to share a node.
838
+ "nodes": {
839
+ # In order to reuse an instance across multiple nodes, instead
840
+ # of a `class_name` there should be a pointer to another node.
841
+ "my_sparse_retriever": {
842
+ # class_name is mandatory, unless it's a pointer to another node.
843
+ "class_name": "BM25Retriever",
844
+ # Then come all the additional init parameters for the node
845
+ "store_name": "my_first_store",
846
+ "top_k": 5
847
+ },
848
+ "my_dense_retriever": {
849
+ "class_name": "EmbeddingRetriever",
850
+ "model_name": "deepset-ai/a-model-name",
851
+ "store_name": "my_second_store",
852
+ "top_k": 5
853
+ },
854
+ "my_ranker": {
855
+ "class_name": "Ranker",
856
+ "inputs": ["documents", "documents"],
857
+ "outputs": ["documents"],
858
+ },
859
+ "my_reader": {
860
+ "class_name": "Reader",
861
+ "model_name": "deepset-ai/another-model-name",
862
+ "top_k": 3
863
+ }
864
+ },
865
+
866
+ # Pipelines are defined here. They can reference all nodes above.
867
+ # All pipelines will get access to all docstores
868
+ "pipelines": {
869
+ "sparse_question_answering": {
870
+ # Mandatory list of edges. Same syntax as for `Pipeline.connect()`
871
+ "edges": [
872
+ ("my_sparse_retriever", ["reader"])
873
+ ],
874
+ # To pass some parameters at the `Pipeline.add_node()` stage, add them here.
875
+ "parameters": {
876
+ "my_sparse_retriever": {
877
+ "top_k": 10
878
+ }
879
+ },
880
+ # Metadata can be very valuable for dC and to organize larger Applications
881
+ "metadata": {
882
+ "type": "question_answering",
883
+ "description": "A test pipeline to evaluate Sparse QA.",
884
+ "author": "ZanSara"
885
+ },
886
+ # Other `Pipeline.__init__()` parameters
887
+ "max_allowed_loops": 10,
888
+ },
889
+ "dense_question_answering": {
890
+ "edges": [
891
+ ("my_dense_retriever", ["reader"])
892
+ ],
893
+ "metadata": {
894
+ "type": "question_answering",
895
+ "description": "A test pipeline to evaluate Sparse QA.",
896
+ "author": "an_intern"
897
+ }
898
+ },
899
+ "hybrid_question_answering": {
900
+ "edges": [
901
+ ("my_sparse_retriever", ["ranker"]),
902
+ ("my_dense_retriever", ["ranker"]),
903
+ ("ranker", ["reader"]),
904
+ ],
905
+ "metadata": {
906
+ "type": "question_answering",
907
+ "description": "A test pipeline to evaluate Hybrid QA.",
908
+ "author": "the_boss"
909
+ }
910
+ }
911
+ }
912
+ }
913
+ ```
914
+
915
+ # Open questions
916
+
917
+ None left.
918
+
919
+ # Drawbacks
920
+
921
+ There are a number of drawbacks about the proposed approach:
922
+
923
+ - 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.
924
+
925
+ - Migration is going to be far from straightforward for the users: see "Adoption strategy".
926
+
927
+ - 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.
928
+
929
+ - 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.
930
+
931
+ - 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.
932
+
933
+ ## Known limitations
934
+
935
+ - **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.
936
+
937
+ # Adoption strategy
938
+
939
+ 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.
940
+
941
+ This proposal is best thought as part of the design of Haystack 2.0.
942
+
943
+ ## Rollout process
944
+
945
+ 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.
946
+
947
+ 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.
948
+ 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.
949
+
950
+ 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.
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/4370-documentstores-and-retrievers.md ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: `DocumentStores` and `Retrievers`
2
+ - Decision driver: @ZanSara
3
+ - Start Date: 2023-03-09
4
+ - Proposal PR: 4370
5
+ - Github Issue or Discussion: (only if available, link the original request for this change)
6
+
7
+ # Summary
8
+
9
+ 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`.
10
+
11
+ 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.
12
+
13
+ In this proposal we outline a reviewed design of the same concept.
14
+
15
+ Note: these stores are designed to work **only** alongside Haystack 2.0 Pipelines (see https://github.com/deepset-ai/haystack/pull/4284)
16
+
17
+ # Motivation
18
+
19
+ Current `DocumentStore` face several issues mostly due to their organic growth. Some of them are:
20
+
21
+ - `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.
22
+
23
+ - `DocumentStore`s tend to bring in complex dependencies, so less used stores should be easy to decouple into external packages at need.
24
+
25
+ # Basic example
26
+
27
+ 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.
28
+
29
+ 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.
30
+
31
+ For example, this is how embedding-based retrieval would look like:
32
+
33
+ ```python
34
+ from haystack import Pipeline
35
+ from haystack.nodes import (
36
+ TxtConverter,
37
+ PreProcessor,
38
+ DocumentWriter,
39
+ DocumentEmbedder,
40
+ StringEmbedder,
41
+ MemoryRetriever,
42
+ Reader,
43
+ )
44
+ from haystack.document_stores import MemoryDocumentStore
45
+
46
+ docstore = MemoryDocumentStore()
47
+
48
+ indexing_pipe = Pipeline()
49
+ indexing_pipe.add_store("document_store", docstore)
50
+ indexing_pipe.add_node("txt_converter", TxtConverter())
51
+ indexing_pipe.add_node("preprocessor", PreProcessor())
52
+ indexing_pipe.add_node("embedder", DocumentEmbedder(model_name="deepset/model-name"))
53
+ indexing_pipe.add_node("writer", DocumentWriter(store="document_store"))
54
+ indexing_pipe.connect("txt_converter", "preprocessor")
55
+ indexing_pipe.connect("preprocessor", "embedder")
56
+ indexing_pipe.connect("embedder", "writer")
57
+
58
+ indexing_pipe.run(...)
59
+
60
+ query_pipe = Pipeline()
61
+ query_pipe.add_store("document_store", docstore)
62
+ query_pipe.add_node("embedder", StringEmbedder(model_name="deepset/model-name"))
63
+ query_pipe.add_node("retriever", MemoryRetriever(store="document_store", retrieval_method="embedding"))
64
+ query_pipe.add_node("reader", Reader(model_name="deepset/model-name"))
65
+ query_pipe.connect("embedder", "retriever")
66
+ query_pipe.connect("retriever", "reader")
67
+
68
+ results = query_pipe.run(...)
69
+ ```
70
+
71
+ Note a few key differences with the existing Haystack process:
72
+
73
+ - 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.
74
+
75
+ - 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").
76
+
77
+ - 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`.
78
+
79
+
80
+ # Detailed design
81
+
82
+ ## `DocumentStore` contract
83
+
84
+ Here is a summary of the basic contract that all `DocumentStore`s are expected to follow.
85
+
86
+ ```python
87
+ class MyDocumentStore:
88
+
89
+ def count_documents(self, **kwargs) -> int:
90
+ ...
91
+
92
+ def filter_documents(self, filters: Dict[str, Any], **kwargs) -> List[Document]:
93
+ ...
94
+
95
+ def write_documents(self, documents: List[Document], **kwargs) -> None:
96
+ ...
97
+
98
+ def delete_documents(self, ids: List[str], **kwargs) -> None:
99
+ ...
100
+ ```
101
+
102
+ 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.
103
+
104
+ Note also how the concept of `index` is not present anymore, as it it mostly ES-specific.
105
+
106
+ For example, a `MemoryDocumentStore` could offer the following API:
107
+
108
+ ```python
109
+ class MemoryDocumentStore:
110
+
111
+ def filter_documents(self, filters: Dict[str, Any], **kwargs) -> List[Document]:
112
+ ...
113
+
114
+ def write_documents(self, documents: List[Document], **kwargs) -> None:
115
+ ...
116
+
117
+ def delete_documents(self, ids: List[str], **kwargs) -> None:
118
+ ...
119
+
120
+ def bm25_retrieval(
121
+ self,
122
+ queries: List[str], # Note: takes strings!
123
+ filters: Optional[Dict[str, Any]] = None,
124
+ top_k: int = 10
125
+ ) -> List[List[Document]]:
126
+ ...
127
+
128
+ def vector_similarity_retrieval(
129
+ self,
130
+ queries: List[np.array], # Note: takes embeddings!
131
+ filters: Optional[Dict[str, Any]] = None,
132
+ top_k: int = 10
133
+ ) -> List[List[Document]]:
134
+ ...
135
+
136
+ def knn_retrieval(
137
+ self,
138
+ queries: List[np.array], # Note: takes embeddings!
139
+ filters: Optional[Dict[str, Any]] = None,
140
+ top_k: int = 10
141
+ ) -> List[List[Document]]:
142
+ ...
143
+ ```
144
+
145
+ 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.
146
+
147
+ Here is, for comparison, an example implementation of a `DocumentWriter`, a document-store agnostic node.
148
+
149
+ ```python
150
+ @node
151
+ class DocumentWriter:
152
+
153
+ def __init__(self, inputs=['documents'], stores=["documents"]):
154
+ self.store_names = stores
155
+ self.inputs = inputs
156
+ self.outputs = []
157
+ self.init_parameters = {"inputs": inputs, "stores": stores}
158
+
159
+ def run(
160
+ self,
161
+ name: str,
162
+ data: List[Tuple[str, Any]],
163
+ parameters: Dict[str, Dict[str, Any]]
164
+ ) -> Dict[str, Any]:
165
+ writer_parameters = parameters.get(name, {})
166
+ stores = writer_parameters.pop("stores", {})
167
+
168
+ all_documents = []
169
+ for _, documents in data:
170
+ all_documents += documents
171
+
172
+ for store_name in self.store_names:
173
+ stores[store_name].write_documents(documents=all_documents, **writer_parameters)
174
+
175
+ return ({}, parameters)
176
+ ```
177
+ 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.
178
+
179
+ Here instead we can see an example implementation of a `MemoryRetriever`, a document-store aware node.
180
+
181
+ ```python
182
+ @node
183
+ class MemoryRetriever:
184
+
185
+ def __init__(self, inputs=['query'], output="documents", stores=["documents"]):
186
+ self.store_names = stores
187
+ self.inputs = inputs
188
+ self.outputs = [output]
189
+ self.init_parameters = {"inputs": inputs, "output": output "stores": stores}
190
+
191
+ def run(
192
+ self,
193
+ name: str,
194
+ data: List[Tuple[str, Any]],
195
+ parameters: Dict[str, Dict[str, Any]]
196
+ ) -> Dict[str, Any]:
197
+
198
+ retriever_parameters = parameters.get(name, {})
199
+ stores = retriever_parameters.pop("stores", {})
200
+ retrieval_method = retriever_parameters.pop("retrieval_method", "bm25")
201
+
202
+ for store_name in self.store_names:
203
+ if not isinstance(stores[store_name], MemoryStore):
204
+ raise ValueError("MemoryRetriever only works with MemoryDocumentStore.")
205
+
206
+ if retrieval_method == "bm25":
207
+ documents = stores[store_name].bm25_retrieval(queries=queries, **retriever_parameters)
208
+ elif retrieval_method == "embedding":
209
+ documents = stores[store_name].vector_similarity_retrieval(queries=queries, **retriever_parameters)
210
+ ...
211
+
212
+ return ({self.outputs[0]: documents}, parameters)
213
+ ```
214
+
215
+ 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.
216
+
217
+ # Drawbacks
218
+
219
+ ### Migration effort
220
+
221
+ 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.
222
+
223
+ 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.
224
+
225
+ # Alternatives
226
+
227
+ 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.
228
+
229
+ # Adoption strategy
230
+
231
+ This proposal is part of the Haystack 2.0 rollout strategy. See https://github.com/deepset-ai/haystack/pull/4284.
232
+
233
+ # How we teach this
234
+
235
+ 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.
236
+
237
+ # Open questions
238
+
239
+ - 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.
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5289-recentness-ranker.md ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: Addition of a RecentnessRanker node
2
+ - Decision driver: @elundaeva
3
+ - Start Date: 2023-07-05
4
+ - Proposal PR: https://github.com/deepset-ai/haystack/pull/5289
5
+ - Github Issue or Discussion: some links available in the "Detailed design" section below
6
+
7
+ # Summary
8
+
9
+ This ranker allows to have retrieved documents sorted not only by relevance (default) but also with recency factored in.
10
+
11
+ # Basic example
12
+
13
+ The RecentnessRanker would be instantiated as follows:
14
+
15
+ ``` python
16
+
17
+ ranker = RecentnessRanker(
18
+ date_identifier="date",
19
+ weight="0.5",
20
+ top_k=3,
21
+ method="reciprocal_rank_fusion",
22
+ )
23
+ ```
24
+
25
+ And here is an example of how the node would work in the context of a generative QA pipeline:
26
+
27
+ ``` yaml
28
+
29
+ version: '1.18.0'
30
+ name: 'Example pipeline'
31
+
32
+ components:
33
+ - name: DocumentStore
34
+ type: DeepsetCloudDocumentStore
35
+ - name: EmbeddingRetriever
36
+ type: EmbeddingRetriever
37
+ params:
38
+ document_store: DocumentStore
39
+ embedding_model: [embedding model here]
40
+ model_format: sentence_transformers
41
+ top_k: 30
42
+ - name: BM25Retriever
43
+ type: BM25Retriever
44
+ params:
45
+ document_store: DocumentStore
46
+ top_k: 30
47
+ - name: JoinDocuments
48
+ type: JoinDocuments
49
+ params:
50
+ top_k_join: 30
51
+ join_mode: reciprocal_rank_fusion
52
+ - name: Ranker
53
+ type: SentenceTransformersRanker
54
+ params:
55
+ model_name_or_path: [cross-encoder model here]
56
+ top_k: 15
57
+ - name: RecentnessRanker
58
+ type: RecentnessRanker
59
+ params:
60
+ date_identifier: release_date
61
+ top_k: 3
62
+ method: score
63
+ - name: qa_template
64
+ type: PromptTemplate
65
+ params:
66
+ output_parser:
67
+ type: AnswerParser
68
+ prompt: "prompt text here"
69
+ - name: PromptNode
70
+ type: PromptNode
71
+ params:
72
+ default_prompt_template: qa_template
73
+ max_length: 300
74
+ model_kwargs:
75
+ temperature: 0
76
+ model_name_or_path: gpt-3.5-turbo
77
+ - name: FileTypeClassifier
78
+ type: FileTypeClassifier
79
+ - name: TextConverter
80
+ type: TextConverter
81
+ - name: PDFConverter
82
+ type: PDFToTextConverter
83
+ - name: Preprocessor
84
+ params:
85
+ language: en
86
+ split_by: word
87
+ split_length: 200
88
+ split_overlap: 10
89
+ split_respect_sentence_boundary: true
90
+ type: PreProcessor
91
+
92
+ pipelines:
93
+ - name: query
94
+ nodes:
95
+ - name: EmbeddingRetriever
96
+ inputs: [Query]
97
+ - name: BM25Retriever
98
+ inputs: [Query]
99
+ - name: JoinDocuments
100
+ inputs: [EmbeddingRetriever, BM25Retriever]
101
+ - name: Ranker
102
+ inputs: [JoinDocuments]
103
+ - name: RecentnessRanker
104
+ inputs: [Ranker]
105
+ - name: PromptNode
106
+ inputs: [RecentnessRanker]
107
+
108
+ - name: indexing
109
+ nodes:
110
+ - inputs:
111
+ - File
112
+ name: FileTypeClassifier
113
+ - inputs:
114
+ - FileTypeClassifier.output_1
115
+ name: TextConverter
116
+ - inputs:
117
+ - FileTypeClassifier.output_2
118
+ name: PDFConverter
119
+ - inputs:
120
+ - TextConverter
121
+ - PDFConverter
122
+ name: Preprocessor
123
+ - inputs:
124
+ - Preprocessor
125
+ name: EmbeddingRetriever
126
+ - inputs:
127
+ - EmbeddingRetriever
128
+ name: DocumentStore
129
+
130
+ ```
131
+
132
+ # Motivation
133
+
134
+ 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.
135
+
136
+ # Detailed design
137
+
138
+ You can see the code for this proposal here: https://github.com/deepset-ai/haystack/pull/5301/files.
139
+
140
+ As a general description, the ranker has the following parameters (date_identifier and method are required, the rest are optional):
141
+ - date_identifier (string pointing to the date field in the metadata)
142
+ - weight (the options are:
143
+ - 0.5 default, relevance and recency will have the same impact in the calculation;
144
+ - 0 only relevance will be considered for the calculation, so the RecentnessRanker is effectively disabled;
145
+ - 1 only recency will be considered for the calculation)
146
+ - top_k (number of documents to return, works the same way as top-k in other rankers as well as retrievers)
147
+ - method (the options are:
148
+ - "reciprocal_rank_fusion" which does not require any relevance score from the previous node;
149
+ - "score" requires a 0-1 relevance score provided from the previous node in the pipeline.
150
+ More information on method compatibility with different retrievers is in the Drawbacks section below)
151
+
152
+ The RecentnessRanker works by:
153
+ 1. Adjusting the relevance score based on the chosen weight.
154
+ 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).
155
+ And the "score" method performs the calculation as relevance score * (1 - weight).
156
+ 2. Adding to the relevance score the recentness score by:
157
+ 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.
158
+ For the "score" method - performing the recentness score * weight calculation where recentness score is (amount of documents - rank) / amount of documents.
159
+ 3. Returning top-k documents in the documents dictionary sorted by final score (relevance score + recentness score both adjusted by weight).
160
+
161
+ 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.
162
+
163
+ # Drawbacks
164
+
165
+ 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.
166
+
167
+ 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.
168
+
169
+ # Alternatives
170
+
171
+ 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.
172
+
173
+ # Adoption strategy
174
+
175
+ 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).
176
+
177
+ # How we teach this
178
+
179
+ 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).
180
+
181
+ 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.
182
+
183
+ # Unresolved questions
184
+
185
+ 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.
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5390-embedders.md ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: Embedders
2
+ - Decision driver: @anakin87
3
+ - Start Date: 2023-07-19
4
+ - Proposal PR: https://github.com/deepset-ai/haystack/pull/5390
5
+
6
+ # Summary
7
+
8
+ 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.
9
+
10
+ **Separation of concerns**
11
+ - DocumentStores: store the Documents, their metadata and representations (vectors); they offer a CRUD API.
12
+ - 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).
13
+ - **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).
14
+
15
+ *In the current implementation, the Embedder is part of Retriever, which is unintuitive and comes with several disadvantages (explained in the previous proposals).*
16
+
17
+ **This proposal aims to define the Embedder design.**
18
+
19
+ # Basic example
20
+
21
+ *This code snippet is merely an example and may not be completely up-to-date.*
22
+
23
+
24
+ ```python
25
+ from haystack import Pipeline
26
+ from haystack.components import (
27
+ TxtConverter,
28
+ PreProcessor,
29
+ DocumentWriter,
30
+ OpenAITextEmbedder,
31
+ OpenAIDocumentEmbedder,
32
+ MemoryRetriever,
33
+ Reader,
34
+ )
35
+ from haystack.document_stores import MemoryDocumentStore
36
+ docstore = MemoryDocumentStore()
37
+
38
+ indexing_pipe = Pipeline()
39
+ indexing_pipe.add_store("document_store", docstore)
40
+ indexing_pipe.add_node("txt_converter", TxtConverter())
41
+ indexing_pipe.add_node("preprocessor", PreProcessor())
42
+ indexing_pipe.add_node("embedder", OpenAIDocumentEmbedder(model_name="text-embedding-ada-002"))
43
+ indexing_pipe.add_node("writer", DocumentWriter(store="document_store"))
44
+ indexing_pipe.connect("txt_converter", "preprocessor")
45
+ indexing_pipe.connect("preprocessor", "embedder")
46
+ indexing_pipe.connect("embedder", "writer")
47
+
48
+ indexing_pipe.run(...)
49
+
50
+ query_pipe = Pipeline()
51
+ query_pipe.add_store("document_store", docstore)
52
+ query_pipe.add_node("embedder", OpenAITextEmbedder(model_name="text-embedding-ada-002"))
53
+ query_pipe.add_node("retriever", MemoryRetriever(store="document_store", retrieval_method="embedding"))
54
+ query_pipe.add_node("reader", Reader(model_name="deepset/model-name"))
55
+ query_pipe.connect("embedder", "retriever")
56
+ query_pipe.connect("retriever", "reader")
57
+
58
+ results = query_pipe.run(...)
59
+ ```
60
+
61
+ - 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.
62
+ - 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.
63
+ - The Retriever is no longer needed in the indexing pipeline.
64
+
65
+ # Motivation
66
+
67
+ 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:
68
+ - Retrievers shouldn't be responsible for embedding Documents.
69
+ - Currently, Retrievers have many parameters just to support and configure different underlying Encoders(≈Embedders).
70
+ - Adding support for new embedding providers or strategies is difficult. It requires changing the Retriever code.
71
+
72
+ # Detailed design
73
+
74
+ ## Handle queries and Documents
75
+ This is the most critical aspect of the design.
76
+
77
+ - When embedding queries, the Embedder component receives a list of strings in input that are transformed into a list of vectors returned as output.
78
+ - 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.
79
+ - 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.
80
+
81
+ **Below, I will focus on the public API. The internal implementation is discussed in [Implementation details](#implementation-details).**
82
+
83
+ ```python
84
+ @component
85
+ class HFTextEmbedder:
86
+ ...
87
+
88
+ @component.output_types(result=List[np.ndarray])
89
+ def run(self, strings: List[str]):
90
+ ...
91
+ return {"result": list_of_computed_embeddings}
92
+
93
+
94
+ @component
95
+ class HFDocumentEmbedder:
96
+ ...
97
+
98
+ @component.output_types(result=List[Document])
99
+ def run(self, documents: List[Document]):
100
+ ...
101
+ return {"result": list_of_documents_with_embeddings}
102
+ ```
103
+
104
+ ## Different providers/strategies
105
+
106
+ - We can define different embedder components depending on the models or services providing the actual embeddings: `OpenAIEmbedder`, `CohereEmbedder`, `HuggingFaceEmbedder`, `SentenceTransformersEmbedder`, etc.
107
+ - Additionally, we could define different classes depending on the embedding strategy if necessary.
108
+ 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.
109
+
110
+ ## Different models in the same embedding/retrieval task
111
+
112
+ 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.
113
+
114
+ 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.
115
+
116
+ Some examples:
117
+ - In Dense Passage Retrieval, you need a model to encode queries and another model to encode Documents
118
+ - in the TableTextRetriever, we use 3 different models: one for queries, one for textual passages and one for tables
119
+ - in Multimodal Retrieval, we can specify different models to encode queries and Documents
120
+
121
+ Since the Embedder will not be included in the Retriever, it makes sense to have different Embedders, each one using a single model.
122
+
123
+ ```python
124
+ dpr_query_embedder = SentenceTransformersTextEmbedder(model_name="facebook/dpr-question_encoder-single-nq-base")
125
+ dpr_doc_embedder = SentenceTransformersDocumentEmbedder(model_name="facebook/dpr-ctx_encoder-single-nq-base")
126
+ ```
127
+
128
+ ## Implementation details
129
+
130
+ *You can skip this section if you are primarily interested in user experience.*
131
+
132
+ There have been much discussion on how to effectively implement this proposal.
133
+ The most important aspects to consider:
134
+ - we want different Embedders for queries and Documents as they require a different treatment
135
+ - if the same model is internally used for different Embedders, we want to reuse the same instance in order to save memory
136
+
137
+ On top of the embedder components we already discussed, we introduce one additional abstraction:
138
+ 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.
139
+ ```python
140
+ @singleton # implementation is out of scope
141
+ class HFEmbeddingBackend:
142
+ """
143
+ NOT A COMPONENT!
144
+ """
145
+ def __init__(self, model_name: str, ... init params ...):
146
+ """
147
+ init takes the minimum parameters needed at init time, not
148
+ the params needed at inference, so they're easier to reuse.
149
+ """
150
+ self.model = ...
151
+
152
+ def embed(self, data: str, ... inference params ... ) -> np.ndarray:
153
+ # compute embedding
154
+ return embedding
155
+
156
+
157
+ class OpenAIEmbeddingBackend:
158
+ ... same as above ...
159
+ ```
160
+
161
+ 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.
162
+
163
+ This is how an EmbeddingBackend would be used by a text embedder component:
164
+ **Part of the public API**.
165
+ ```python
166
+ @component
167
+ class HFTextEmbedder:
168
+
169
+ def __init__(self, model_name: str, ... init params ...):
170
+ self.model_name = model_name
171
+ self.model_params = ... params ...
172
+
173
+ def warm_up(self):
174
+ self.embedding_backend = HFEmbeddingBackend(self.model_name, **self.model_params)
175
+
176
+ @component.output_types(result=List[np.ndarray])
177
+ def run(self, strings: List[str]):
178
+ return {"result": self.embedding_backend.embed(data)}
179
+ ```
180
+
181
+ Another example, using an embedder component expecting Documents:
182
+ **Part of the public API**.
183
+
184
+ ```python
185
+ @component
186
+ class HFDocumentEmbedder:
187
+
188
+ def __init__(self, model_name: str, ... init params ...):
189
+ self.model_name = model_name
190
+ self.model_params = ... params ...
191
+
192
+ def warm_up(self):
193
+ self.embedding_backend = HFEmbeddingBackend(self.model_name, **self.model_params)
194
+
195
+ @component.output_types(result=List[Document])
196
+ def run(self, documents: List[Document]):
197
+ text_strings = [document.content for document in data]
198
+ embeddings = self.embedding_backend.embed(text_strings)
199
+ documents_with_embeddings = [Document.from_dict(**doc.to_dict, "embedding": emb) for doc, emb in zip(documents, embeddings)]
200
+ return {"result": documents_with_embeddings}
201
+ ```
202
+
203
+ # Drawbacks
204
+
205
+ ## Migration
206
+ 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**.
207
+
208
+ 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)`.
209
+
210
+ With the new Embedder design, I can imagine something similar (based on the MemoryDocumentStore v2 implementation):
211
+ ```python
212
+ # get all the documents
213
+ docs = memory_document_store.filter_documents()
214
+
215
+ # compute the embedding with the new model
216
+ new_embedder = HFDocumentEmbedder(model_name="new-model")
217
+ docs_with_embeddings = new_embedder.run(documents=docs)
218
+
219
+ # overwrite the documents
220
+ memory_document_store.write_documents(documents=docs_with_embeddings, policy=DuplicatePolicy.OVERWRITE)
221
+ ```
222
+ ## Other aspects
223
+ Regarding the design proposed in this document, there are some potential drawbacks to consider:
224
+ - Proliferation of classes (though they will be small and easy to maintain).
225
+ - 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.
226
+
227
+ # Alternatives
228
+
229
+ Several alternatives to this design were considered. The main challenge was handling the differences between queries and Documents.
230
+ Some ideas:
231
+ - 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.
232
+ - Make Embedders only work on Documents and represent the query as a Document. --> Unintuitive and require changes in the Retriever.
233
+ - Create another primitive like Data (content + embedding) and use it for both queries and Documents. --> More conversion components like DataToDocument.
234
+ - Have the DocumentEmbedder take a TextEmbedder as an input parameter. --> Fewer classes but serialization issues.
235
+
236
+ # Adoption strategy
237
+
238
+ This change will constitute a part of Haystack v2.
239
+
240
+ # How we teach this
241
+
242
+ Documentation and tutorials will be of fundamental importance.
243
+
244
+ # Unresolved questions
245
+
246
+ - Migration and refactoring of existing Encoders hidden in Retrievers.
247
+ I prepared a table. Should it be shared here?
248
+ - The migration and refactoring of TableTextRetriever require input and ownership from people involved in TableQA.
249
+ - How to approach MultiModal Embedding? How many classes? Take into consideration that a query could also be an Image or a Table.
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5540-llm-support-2.0.md ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: LLM SUpport in Haystack 2.0
2
+ - Decision driver: @ZanSara
3
+ - Start Date: 2023-08-10
4
+ - Proposal PR: #5540
5
+ - Github Issue or Discussion: https://github.com/deepset-ai/haystack/issues/5330
6
+
7
+ # Summary
8
+
9
+ In this proposal we outline our migration strategy of the `PromptNode` stack of functionality into Haystack 2.0 components.
10
+
11
+ This proposal, however, does not discuss Agents or Agent-related features and functionality, which are going to be addressed into a separate proposal.
12
+
13
+ # Motivation
14
+
15
+ This proposal is part of a larger effort of migrating existing Haystack 1.x components into their 2.0 counterpart.
16
+
17
+ # Basic example
18
+
19
+ 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.
20
+
21
+ As this proposal concerns LLM support, not specifically Agents, the main usecase in question is RAG (Retrieval-Augmented Generation).
22
+
23
+ ## Example: RAG Pipeline
24
+
25
+ Using the components discussed in the Detailed Design section, a Haystack 2.0 RAG pipeline may look like this:
26
+
27
+ ```mermaid
28
+ graph TD;
29
+
30
+ IN{IN} -- "questions (List[str])" --> Retriever
31
+ IN{IN} -- "questions (List[str])" --> PromptBuilder
32
+ Retriever -- "documents (List[List[Doc]])" --> PromptBuilder
33
+ PromptBuilder -- "prompts (List[str])" --> GPT4Generator
34
+ GPT4Generator -- "replies (List[List[str]])" --> RepliesToAnswersConverter
35
+ RepliesToAnswersConverter -- "answers (List[List[Answer]])" --> OUT{OUT}
36
+ ```
37
+
38
+ While the code for such pipeline may look like:
39
+
40
+ ```python
41
+ from haystack.preview.components import MemoryRetriever, PromptBuilder, ChatGPTGenerator, RepliesToAnswersConverter
42
+ from haystack.preview.document_stores import MemoryDocumentStore
43
+ from haystack.preview.pipeline import Pipeline
44
+
45
+ pipe = Pipeline()
46
+ pipe.add_store("store", MemoryDocumentStore())
47
+ pipe.add_component("retriever", MemoryRetriever(), store="store")
48
+ pipe.add_component("prompt_builder", PromptBuilder("deepset/question-answering"))
49
+ pipe.add_component("llm", GPT4Generator(api_key="..."))
50
+ pipe.add_component("replies_converter", RepliesToAnswersConverter())
51
+
52
+ pipe.connect("retriever", "prompt_builder")
53
+ pipe.connect("prompt_builder", "llm")
54
+ pipe.connect("llm", "replies_converter")
55
+
56
+ questions = ["Why?", "Why not?"]
57
+ results = pipe.run({
58
+ "retriever": {"queries": questions},
59
+ "prompt_builder": {"questions": questions},
60
+ })
61
+
62
+ assert results == {
63
+ "replies_converter": {
64
+ "answers": [[Answer("Because of this.")], [Answer("Because of that.")]]
65
+ }
66
+ }
67
+ ```
68
+
69
+ # Detailed design
70
+
71
+ 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.
72
+
73
+ 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.
74
+
75
+ The main functionalities we identified are the following:
76
+
77
+ 1. Fetching the prompt from different sources
78
+ 2. Rendering the prompt using variables
79
+ 3. Invoke the LLM
80
+ 4. Parse the output
81
+ 5. History/Memory management
82
+
83
+ We leave the discussion about History/Memory to a separate proposal, as it concerns mostly Agents, and focus on the other points.
84
+
85
+ ## LLM invocation
86
+
87
+ 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.
88
+
89
+ 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.
90
+
91
+ 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.
92
+
93
+ 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.
94
+
95
+ All these LLM clients will have a near-identical I/O:
96
+
97
+ ```python
98
+ @component
99
+ class ChatGPTGenerator:
100
+
101
+ @component.output_types(replies=List[List[str]])
102
+ def run(self, prompts: List[str], ... chatgpt specific params...):
103
+ ...
104
+ return {'replies': [...]}
105
+ ```
106
+
107
+ 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.
108
+
109
+ 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.
110
+
111
+ ### Chat API
112
+
113
+ Most LLMs support Chat interfaces, where they expect not a single prompt, but a list of messages in a format such as:
114
+
115
+ ```
116
+ [
117
+ {"role": "system", "content": "\nYou are a helpful assistant speaking like a pirate. argh!"},
118
+ {"role": "user", "content": "What is the sun?"},
119
+ ]
120
+ ```
121
+
122
+ 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.
123
+
124
+ ### Returning metadata
125
+
126
+ 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.
127
+
128
+ 1. Do we already have any such situation?
129
+ 2. Can we foresee any other?
130
+
131
+ 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.
132
+
133
+ ### Returning streams
134
+
135
+ 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.
136
+
137
+ 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.
138
+
139
+ In version 2.x we're going to do the same and have all generator components accept an optional callback during initialization.
140
+
141
+ ### How many clients we will have?
142
+
143
+ Basing on the list of current invocation layers in Haystack 1.x, the list might look like:
144
+
145
+ 1. `ClaudeGenerator`
146
+ 2. `ChatGPTGenerator`, supporting GPT4 as well
147
+ - it may have an alias `GPT4Generator` to help users
148
+ 3. `CohereGenerator`
149
+ 4. `HuggingFaceInferenceGenerator`
150
+ 5. `HuggingFaceLocalGenerator`
151
+ 6. `GPT3Generator`
152
+ 7. `SagemakerGenerator`
153
+
154
+ Plus one more for any other inference hosting/library that may appear in the future.
155
+
156
+ ## Prompt Builder
157
+
158
+ 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.
159
+
160
+ 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.
161
+
162
+ `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.
163
+
164
+ Draft I/O for `PromptBuilder`:
165
+
166
+ ```python
167
+ @component
168
+ class PromptBuilder:
169
+
170
+ def __init__(self, template: Union[str, Path]):
171
+ self.template = # Download the template
172
+ template_variables = # extracts the variables from the template text
173
+ component.set_input_parameters(**{var: Any for var in template_variables})
174
+
175
+ @component.output_types(prompts=List[str])
176
+ def run(self, **kwargs):
177
+ # Render the template using the variables
178
+ return {"prompts": prompts}
179
+ ```
180
+
181
+ ### Template variables
182
+
183
+ 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.
184
+
185
+ Such template names **cannot be changed at runtime**.
186
+
187
+ 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.
188
+
189
+ 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.
190
+
191
+ 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.
192
+
193
+ For example:
194
+
195
+ ```python
196
+ @component
197
+ class PromptBuilder:
198
+
199
+ @variadic_input
200
+ @component.output_types(prompts=List[str])
201
+ def run(self, template: Union[str, Path], **kwargs):
202
+ # ... loads the template ...
203
+ # ... render the prompts ...
204
+ return {"prompts": prompts}
205
+ ```
206
+
207
+ ### Why a separate `PromptBuilder` component at all?
208
+
209
+ `PromptNode` used to take the prompt template and the variables to render it directly, and then forward the result to the LLM.
210
+
211
+ 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.
212
+
213
+ 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).
214
+
215
+ 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.
216
+
217
+ ## Output parsing
218
+
219
+ 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.
220
+
221
+ 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.
222
+
223
+ 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.
224
+
225
+ Draft I/O for `RepliesToAnswersConverter` (note: this may end up being almost the entire component’s implementation):
226
+
227
+ ```python
228
+ @component
229
+ class RepliesToAnswersConverter:
230
+
231
+ @component.output_types(answers=List[List[Answer]])
232
+ def run(self, replies: List[List[str]]):
233
+ return {"answers": Answer(answer=answer) for answers in replies for answer in answers}
234
+ ```
235
+
236
+ # Drawbacks
237
+
238
+ Possible drawbacks of this design:
239
+
240
+ 1. Users now need to use three components instead of a single, large one.
241
+ 2. We lose the capability to change the prompt for the LLM at runtime.
242
+
243
+ # Alternatives
244
+
245
+ 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.
246
+
247
+ # Adoption strategy
248
+
249
+ Follows the same strategy outlines for all other Proposal relative to the Haystack 2.0 migration
250
+
251
+ # How we teach this
252
+
253
+ We need brand new tutorials and examples of pipelines using these components.
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5738-document-2.0.md ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: Document class for Haystack 2.0
2
+ - Decision driver: ZanSara
3
+ - Start Date: 2023-09-07
4
+ - Proposal PR: 5738
5
+
6
+ # Summary
7
+
8
+ With Haystack 2.0 we want to provide a lot more flexibility to Pipelines and Components. In a lot of situations,
9
+ we found that the Document class inherited from Haystack 1.x was not up to the task: therefore we chose to expand its
10
+ API to work best in this new paradigm.
11
+
12
+ # Basic example
13
+
14
+ Documents 2.0 have two fundamental differences with Documents 1.x:
15
+
16
+ - They have more than one content field. Documents 1.x only have a `content: Any` field that needs to match with the
17
+ `content_type` field in meaning. Documents 2.0 instead support `text`, `array`, `dataframe` and `blob`, each typed
18
+ correctly.
19
+
20
+ - The `content_type` field is gone: In Haystack 1.x we used the `content_type` field to interpret the data contained
21
+ in the `content` field: with the new design, this won't be necessary any longer. Haystack 2.0, however, have
22
+ a `mime_type` field that helps interpret the content of the `blob` field if necessary.
23
+
24
+ # Motivation
25
+
26
+ During the development of Haystack 2.0 components, we often found ourselves hold back by the design limitations of
27
+ the Document class. Unlike in Haystack 1.x, Documents now carry more information across the pipeline: for example,
28
+ they might contain the file they originated from, they might support more datatypes, etc.
29
+
30
+ Therefore we decided to extend the Document class to support a wider array of data.
31
+
32
+ # Detailed design
33
+
34
+ The design of this class was inspired by the [DocArray API](https://docarray.jina.ai/fundamentals/document/).
35
+
36
+ Here is the high-level API of the new Document class:
37
+
38
+ ```python
39
+ @dataclass(frozen=True)
40
+ class Document:
41
+ id: str = field(default_factory=str)
42
+ text: Optional[str] = field(default=None)
43
+ array: Optional[numpy.ndarray] = field(default=None)
44
+ dataframe: Optional[pandas.DataFrame] = field(default=None)
45
+ blob: Optional[bytes] = field(default=None)
46
+ mime_type: str = field(default="text/plain")
47
+ metadata: Dict[str, Any] = field(default_factory=dict, hash=False)
48
+ id_hash_keys: List[str] = field(default_factory=lambda: ["text", "array", "dataframe", "blob"], hash=False)
49
+ score: Optional[float] = field(default=None, compare=True)
50
+ embedding: Optional[numpy.ndarray] = field(default=None, repr=False)
51
+
52
+ def to_dict(self):
53
+ """
54
+ Saves the Document into a dictionary.
55
+ """
56
+
57
+ def to_json(self, json_encoder: Optional[Type[DocumentEncoder]] = None, **json_kwargs):
58
+ """
59
+ Saves the Document into a JSON string that can be later loaded back. Drops all binary data from the blob field.
60
+ """
61
+
62
+ @classmethod
63
+ def from_dict(cls, dictionary):
64
+ """
65
+ Creates a new Document object from a dictionary of its fields.
66
+ """
67
+
68
+ @classmethod
69
+ def from_json(cls, data, json_decoder: Optional[Type[DocumentDecoder]] = None, **json_kwargs):
70
+ """
71
+ Creates a new Document object from a JSON string.
72
+ """
73
+
74
+ def flatten(self) -> Dict[str, Any]:
75
+ """
76
+ Returns a dictionary with all the document fields and metadata on the same level.
77
+ Helpful for filtering in document stores.
78
+ """
79
+
80
+ ```
81
+
82
+ As you can notice, the main difference is the management of the content fields: we now have:
83
+
84
+ - `text`: for text data
85
+ - `array`: for array-like data, for example images, audio, video
86
+ - `dataframe`: for tabular data
87
+ - `blob`: for binary data.
88
+
89
+ In order to help interpret the content of these field, there's a `mime_type` field that components can use to figure out
90
+ how to use the content fields they need.
91
+
92
+ There are additional information that we may want to add, for example `path`. For now such info can be
93
+ kept into the metadata: if we realize we access it extremely often while processing Documents we should consider
94
+ bringing those fields out of `metadata` as top-level properties of the dataclass.
95
+
96
+
97
+ # Drawbacks
98
+
99
+ As the Document class becomes a bit more complex, components need to be adapted to it. This may cause some issues
100
+ to DocumentStores, because now they not only need to be able to store text but binary blobs as well.
101
+
102
+ We can imagine that some very simple DocumentStore will refuse to store the binary blobs. Fully-featured,
103
+ production-ready document stores instead should be able to find a way to store such blobs.
104
+
105
+
106
+ # Unresolved questions
107
+
108
+ Are the 4 content fields appropriate? Are there other content types we can consider adding?
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5794-evaluation-haystack-2.md ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: Evaluation in Haystack 2.0
2
+ - Decision driver: (Silvano Cerza, Julian Risch)
3
+ - Start Date: 2023-08-23
4
+ - Proposal PR: [#5794](https://github.com/deepset-ai/haystack/pull/5794/)
5
+ - Github Issue or Discussion: https://github.com/deepset-ai/haystack/issues/5628
6
+
7
+ # Summary
8
+
9
+ Given the below requirements we redefine how evaluation and metrics are handled in Haystack 2.x.
10
+
11
+ 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.
12
+ All this while making it more modular and easier to test and maintain.
13
+
14
+ The requirements are:
15
+
16
+ - compare the performance of different pipelines on level of pipeline outputs (user perspective, integrated eval)
17
+ - while running the full pipeline we can store intermediate results and calculate metrics for each component that returns answers or documents
18
+ - find out which component is the performance bottleneck in one pipeline by evaluating subpipelines (isolated evaluation)
19
+ - as above, get evaluation metrics for every component in a pipeline that returns answer or documents (ranker, retriever, reader, PromptNode)
20
+ - compare the performance of two components, for example two Readers, without the need to create a full retriever-reader pipeline
21
+ - export evaluation results to a file (similar to Haystack 1.x but faster) and evaluation report
22
+ - choose evaluation metrics from a list of metrics (e.g. F1, BLEU, ROUGE, Semantic Answer Similarity) based on the output type of a component
23
+ - evaluate pipelines that return ExtractiveAnswers
24
+ - evaluate pipelines that return GenerativeAnswers
25
+ - evaluate hallucinations (check generated answers are backed up by retrieved documents)
26
+ - 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)
27
+ - load evaluation data for example from BEIR
28
+
29
+ # Basic example
30
+
31
+ ```python
32
+ pipe = Pipeline()
33
+ ...
34
+ inputs = [{"component_name": {"query": "some question"}, ...}, ...]
35
+ expected_output = [{"another_component_name": {"answer": "42"}, ...}, ...]
36
+ result = eval(pipe, inputs=inputs, expected_output=expected_output)
37
+ metrics = result.calculate_metrics(Metric.SAS)
38
+ metrics.save("path/to/file.csv")
39
+ ```
40
+
41
+ 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.
42
+
43
+ # Motivation
44
+
45
+ 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.
46
+
47
+ 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.
48
+
49
+ 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.
50
+
51
+ 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.
52
+
53
+ 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.
54
+
55
+ 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.
56
+
57
+ # Detailed design
58
+
59
+ ### The `eval` function
60
+
61
+ We'll implement an `eval` function that will be able to evaluate all `Pipeline`s and `Component`s.
62
+ A minimal implementation could look like this:
63
+
64
+ ```python
65
+ def eval(runnable: Union[Pipeline, Component], inputs: List[Dict[str, Any]], expected_outputs: List[Dict[str, Any]]) -> EvaluationResult:
66
+ outputs = []
67
+ for input_ in inputs:
68
+ output = runnable.run(input_)
69
+ outputs.append(output)
70
+ return EvaluationResult(runnable, inputs, outputs, expected_outputs)
71
+ ```
72
+
73
+ This is obviously an overtly simplistic example but the core concept remains.
74
+ `inputs` must be a list of data that will be passed to either the `Pipeline` or the `Component`.
75
+ `expected_outputs` could be a list with the same length of `inputs` or an empty list for blind evaluation.
76
+
77
+ 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.
78
+
79
+ `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.
80
+
81
+ 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.
82
+
83
+ 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:
84
+
85
+ ```python
86
+ simulated_output = {
87
+ "component_name": {"answer": "120"},
88
+ "another_component_name": {"metadata": {"id": 1}}
89
+ }
90
+ ```
91
+
92
+ Another alternative would be to use the `expected_output` also to simulate outputs of intermediate components.
93
+
94
+ #### Tracking progress
95
+
96
+ To track progress we can also go on another direction. We could return partials results while iterating our inputs:
97
+
98
+ ```
99
+ def eval(runnable, inputs, expected_outputs):
100
+ result = EvaluationResult(runnable, inputs, {}, expected_outputs)
101
+ for input_ in inputs:
102
+ output = runnable.run(input_)
103
+ result.append_output(output)
104
+ yield result
105
+ ```
106
+
107
+ Or return some progress percentage and only in the end the final result.
108
+
109
+ ```
110
+ def eval(runnable, inputs, expected_outputs):
111
+ outputs = []
112
+ total = len(inputs)
113
+ for i, input_ in enumerate(inputs):
114
+ output = runnable.run(input_)
115
+ outputs.append(output)
116
+ yield 100 * (i / total), None
117
+
118
+ yield 100, EvaluationResult(runnable, inputs, outputs, expected_outputs)
119
+ ```
120
+
121
+ ### `EvaluationResult`
122
+
123
+ `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()`.
124
+ This way we'll be able to save all the necessary information to a single file. That information will probably be:
125
+
126
+ - Serialized Pipeline or Component
127
+ - Inputs
128
+ - Expected outputs
129
+ - Actual outputs
130
+
131
+ This data should be serializable to string so that it can be saved to file and loaded back whenever necessary.
132
+ 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.
133
+
134
+ Given the above information we should be able to implement a single method to calculate predeterminated metrics or even custom ones.
135
+ Known metrics could be defined as an enum to ease discoverability and documentation.
136
+
137
+ ```python
138
+ class Metric(Enum):
139
+ RECALL = "Recall"
140
+ MRR = "Mean Reciprocal Rank"
141
+ MAP = "Mean Average Precision"
142
+ EM = "Exact Match"
143
+ F1 = "F1"
144
+ SAS = "SemanticAnswerSimilarity"
145
+ ```
146
+
147
+ The method to calculate metrics could look similar to this:
148
+
149
+ ```python
150
+ MetricsResult = Dict[str, Dict[str, float]]
151
+ MetricCalculator = Callable[..., MetricResult]
152
+
153
+ def calculate_metrics(self: EvaluationResult, metric: Union[Metric, MetricCalculator], **kwargs) -> MetricsResult:
154
+ # Verify if we're calculating a known metric
155
+ if metric == Metric.RECALL:
156
+ return self._calculate_recall(**kwargs)
157
+ elif metric == Metric.MRR:
158
+ return self._calculate_mrr(**kwargs)
159
+ # Other metrics...
160
+
161
+ # If it's not a known metric it must be a custom one
162
+ return metric(self, **kwargs)
163
+ ```
164
+
165
+ 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.
166
+ 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:
167
+
168
+ ```python
169
+ class MetricResult(dict):
170
+ def save(self, file: Union[str, Path]):
171
+ # Dump info to file here
172
+ ```
173
+
174
+ ### Ease input specification
175
+
176
+ 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.
177
+
178
+ 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.
179
+
180
+ 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:
181
+
182
+ ```python
183
+ eval(pipe, {"query": "This is the query"})
184
+ ```
185
+
186
+ 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:
187
+
188
+ ```python
189
+ eval(pipe, {"foo": {"query": "This is the query"}, "bar": {"query": "This is the query"}})
190
+ ```
191
+
192
+ # Drawbacks
193
+
194
+ 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`.
195
+
196
+ 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:
197
+
198
+ ```python
199
+ input = {
200
+ "foo": {"input_query": "This my input query"},
201
+ "bar": {"input_query": "This my input query"}
202
+ }
203
+ ```
204
+
205
+ I believe this a worthy tradeoff as it gives huge amount of customization that wasn't possible in Haystack 1.x.
206
+
207
+ 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.
208
+
209
+ 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.
210
+
211
+ 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`.
212
+
213
+ 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.
214
+
215
+ # Adoption strategy
216
+
217
+ This is obviously a breaking change as it's meant for Haystack 2.x.
218
+
219
+ # How we teach this
220
+
221
+ 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.
222
+
223
+ We're also going to have new community spotlights in Discord to show how to approach evaluation in Haystack 2.x.
224
+
225
+ # Unresolved questions
226
+
227
+ Evaluation of pipelines containing Agents or other loops is out of scope for this proposal (except for integrated pipeline evaluation).
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/5794-evaluation-haystack-2.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ # mypy: ignore-errors
5
+ # pylint: skip-file
6
+ ###
7
+ ### This is an example script of how to use the eval function to evaluate a RAG Pipeline.
8
+ ### For more information see the relative proposal.
9
+ ###
10
+
11
+ import os
12
+
13
+ from haystack import Pipeline
14
+ from haystack.components.builders.prompt_builder import PromptBuilder
15
+ from haystack.components.generators.openai.gpt35 import GPT35Generator
16
+ from haystack.components.retrievers.memory import MemoryBM25Retriever
17
+ from haystack.dataclasses.document import Document
18
+ from haystack.document_stores.memory import MemoryDocumentStore
19
+
20
+ docstore = MemoryDocumentStore()
21
+
22
+ # Write some fake documents
23
+ docstore.write_documents(
24
+ [
25
+ Document(content="This is not the answer you are looking for.", meta={"name": "Obi-Wan Kenobi"}),
26
+ Document(content="This is the way.", meta={"name": "Mandalorian"}),
27
+ Document(content="The answer to life, the universe and everything is 42.", meta={"name": "Deep Thought"}),
28
+ Document(content="When you play the game of thrones, you win or you die.", meta={"name": "Cersei Lannister"}),
29
+ Document(content="Winter is coming.", meta={"name": "Ned Stark"}),
30
+ ]
31
+ )
32
+
33
+ # Create our retriever, we set top_k to 3 to get only the best 3 documents otherwise by default we get 10
34
+ retriever = MemoryBM25Retriever(document_store=docstore, top_k=3)
35
+
36
+ # Create our prompt template
37
+ template = """Given the context please answer the question.
38
+ Context:
39
+ {# We're receiving a list of lists, so we handle it like this #}
40
+ {% for list in documents %}
41
+ {% for doc in list %}
42
+ {{- doc -}};
43
+ {% endfor %}
44
+ {% endfor %}
45
+ Question: {{ question }};
46
+ Answer:
47
+ """
48
+ prompt_builder = PromptBuilder(template)
49
+
50
+ # We're using OpenAI gpt-3.5
51
+ OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
52
+ generator = GPT35Generator(api_key=OPENAI_API_KEY)
53
+
54
+ # Build the pipeline
55
+ pipe = Pipeline()
56
+
57
+ pipe.add_component("docs_retriever", retriever)
58
+ pipe.add_component("builder", prompt_builder)
59
+ pipe.add_component("gpt35", generator)
60
+
61
+ pipe.connect("docs_retriever.documents", "builder.documents")
62
+ pipe.connect("builder.prompt", "gpt35.prompt")
63
+
64
+ # Run the pipeline
65
+ query = "What is the answer to life, the universe and everything?"
66
+ result = pipe.run({"docs_retriever": {"queries": [query]}, "builder": {"question": query}})
67
+
68
+ print(result["gpt35"]["replies"])
69
+
70
+
71
+ # These are the input that will be passed to the Pipeline when running eval, much like we've done a couple of lines above
72
+ inputs = [
73
+ {"docs_retriever": {"queries": ["What is the answer?"]}, "builder": {"question": "What is the answer?"}},
74
+ {
75
+ "docs_retriever": {"queries": ["Take a deep breath and think. What is the answer?"]},
76
+ "builder": {"question": "Take a deep breath and think. What is the answer?"},
77
+ },
78
+ {
79
+ "docs_retriever": {"queries": ["What is the answer to life, the universe and everything?"]},
80
+ "builder": {"question": "What is the answer to life, the universe and everything?"},
81
+ },
82
+ ]
83
+
84
+ # These are the expected output that will be compared to the actual output of the Pipeline.
85
+ # We have a dictionary for each input so that len(inputs) == len(expected_output).
86
+ # This gives the possibility to have different expected output for each different input.
87
+ # NOTE: I omitted the gpt35 metadata output because it's too long.
88
+ expected_output = [
89
+ {
90
+ # This is the output that we expect from the docs_retriever component
91
+ "docs_retriever": {
92
+ "documents": [
93
+ [
94
+ Document(
95
+ content="The answer to life, the universe and everything is 42.", meta={"name": "Deep Thought"}
96
+ ),
97
+ Document(content="This is not the answer you are looking for.", meta={"name": "Obi-Wan Kenobi"}),
98
+ Document(content="This is the way.", meta={"name": "Mandalorian"}),
99
+ ]
100
+ ]
101
+ },
102
+ # This is the output that we expect from the builder component
103
+ "builder": {"prompt": "I should write the actual template here but I'm lazy so I won't."},
104
+ # This is the output that we expect from the gpt35 component
105
+ "gpt35": {"replies": ["The answer to life, the universe and everything is 42."], "metadata": {}},
106
+ },
107
+ {
108
+ "docs_retriever": {
109
+ "documents": [
110
+ [
111
+ Document(
112
+ content="The answer to life, the universe and everything is 42.", meta={"name": "Deep Thought"}
113
+ ),
114
+ Document(content="This is not the answer you are looking for.", meta={"name": "Obi-Wan Kenobi"}),
115
+ Document(content="This is the way.", meta={"name": "Mandalorian"}),
116
+ ]
117
+ ]
118
+ },
119
+ "builder": {"prompt": "I should write the actual template here but I'm lazy so I won't."},
120
+ "gpt35": {"replies": ["The answer to life, the universe and everything is 42."], "metadata": {}},
121
+ },
122
+ {
123
+ "docs_retriever": {
124
+ "documents": [
125
+ [
126
+ Document(
127
+ content="The answer to life, the universe and everything is 42.", meta={"name": "Deep Thought"}
128
+ ),
129
+ Document(content="This is not the answer you are looking for.", meta={"name": "Obi-Wan Kenobi"}),
130
+ Document(content="This is the way.", meta={"name": "Mandalorian"}),
131
+ ]
132
+ ]
133
+ },
134
+ "builder": {"prompt": "I should write the actual template here but I'm lazy so I won't."},
135
+ "gpt35": {"replies": ["The answer to life, the universe and everything is 42."], "metadata": {}},
136
+ },
137
+ ]
138
+
139
+ eval_result = eval(pipe, inputs=inputs, expected_output=expected_output)
140
+ metrics = result.calculate_metrics(Metric.SAS) # noqa
141
+ metrics.save("path/to/file.csv")
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6001-document-store-filter-rework.md ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: Document Stores filter specification for Haystack 2.x
2
+ - Decision driver: Silvano Cerza
3
+ - Start Date: 2023-10-08
4
+ - Proposal PR: [#6001](https://github.com/deepset-ai/haystack/pull/6001)
5
+
6
+ # Summary
7
+
8
+ This proposal introduces a new fully detailed and extensible specification for filtering Document Stores in Haystack 2.x.
9
+ This comes from my personal experience and struggles trying to implement filters conversion for `ElasticsearchDocumentStore`.
10
+
11
+ # Basic example
12
+
13
+ ```
14
+ {
15
+ "conditions": [
16
+ { "field": "age", "operator": ">=", "value": 18 },
17
+ {
18
+ "operator": "OR",
19
+ "conditions": [
20
+ { "field": "country", "operator": "==", "value": "USA" },
21
+ { "field": "country", "operator": "==", "value": "Canada" }
22
+ ]
23
+ }
24
+ ]
25
+ }
26
+ ```
27
+
28
+ The above snippet would be equivalent to the following Python code:
29
+
30
+ ```python
31
+ age >= 18 and (country == "USA" or country == "Canada)
32
+ ```
33
+
34
+ # Motivation
35
+
36
+ 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.
37
+
38
+ 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.
39
+
40
+ As a practical example the below two filters are equivalent. Given that they're structured differently and `$and` is implicit in the second one:
41
+
42
+ ```
43
+ {"number": {"$and": [{"$lte": 2}, {"$gte": 0}]}}
44
+
45
+ {"number": {"$lte": 2, "$gte": 0}}
46
+ ```
47
+
48
+ With the newly proposed approach both filters would be equivalent to:
49
+
50
+ ```
51
+ {
52
+ "operator": "AND",
53
+ "conditions": [
54
+ { "field": "number", "operator": "<=", "value": 2 },
55
+ { "field": "number", "operator": ">=", "value": 0 },
56
+ ]
57
+ }
58
+ ```
59
+
60
+ 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.
61
+
62
+ In Python code:
63
+
64
+ ```python
65
+ number <= 2 AND number >= 0
66
+ ```
67
+
68
+ # Detailed design
69
+
70
+ Filters top level must be a dictionary.
71
+
72
+ There are two types of dictionaries:
73
+
74
+ - Comparison
75
+ - Logic
76
+
77
+ Top level can be either be a Comparison or Logic dictionary.
78
+
79
+ Comparison dictionaries must contain the keys:
80
+
81
+ - `field`
82
+ - `operator`
83
+ - `value`
84
+
85
+ Logic dictionaries must contain the keys:
86
+
87
+ - `operator`
88
+ - `conditions`
89
+
90
+ `conditions` key must be a list of dictionaries, either Comparison or Logic.
91
+
92
+ `operator` values in Comparison dictionaries must be:
93
+
94
+ - `==`
95
+ - `!=`
96
+ - `>`
97
+ - `>=`
98
+ - `<`
99
+ - `<=`
100
+ - `in`
101
+ - `not in`
102
+
103
+ `operator` values in Logic dictionaries must be:
104
+
105
+ - `NOT`
106
+ - `OR`
107
+ - `AND`
108
+
109
+ ---
110
+
111
+ As an example this:
112
+
113
+ ```
114
+ {
115
+ "$and": {
116
+ "type": {"$eq": "article"},
117
+ "$or": {"genre": {"$in": ["economy", "politics"]}, "publisher": {"$eq": "nytimes"}},
118
+ "date": {"$gte": "2015-01-01", "$lt": "2021-01-01"},
119
+ "rating": {"$gte": 3},
120
+ }
121
+ }
122
+ ```
123
+
124
+ would convert to:
125
+
126
+ ```
127
+ {
128
+ "operator": "AND",
129
+ "conditions": [
130
+ { "field": "type", "operator": "==", "value": "article" },
131
+ {
132
+ "operator": "OR",
133
+ "conditions": [
134
+ { "field": "genre", "operator": "in", "value": ["economy", "politics"] },
135
+ { "field": "publisher", "operator": "==", "value": "nytimes" },
136
+ ]
137
+ },
138
+ { "field": "date", "operator": ">=", "value": "2015-01-01" },
139
+ { "field": "date", "operator": "<", "value": "2021-01-01" },
140
+ { "field": "rating", "operator": ">=", "value": 3 },
141
+ ]
142
+ }
143
+ ```
144
+
145
+ In Python code:
146
+
147
+ ```python
148
+ type == "article" and (
149
+ genre in ["economy", "politics"] or publisher == "nytimes"
150
+ ) and date >= "2015-01-01" and date < "2021-01-01" and rating >= 3
151
+ ```
152
+
153
+ 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.
154
+
155
+ 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`
156
+ This connects to `Document` implementation and is not the focus of this proposal, but it should be taken into account.
157
+
158
+ # Drawbacks
159
+
160
+ 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.
161
+
162
+ # Alternatives
163
+
164
+ An alternative would be keeping the current strategy of declaring filters.
165
+ 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.
166
+
167
+ # Adoption strategy
168
+
169
+ 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.
170
+
171
+ 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.
172
+
173
+ # How we teach this
174
+
175
+ 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.
176
+
177
+ We're also going to provide utility functions to migrate filters from old style to new style.
178
+
179
+ # Unresolved questions
180
+
181
+ This is the full design and there are no unresolved questions.
182
+
183
+ [filters-high-level-doc]: https://docs.haystack.deepset.ai/docs/metadata-filtering
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6141-meta-field-ranker.md ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: Meta Field Ranker
2
+ - Decision driver: @domenicocinque
3
+ - Start Date: 2023-10-20
4
+ - Proposal PR: https://github.com/deepset-ai/haystack/pull/6141
5
+ - Github Issue or Discussion: https://github.com/deepset-ai/haystack/issues/6054
6
+
7
+ # Summary
8
+
9
+ This ranker should allow to sort the documents based on a meta field of choice.
10
+
11
+ # Basic example
12
+
13
+ The ranker could be instantiated as follows:
14
+
15
+ ``` python
16
+ ranker = MetaFieldRanker(
17
+ meta_field="rating",
18
+ weight="0.5",
19
+ ascending=False,
20
+ top_k=3,
21
+ )
22
+ ```
23
+ In the context of a simple pipeline with a retriever and a MetaFieldRanker in which
24
+ the documents are provided with a meta field "rating". The documents are first retrieved by the retriever and
25
+ then sorted by the MetaFieldRanker.
26
+
27
+ ``` python
28
+ pipeline = Pipeline()
29
+ pipeline.add_component(component=InMemoryBM25Retriever(document_store=document_store, top_k=20)
30
+ , name="Retriever")
31
+ pipeline.add_component(component=MetaFieldRanker(meta_field="rating"), name="Ranker")
32
+ pipeline.connect("Retriever.documents", "MetaFieldRanker.documents")
33
+ ```
34
+
35
+ # Motivation
36
+
37
+ I found the need for this feature while working on system that retrieves books based on their description and the
38
+ similarity to the query. After retrieving the documents it makes sense to expose them to the user in order of popularity.
39
+ This is just one example of a use case for this feature, but I think it could be useful in many other contexts.
40
+
41
+ # Detailed design
42
+
43
+ The actual implementation of the ranker is very similar to the already present RecentnessRanker. The main difference
44
+ is to remove the date parsing logic.
45
+
46
+ # Drawbacks
47
+
48
+ The main drawback is that it would be very similar to the already present RecentnessRanker. However, this could be
49
+ solved by making the RecentnessRanker a subclass of the MetaFieldRanker and adding the date parsing logic to it.
50
+ Apart from that, it is a very simple component that should not have any other drawbacks.
51
+
52
+ # Alternatives
53
+
54
+ The alternative is to make the user implement its own ranking logic.
55
+
56
+ # Adoption strategy
57
+
58
+ 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.
59
+
60
+ # How we teach this
61
+
62
+ It would be sufficient to integrate a small comparison with the RecentnessRanker in the documentation.
63
+
64
+
65
+ # Unresolved questions
66
+
67
+ The main issue is the implementation strategy. Especially if we want to include the `ranking_mode` parameter in the
68
+ MetaFieldRanker, it would make sense to have the RecentnessRanker as a subclass of the MetaFieldRanker.
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/6784-integrations-for-eval-framworks.md ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: Integration of LLM Evaluation Frameworks
2
+ - Decision driver: Madeesh Kannan, Julian Risch
3
+ - Start Date: 2024-01-19
4
+ - Proposal PR: https://github.com/deepset-ai/haystack/pull/6784
5
+ - Github Issue or Discussion: https://github.com/deepset-ai/haystack/issues/6672
6
+
7
+ # Summary
8
+
9
+ - Create integrations for three different LLM evaluation frameworks in https://github.com/deepset-ai/haystack-core-integrations
10
+ - 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).
11
+ - The integrations introduce the following components in this order: `UptrainEvaluator`, `RagasEvaluator`, `DeepEvalEvaluator`.
12
+ - Users can run a Haystack pipeline and evaluate the result with model-based metrics implemented by the evaluation frameworks.
13
+ - Calculation of metrics is done by the frameworks through running prompts with OpenAI (Uptrain) or using langchain to make the OpenAI call (RAGAS, DeepEval).
14
+
15
+ # Basic example
16
+
17
+ 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:
18
+
19
+ ```python
20
+ p = Pipeline()
21
+ p.add_component(instance=DeepEvalEvaluator(metric="Hallucination", params={"threshold": 0.3)}, name="evaluator"))
22
+ # p.add_component(instance=RagasEvaluator()...
23
+
24
+ questions = [...]
25
+ contexts = [...]
26
+ answers = [...]
27
+
28
+ p.run({"evaluator": {"questions": questions, "context": contexts, "answer": answers})
29
+ # {"evaluator": DeepEvalResult(metric='hallucination', score=0.817)}
30
+ ```
31
+
32
+ # Motivation
33
+
34
+ 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.
35
+
36
+ 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.
37
+
38
+ 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.
39
+
40
+ # Detailed design
41
+
42
+ 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.
43
+
44
+ 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.
45
+
46
+ The implementation of the three evaluator components should follow the general guidelines for custom component development. There are two approaches we could take:
47
+
48
+ - **Metric wrapping**: Make each metric an individual component.
49
+
50
+ Advantages:
51
+
52
+ - Inputs and outputs are explicitly defined for each metric, which makes the API more explicit.
53
+ - We can control which metrics to include.
54
+ - We can use the execution graph for control flow.
55
+
56
+ Disadvantages:
57
+
58
+ - Duplication between frameworks.
59
+ - Maintenance burden.
60
+ - Less freedom for the user.
61
+
62
+ - **Framework wrapping**: Make each evaluation framework an individual component.
63
+
64
+ Advantages:
65
+
66
+ - Straightforward implementation.
67
+ - Easier to reason about.
68
+ - Low maintenance burden.
69
+ - More freedom for the user.
70
+
71
+ Disadvantages:
72
+
73
+ - API has to accommodate all possible inputs for all supported metrics.
74
+ - Less flexibility.
75
+
76
+ 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.
77
+
78
+ ## API overview
79
+
80
+ - We implement three components: `DeepEvalEvaluator`, `RagasEvaluator`, `UpTrainEvaluator`.
81
+ - Their constructors take a two parameters: `Literal["MetricName"]` and `Optional[Dict[str, Any]]` for the metric name and optional parameters for the same.
82
+ - We use JSON-serializable types here to ensure serde support.
83
+ - The component initializes the internal framework-specific metric representation.
84
+ - 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.
85
+ - This approach lets the user modulate the inputs individually, which wouldn't be possible if we use a generic representation for all metrics/frameworks.
86
+ - Outputs can be implemented in one of two ways:
87
+
88
+ - `set_output_types` is also called to enumerate the outputs of the metric
89
+ - The output is a `dataclass` specific to the evaluation framework.
90
+
91
+ 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.
92
+
93
+ ### Illustrative example
94
+
95
+ ```python
96
+ from deepeval import BaseMetric, FaithfulnessMetric
97
+
98
+ @component
99
+ class DeepEvalEvaluator:
100
+ self._metric: BaseMetric
101
+
102
+ def __init__(self, metric: str, params: Optional[Dict[str, Any]]):
103
+ params = {} if params is None
104
+ if metric == "Faithfulness":
105
+ self._metric = FaithfulnessMetric(**params)
106
+ self.set_input_types(questions=List[str], answers=List[str], contexts=Listt[List[str]])
107
+ elif metric == "ContextRecall":
108
+ ...
109
+
110
+ def run(self, **kwargs):
111
+ # Logic to unwrap the inputs based on the metric and
112
+ # execute the backend code.
113
+ ...
114
+
115
+ ```
116
+
117
+ # Drawbacks
118
+
119
+ - **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.
120
+ - **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.
121
+ - **Additional dependencies**: RAGAS and DeepEval depend on langchain, whereas UpTrain uses both its own client and OpenAI's.
122
+ - https://github.com/confident-ai/deepeval/blob/main/pyproject.toml
123
+ - https://github.com/explodinggradients/ragas/blob/main/pyproject.toml
124
+ - https://github.com/uptrain-ai/uptrain/blob/main/pyproject.toml
125
+
126
+ # Alternatives
127
+
128
+ - Eschewing the pipeline paradigm and using a separate evaluation API.
129
+ - Similar to how it was done in Haystack 1.x.
130
+ - Implement them as components but run them individually.
131
+ - This would also be possible with the proposed API.
132
+
133
+ # Adoption strategy
134
+
135
+ 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.
136
+
137
+ # How we teach this
138
+
139
+ 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.
140
+
141
+ 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.
142
+
143
+ 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.
144
+
145
+ # Unresolved questions & future work
146
+
147
+ - 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.
148
+ - We envision an `Evaluator` component in Haystack's core with customizable model and prompt.
149
+ - 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).
150
+ - Alternative take on the evaluation API - https://github.com/deepset-ai/haystack/pull/5794/
151
+ - The ideas proposed in the above should compatible with those of this proposal.
SPFsmartGATE/LIVE/TMP/haystack/proposals/text/7462-rag-evaluation.md ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - Title: Proposal for presentation of evaluation results
2
+ - Decision driver: David S. Batista
3
+ - Start Date: 2024-04-03
4
+ - Proposal PR: #7462
5
+ - Github Issue or Discussion: https://github.com/deepset-ai/haystack/issues/7398
6
+
7
+ # Summary
8
+
9
+ Add a new component to Haystack allowing users interact with the results of evaluating the performance of a RAG model.
10
+
11
+
12
+ # Motivation
13
+
14
+ 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.
15
+
16
+
17
+ # Detailed design
18
+
19
+ The output results of an evaluation pipeline composed of `evaluator` components are passed to a `EvaluationResults`
20
+ (this is a placeholder name) which stores them internally and acts as an interface to access and present the results.
21
+
22
+ The examples below are just for illustrative purposes and are subject to change.
23
+
24
+ Example of the data structure that the `EvaluationResults` class will receive for initialization:
25
+
26
+ ```python
27
+
28
+ data = {
29
+ "inputs": {
30
+ "query_id": ["53c3b3e6", "225f87f7"],
31
+ "question": ["What is the capital of France?", "What is the capital of Spain?"],
32
+ "contexts": ["wiki_France", "wiki_Spain"],
33
+ "answer": ["Paris", "Madrid"],
34
+ "predicted_answer": ["Paris", "Madrid"]
35
+ },
36
+ "metrics":
37
+ [
38
+ {"name": "reciprocal_rank", "scores": [0.378064, 0.534964, 0.216058, 0.778642]},
39
+ {"name": "single_hit", "scores": [1, 1, 0, 1]},
40
+ {"name": "multi_hit", "scores": [0.706125, 0.454976, 0.445512, 0.250522]},
41
+ {"name": "context_relevance", "scores": [0.805466, 0.410251, 0.750070, 0.361332]},
42
+ {"name": "faithfulness", "scores": [0.135581, 0.695974, 0.749861, 0.041999]},
43
+ {"name": "semantic_answer_similarity", "scores": [0.971241, 0.159320, 0.019722, 1]}
44
+ ],
45
+ },
46
+
47
+ ```
48
+
49
+ The `EvaluationResults` class provides the following methods to different types of users:
50
+
51
+ Basic users:
52
+ - `individual_aggregate_score_report()`
53
+ - `comparative_aggregate_score_report()`
54
+
55
+ Intermediate users:
56
+ - `individual_detailed_score_report()`
57
+ - `comparative_detailed_score_report()`
58
+
59
+ Advanced users:
60
+ - `find_thresholds()`
61
+ - `find_inputs_below_threshold()`
62
+
63
+
64
+ ### Methods description
65
+ An evaluation report that provides a summary of the performance of the model across all queries, showing the
66
+ aggregated scores for all available metrics.
67
+
68
+ ```python
69
+ def individual_aggregate_score_report():
70
+ ```
71
+
72
+ Example output
73
+
74
+ ```bash
75
+ {'Reciprocal Rank': 0.448,
76
+ 'Single Hit': 0.5,
77
+ 'Multi Hit': 0.540,
78
+ 'Context Relevance': 0.537,
79
+ 'Faithfulness': 0.452,
80
+ 'Semantic Answer Similarity': 0.478
81
+ }
82
+ ```
83
+
84
+ A detailed evaluation report that provides the scores of all available metrics for all queries or a subset of queries.
85
+
86
+ ```python
87
+ def individual_detailed_score_report(queries: Union[List[str], str] = "all"):
88
+ ```
89
+
90
+ Example output
91
+
92
+ ```bash
93
+ | question | context | answer | predicted_answer | reciprocal_rank | single_hit | multi_hit | context_relevance | faithfulness | semantic_answer_similarity |
94
+ |----------|---------|--------|------------------|-----------------|------------|-----------|-------------------|-------------|----------------------------|
95
+ | What is the capital of France? | wiki_France | Paris | Paris | 0.378064 | 1 | 0.706125 | 0.805466 | 0.135581 | 0.971241 |
96
+ | What is the capital of Spain? | wiki_Spain | Madrid | Madrid | 0.534964 | 1 | 0.454976 | 0.410251 | 0.695974 | 0.159320 |
97
+ ```
98
+
99
+ ### Comparative Evaluation Report
100
+
101
+ A comparative summary that compares the performance of the model with another model based on the aggregated scores
102
+ for all available metrics.
103
+
104
+ ```python
105
+ def comparative_aggregate_score_report(self, other: "EvaluationResults"):
106
+ ```
107
+
108
+ ```bash
109
+ {
110
+ "model_1": {
111
+ 'Reciprocal Rank': 0.448,
112
+ 'Single Hit': 0.5,
113
+ 'Multi Hit': 0.540,
114
+ 'Context Relevance': 0.537,
115
+ 'Faithfulness': 0.452,
116
+ 'Semantic Answer Similarity': 0.478
117
+ },
118
+ "model_2": {
119
+ 'Reciprocal Rank': 0.448,
120
+ 'Single Hit': 0.5,
121
+ 'Multi Hit': 0.540,
122
+ 'Context Relevance': 0.537,
123
+ 'Faithfulness': 0.452,
124
+ 'Semantic Answer Similarity': 0.478
125
+ }
126
+ }
127
+
128
+ ```
129
+
130
+ A detailed comparative summary that compares the performance of the model with another model based on the scores of all
131
+ available metrics for all queries.
132
+
133
+
134
+ ```python
135
+ def comparative_detailed_score_report(self, other: "EvaluationResults"):
136
+ ```
137
+
138
+ ```bash
139
+ | 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 |
140
+ |----------|---------|--------|--------------------------|--------------------------|-------------------------|-------------------------|--------------------|--------------------|-------------------|-------------------|---------------------------|---------------------------|----------------------|----------------------|------------------------------------|------------------------------------|
141
+ | 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 |
142
+ | 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 |
143
+ ````
144
+
145
+
146
+ Have a method to find interesting scores thresholds, typically used for error analysis, for all metrics available.
147
+ Some potentially interesting thresholds to find are: the 25th percentile, the 75th percentile, the mean , the median.
148
+
149
+ ```python
150
+ def find_thresholds(self, metrics: List[str]) -> Dict[str, float]:
151
+ ```
152
+
153
+ ```bash
154
+ data = {
155
+ "thresholds": ["25th percentile", "75th percentile", "median", "average"],
156
+ "reciprocal_rank": [0.378064, 0.534964, 0.216058, 0.778642],
157
+ "context_relevance": [0.805466, 0.410251, 0.750070, 0.361332],
158
+ "faithfulness": [0.135581, 0.695974, 0.749861, 0.041999],
159
+ "semantic_answer_similarity": [0.971241, 0.159320, 0.019722, 1],
160
+ }
161
+ ````
162
+
163
+ Then have another method that
164
+
165
+ ```python
166
+ def find_inputs_below_threshold(self, metric: str, threshold: float):
167
+ """Get the all the queries with a score below a certain threshold for a given metric"""
168
+ ```
169
+
170
+ # Drawbacks
171
+
172
+ - Having the output in a format table may not be flexible enough, and maybe too verbose for datasets with a large number of queries.
173
+ - Maybe the option to export to a .csv file would be better than having the output in a table format.
174
+ - Maybe a JSON format would be better with the option for advanced users to do further analysis and visualization.
175
+
176
+
177
+ # Adoption strategy
178
+
179
+ - 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.
180
+
181
+ # How we teach this
182
+
183
+ - A tutorial would be the best approach to teach users how to use this feature.
184
+ - Adding a new entry to the documentation.
185
+
186
+ # User stories
187
+
188
+ ### 1. I would like to get a single summary score for my RAG pipeline so I can compare several pipeline configurations.
189
+
190
+ Run `individual_aggregate_score_report()` and get the following output:
191
+
192
+ ```bash
193
+ {'Reciprocal Rank': 0.448,
194
+ 'Single Hit': 0.5,
195
+ 'Multi Hit': 0.540,
196
+ 'Context Relevance': 0.537,
197
+ 'Faithfulness': 0.452,
198
+ 'Semantic Answer Similarity': 0.478
199
+ }
200
+ ```
201
+
202
+ ### 2. I am not sure what evaluation metrics work best for my RAG pipeline, specially when using the more novel LLM-based
203
+
204
+ Use `context relevance` or `faithfulness`
205
+
206
+ ### 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.
207
+
208
+ 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:
209
+
210
+ find_inputs_below_threshold("reciprocal_rank", <threshold>)
211
+
212
+ If the low score is in `reciprocal_rank` one can first get thresholds for this metric using:
213
+
214
+ `find_thresholds(["reciprocal_rank"])`
215
+
216
+ this will give:
217
+
218
+ - 25th percentile: (Q1) the value below which 25% of the data falls.
219
+ - median percentile: (Q2) the value below which 50% of the data falls.
220
+ - 75th percentile: (Q3) the value below which 75% of the data falls.
221
+
222
+ this can help to decide what is considered a low score, and then get, for instance, queries with a score below
223
+ the Q2 threshold using `find_inputs_below_threshold("context_relevance", threshold)`
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-TEI-embedders-8c76593bc25a7219.yaml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ features:
3
+ - |
4
+ Add HuggingFace TEI Embedders - `HuggingFaceTEITextEmbedder` and `HuggingFaceTEIDocumentEmbedder`.
5
+
6
+ An example using `HuggingFaceTEITextEmbedder` to embed a string:
7
+ ```python
8
+ from haystack.components.embedders import HuggingFaceTEITextEmbedder
9
+ text_to_embed = "I love pizza!"
10
+ text_embedder = HuggingFaceTEITextEmbedder(
11
+ model="BAAI/bge-small-en-v1.5", url="<your-tei-endpoint-url>", token="<your-token>"
12
+ )
13
+ print(text_embedder.run(text_to_embed))
14
+ # {'embedding': [0.017020374536514282, -0.023255806416273117, ...],
15
+ ```
16
+
17
+ An example using `HuggingFaceTEIDocumentEmbedder` to create Document embeddings:
18
+ ```python
19
+ from haystack.dataclasses import Document
20
+ from haystack.components.embedders import HuggingFaceTEIDocumentEmbedder
21
+ doc = Document(content="I love pizza!")
22
+ document_embedder = HuggingFaceTEIDocumentEmbedder(
23
+ model="BAAI/bge-small-en-v1.5", url="<your-tei-endpoint-url>", token="<your-token>"
24
+ )
25
+ result = document_embedder.run([doc])
26
+ print(result["documents"][0].embedding)
27
+ # [0.017020374536514282, -0.023255806416273117, ...]
28
+ ```
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-answerbuilder-2.0-5dd255eeba68041f.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ preview:
3
+ - |
4
+ Add the `AnswerBuilder` component for Haystack 2.0 that creates Answer objects from the string output of Generators.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-apple-silicon-gpu-acceleration-38bf69781a933b95.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ enhancements:
3
+ - |
4
+ Added support for Apple Silicon GPU acceleration through "mps pytorch", enabling better performance on Apple M1 hardware.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-apply_filter_policy-function-ae3152e6afe0ca57.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ enhancements:
3
+ - |
4
+ 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).
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure-kwargs-6a5ab1358ef7f44c.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ---
2
+ enhancements:
3
+ - |
4
+ Expose default_headers to pass custom headers to Azure API including APIM subscription key.
5
+ - |
6
+ Add optional azure_kwargs dictionary parameter to pass in parameters undefined in Haystack but supported by AzureOpenAI.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-azure_ocr_doc_converter-935130b3b243d236.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ preview:
3
+ - |
4
+ Add AzureOCRDocumentConverter to convert files of different types using Azure's Document Intelligence Service.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-batch_size_faiss_init-5e97c1fb9409f873.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ---
2
+ enhancements:
3
+ - |
4
+ Add batch_size to the __init__ method of FAISS Document Store. This works as the default value for all methods of
5
+ FAISS Document Store that support batch_size.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-blob-type-2a9476a39841f54d.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ---
2
+ preview:
3
+ - |
4
+ Add ByteStream type to send binary raw data across components
5
+ in a pipeline.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-branch-joiner-037298459ca74077.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ highlights: >
3
+ The `Multiplexer` component proved to be hard to explain and to understand. After reviewing its use cases, the documentation
4
+ was rewritten and the component was renamed to `BranchJoiner` to better explain its functionalities.
5
+ upgrade:
6
+ - |
7
+ `BranchJoiner` has the very same interface as `Multiplexer`. To upgrade your code, just rename any occurrence
8
+ of `Multiplexer` to `BranchJoiner` and ajdust the imports accordingly.
9
+ features:
10
+ - |
11
+ Add `BranchJoiner` to eventually replace `Multiplexer`
12
+ deprecations:
13
+ - |
14
+ `Mulitplexer` is now deprecated.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-calculate-metrics-metricsresults-03bf27ce8b16cff5.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ---
2
+ features:
3
+ - |
4
+ Adds `calculate_metrics()` function to EvaluationResult for computation of evaluation metrics.
5
+ Adds `Metric` class to store list of available metrics.
6
+ Adds `MetricsResult` class to store the metric values computed during the evaluation.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-custom-filters-to-conditional-router-631eba8bab3c2ae7.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ---
2
+ features:
3
+ - |
4
+ Added custom filters support to ConditionalRouter. Users can now pass in
5
+ one or more custom Jinja2 filter callables and be able to access those
6
+ filters when defining condition expressions in routes.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-default-value-to-input-socket-2e62116fc4be5214.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ---
2
+ enhancements:
3
+ - |
4
+ Add a field called `default_value` to the `InputSocket` dataclass.
5
+ Derive `is_mandatory` value from the presence of `default_value`.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-document-writer-number-of-documents-written-2c57f3a5d6ae2131.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ enhancements:
3
+ - |
4
+ Document writer returns the number of documents written.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-dynamic-prompt-builder-e61c4b11405b8d80.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ---
2
+ preview:
3
+ - |
4
+ Add `DynamicPromptBuilder` to dynamically generate prompts from either a list of ChatMessage instances or a string
5
+ template, leveraging Jinja2 templating for flexible and efficient prompt construction.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-exact-match-a7df21717238b771.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ features:
3
+ - |
4
+ Adds support for the Exact Match metric to `EvaluationResult.calculate_metrics(...)`:
5
+ ```python
6
+ from haystack.evaluation.metrics import Metric
7
+ exact_match_metric = eval_result.calculate_metrics(Metric.EM, output_key="answers")
8
+ ```
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-f1-d54cc900bec753f7.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ features:
3
+ - |
4
+ Adds support for the F1 metric to `EvaluationResult.calculate_metrics(...)`:
5
+ ```python
6
+ from haystack.evaluation.metrics import Metric
7
+ f1_metric = eval_result.calculate_metrics(Metric.F1, output_key="answers")
8
+ ```
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-huggingface-tgi-generator-9d7eed86f5246ea9.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ---
2
+ preview:
3
+ - |
4
+ Adds `HuggingFaceTGIGenerator` for text generation. This components support remote inferencing for
5
+ Hugging Face LLMs via text-generation-inference (TGI) protocol.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-indexing-ready-made-pipeline-85c1da2f8f910f9d.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ features:
3
+ - |
4
+ Add a indexing `build_indexing_pipeline` utility function
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-keep-id-to-document-cleaner-2a9854b5f195bb78.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ enhancements:
3
+ - |
4
+ The `DocumentCleaner` class has the optional attribute `keep_id` that if set to True it keeps the document ids unchanged after cleanup.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-link-content-fetcher-145915976f38e1e0.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ---
2
+ preview:
3
+ - |
4
+ Introduced the LinkContentFetcher in Haystack 2.0. This component fetches content from specified
5
+ URLs and converts them into ByteStream objects for further processing in Haystack pipelines.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-lost-in-the-middle-ranker-6ad7dda754fad5a9.yaml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ prelude: >
3
+ We're excited to introduce a new ranker to Haystack - LostInTheMiddleRanker.
4
+ It reorders documents based on the "Lost in the Middle" order, a strategy that
5
+ places the most relevant paragraphs at the beginning or end of the context,
6
+ while less relevant paragraphs are positioned in the middle. This ranker,
7
+ based on the research paper "Lost in the Middle: How Language Models Use Long
8
+ Contexts" by Liu et al., can be leveraged in Retrieval-Augmented Generation
9
+ (RAG) pipelines.
10
+ features:
11
+ - |
12
+ The LostInTheMiddleRanker can be used like other rankers in Haystack. After
13
+ initializing LostInTheMiddleRanker with the desired parameters, it can be
14
+ used to rank/reorder a list of documents based on the "Lost in the Middle"
15
+ order - the most relevant documents are located at the top and bottom of
16
+ the returned list, while the least relevant documents are found in the
17
+ middle. We advise that you use this ranker in combination with other rankers,
18
+ and to place it towards the end of the pipeline.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-lost-in-the-middle-ranker-976f2e9bf83c3c68.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ ---
2
+
3
+ features:
4
+ - |
5
+ Add LostInTheMiddleRanker.
6
+ It reorders documents based on the "Lost in the Middle" order, a strategy that
7
+ places the most relevant paragraphs at the beginning or end of the context,
8
+ while less relevant paragraphs are positioned in the middle.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-markdown-file-type-router-support-39a607faa5c1436f.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ enhancements:
3
+ - |
4
+ Adds markdown mimetype support to the file type router i.e. `FileTypeRouter` class.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-metadata-HTMLToDocument-42dbd074a46c979e.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ preview:
3
+ - |
4
+ Adds support for adding additional metadata and utilizing metadata received from ByteStream sources when creating documents using HTMLToDocument.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-metadata_router-2.0-63829ac5a0528e9d.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ preview:
3
+ - |
4
+ Add `MetadataRouter`, a component that routes documents to different edges based on the content of their fields
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-min-top-k-top-p-sampler-dc65f97d420e70b0.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ enhancements:
3
+ - |
4
+ 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.
SPFsmartGATE/LIVE/TMP/haystack/releasenotes/notes/add-mrr-metric-362527e55e21c24c.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ---
2
+ features:
3
+ - |
4
+ Add support for Mean Reciprocal Rank (MRR) Metric to `StatisticalEvaluator`.
5
+ MRR measures the mean reciprocal rank of times a label is present in at least one or more predictions.