answerbuilder.mdx
  1  ---
  2  title: "AnswerBuilder"
  3  id: answerbuilder
  4  slug: "/answerbuilder"
  5  description: "Use this component in pipelines that contain a Generator to parse its replies."
  6  ---
  7  
  8  # AnswerBuilder
  9  
 10  Use this component in pipelines that contain a Generator to parse its replies.
 11  
 12  <div className="key-value-table">
 13  
 14  |  |  |
 15  | --- | --- |
 16  | **Most common position in a pipeline** | Use in pipelines (such as a RAG pipeline) after a [Generator](../generators.mdx)  component to create [`GeneratedAnswer`](../../concepts/data-classes.mdx#generatedanswer)   objects from its replies. |
 17  | **Mandatory run variables** | `query`: A query string  <br /> <br />`replies`: A list of strings, or a list of [`ChatMessage`](../../concepts/data-classes/chatmessage.mdx)   objects that are replies from a Generator |
 18  | **Output variables** | `answers`:  A list of `GeneratedAnswer` objects |
 19  | **API reference** | [Builders](/reference/builders-api) |
 20  | **GitHub link** | https://github.com/deepset-ai/haystack/blob/main/haystack/components/builders/answer_builder.py |
 21  
 22  </div>
 23  
 24  ## Overview
 25  
 26  `AnswerBuilder` takes a query and the replies a Generator returns as input and parses them into `GeneratedAnswer` objects. Optionally, it also takes documents and metadata from the Generator as inputs to enrich the `GeneratedAnswer` objects.
 27  
 28  The `AnswerBuilder` works with both Chat and non-Chat Generators.
 29  
 30  The optional `pattern` parameter defines how to extract answer texts from replies. It needs to be a regular expression with a maximum of one capture group. If a capture group is present, the text matched by the capture group is used as the answer. If no capture group is present, the whole match is used as the answer. If no `pattern` is set, the whole reply is used as the answer text.
 31  
 32  The optional `reference_pattern` parameter can be set to a regular expression that parses referenced documents from the replies so that only those referenced documents are listed in the `GeneratedAnswer` objects. Haystack assumes that documents are referenced by their index in the list of input documents and that indices start at 1. For example, if you set the `reference_pattern` to _`\\[(\\d+)\\]`,_ it finds “1” in a string "This is an answer[1]". If `reference_pattern` is not set, all input documents are listed in the `GeneratedAnswer` objects.
 33  
 34  ## Usage
 35  
 36  ### On its own
 37  
 38  Below is an example where we’re using the `AnswerBuilder` to parse a string that could be the reply received from a Generator using a custom regular expression. Any text other than the answer will not be included in the `GeneratedAnswer` object constructed by the builder.
 39  
 40  ```python
 41  from haystack.components.builders import AnswerBuilder
 42  
 43  builder = AnswerBuilder(pattern="Answer: (.*)")
 44  builder.run(
 45      query="What's the answer?",
 46      replies=["This is an argument. Answer: This is the answer."],
 47  )
 48  ```
 49  
 50  ### In a pipeline
 51  
 52  Below is an example of a RAG pipeline where we use an `AnswerBuilder` to create `GeneratedAnswer` objects from the replies returned by a Generator. In addition to the text of the reply, these objects also hold the query, the referenced docs, and metadata returned by the Generator.
 53  
 54  ```python
 55  from haystack import Pipeline
 56  from haystack.document_stores.in_memory import InMemoryDocumentStore
 57  from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
 58  from haystack.components.generators.chat import OpenAIChatGenerator
 59  from haystack.components.builders.chat_prompt_builder import ChatPromptBuilder
 60  from haystack.components.builders.answer_builder import AnswerBuilder
 61  from haystack.utils import Secret
 62  from haystack.dataclasses import ChatMessage
 63  from haystack.dataclasses import Document
 64  
 65  prompt_template = [
 66      ChatMessage.from_system("You are a helpful assistant."),
 67      ChatMessage.from_user(
 68          "Given these documents, answer the question.\nDocuments:\n"
 69          "{% for doc in documents %}{{ doc.content }}{% endfor %}\n"
 70          "Question: {{query}}\nAnswer:",
 71      ),
 72  ]
 73  
 74  docs = [
 75      Document(content="The capital of France is Paris"),
 76      Document(content="The capital of England is London"),
 77  ]
 78  document_store = InMemoryDocumentStore()
 79  document_store.write_documents(docs)
 80  
 81  p = Pipeline()
 82  p.add_component(
 83      instance=InMemoryBM25Retriever(document_store=document_store),
 84      name="retriever",
 85  )
 86  p.add_component(
 87      instance=ChatPromptBuilder(
 88          template=prompt_template,
 89          required_variables={"query", "documents"},
 90      ),
 91      name="prompt_builder",
 92  )
 93  p.add_component(
 94      instance=OpenAIChatGenerator(api_key=Secret.from_env_var("OPENAI_API_KEY")),
 95      name="llm",
 96  )
 97  p.add_component(instance=AnswerBuilder(), name="answer_builder")
 98  p.connect("retriever", "prompt_builder.documents")
 99  p.connect("prompt_builder", "llm.messages")
100  p.connect("llm.replies", "answer_builder.replies")
101  p.connect("retriever", "answer_builder.documents")
102  
103  query = "What is the capital of France?"
104  result = p.run(
105      {
106          "retriever": {"query": query},
107          "prompt_builder": {"query": query},
108          "answer_builder": {"query": query},
109      },
110  )
111  
112  print(result)
113  ```