openaidocumentembedder.mdx
  1  ---
  2  title: "OpenAIDocumentEmbedder"
  3  id: openaidocumentembedder
  4  slug: "/openaidocumentembedder"
  5  description: "OpenAIDocumentEmbedder computes the embeddings of a list of documents and stores the obtained vectors in the embedding field of each document. It uses OpenAI embedding models."
  6  ---
  7  
  8  # OpenAIDocumentEmbedder
  9  
 10  OpenAIDocumentEmbedder computes the embeddings of a list of documents and stores the obtained vectors in the embedding field of each document. It uses OpenAI embedding models.
 11  
 12  The vectors computed by this component are necessary to perform embedding retrieval on a collection of documents. At retrieval time, the vector representing the query is compared with those of the documents to find the most similar or relevant documents.
 13  
 14  |  |  |
 15  | --- | --- |
 16  | **Most common position in a pipeline** | Before a [`DocumentWriter`](../writers/documentwriter.mdx)  in an indexing pipeline |
 17  | **Mandatory init variables** | "api_key": An OpenAI API key. Can be set with `OPENAI_API_KEY` env var. |
 18  | **Mandatory run variables** | "documents": A list of documents |
 19  | **Output variables** | "documents": A list of documents (enriched with embeddings)  <br /> <br />"meta": A dictionary of metadata |
 20  | **API reference** | [Embedders](/reference/embedders-api) |
 21  | **GitHub link** | https://github.com/deepset-ai/haystack/blob/main/haystack/components/embedders/openai_document_embedder.py |
 22  
 23  ## Overview
 24  
 25  To see the list of compatible OpenAI embedding models, head over to OpenAI [documentation](https://platform.openai.com/docs/guides/embeddings/embedding-models). The default model for `OpenAIDocumentEmbedder` is `text-embedding-ada-002`. You can specify another model with the `model` parameter when initializing this component.
 26  
 27  This component should be used to embed a list of documents. To embed a string, use the [OpenAITextEmbedder](openaitextembedder.mdx).
 28  
 29  The component uses an `OPENAI_API_KEY` environment variable by default. Otherwise, you can pass an API key at initialization with `api_key`:
 30  
 31  ```
 32  embedder = OpenAIDocumentEmbedder(api_key=Secret.from_token("<your-api-key>"))
 33  ```
 34  
 35  ### Embedding Metadata
 36  
 37  Text documents often come with a set of metadata. If they are distinctive and semantically meaningful, you can embed them along with the text of the document to improve retrieval.
 38  
 39  You can do this easily by using the Document Embedder:
 40  
 41  ```python
 42  from haystack import Document
 43  from haystack.components.embedders import OpenAIDocumentEmbedder
 44  
 45  doc = Document(content="some text", meta={"title": "relevant title", "page number": 18})
 46  
 47  embedder = OpenAIDocumentEmbedder(meta_fields_to_embed=["title"])
 48  
 49  docs_w_embeddings = embedder.run(documents=[doc])["documents"]
 50  ```
 51  
 52  ## Usage
 53  
 54  ### On its own
 55  
 56  Here is how you can use the component on its own:
 57  
 58  ```python
 59  from haystack.components.embedders import OpenAIDocumentEmbedder
 60  
 61  doc = Document(content="I love pizza!")
 62  
 63  document_embedder = OpenAIDocumentEmbedder(api_key=Secret.from_token("<your-api-key>"))
 64  
 65  result = document_embedder.run([doc])
 66  print(result["documents"][0].embedding)
 67  
 68  ## [0.017020374536514282, -0.023255806416273117, ...]
 69  ```
 70  
 71  :::note
 72  We recommend setting OPENAI_API_KEY as an environment variable instead of setting it as a parameter.
 73  
 74  :::
 75  
 76  ### In a pipeline
 77  
 78  ```python
 79  from haystack import Pipeline
 80  from haystack.document_stores.in_memory import InMemoryDocumentStore
 81  from haystack.components.embedders import OpenAITextEmbedder, OpenAIDocumentEmbedder
 82  from haystack.components.writers import DocumentWriter
 83  from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever
 84  
 85  document_store = InMemoryDocumentStore(embedding_similarity_function="cosine")
 86  
 87  documents = [
 88      Document(content="My name is Wolfgang and I live in Berlin"),
 89      Document(content="I saw a black horse running"),
 90      Document(content="Germany has many big cities"),
 91  ]
 92  
 93  indexing_pipeline = Pipeline()
 94  indexing_pipeline.add_component("embedder", OpenAIDocumentEmbedder())
 95  indexing_pipeline.add_component("writer", DocumentWriter(document_store=document_store))
 96  indexing_pipeline.connect("embedder", "writer")
 97  
 98  indexing_pipeline.run({"embedder": {"documents": documents}})
 99  
100  query_pipeline = Pipeline()
101  query_pipeline.add_component("text_embedder", OpenAITextEmbedder())
102  query_pipeline.add_component(
103      "retriever",
104      InMemoryEmbeddingRetriever(document_store=document_store),
105  )
106  query_pipeline.connect("text_embedder.embedding", "retriever.query_embedding")
107  
108  query = "Who lives in Berlin?"
109  
110  result = query_pipeline.run({"text_embedder": {"text": query}})
111  
112  print(result["retriever"]["documents"][0])
113  
114  ## Document(id=..., mimetype: 'text/plain',
115  ##  text: 'My name is Wolfgang and I live in Berlin')
116  ```