Tutorial: semantic search with the inference API
editTutorial: semantic search with the inference API
editThe instructions in this tutorial shows you how to use the inference API with
various services to perform semantic search on your data. The following examples
use Cohere’s embed-english-v3.0
model, the all-mpnet-base-v2
model from
HuggingFace, and OpenAI’s text-embedding-ada-002
second generation embedding
model. You can use any Cohere and OpenAI models, they are all supported by the
inference API. For a list of supported models available on HuggingFace, refer to
the supported model list.
Click the name of the service you want to use on any of the widgets below to review the corresponding instructions.
Requirements
editA Cohere account is required to use the inference API with the Cohere service.
A HuggingFace account is required to use the inference API with the HuggingFace service.
An OpenAI account is required to use the inference API with the OpenAI service.
Create an inference endpoint
editCreate an inference endpoint by using the Create inference API:
PUT _inference/text_embedding/cohere_embeddings { "service": "cohere", "service_settings": { "api_key": "<api_key>", "model_id": "embed-english-v3.0", "embedding_type": "byte" } }
The task type is |
|
The API key of your Cohere account. You can find your API keys in your Cohere dashboard under the API keys section. You need to provide your API key only once. The Get inference API does not return your API key. |
|
The name of the embedding model to use. You can find the list of Cohere embedding models here. |
When using this model the recommended similarity measure to use in the
dense_vector
field mapping is dot_product
. In the case of Cohere models, the
embeddings are normalized to unit length in which case the dot_product
and
the cosine
measures are equivalent.
First, you need to create a new inference endpoint on
the Hugging Face endpoint page to get an
endpoint URL. Select the model all-mpnet-base-v2
on the new endpoint creation
page, then select the Sentence Embeddings
task under the Advanced
configuration section. Create the endpoint. Copy the URL after the endpoint
initialization has been finished, you need the URL in the following inference API
call.
PUT _inference/text_embedding/hugging_face_embeddings { "service": "hugging_face", "service_settings": { "api_key": "<access_token>", "url": "<url_endpoint>" } }
The task type is |
|
A valid HuggingFace access token. You can find on the settings page of your account. |
|
The inference endpoint URL you created on Hugging Face. |
PUT _inference/text_embedding/openai_embeddings { "service": "openai", "service_settings": { "api_key": "<api_key>", "model_id": "text-embedding-ada-002" } }
The task type is |
|
The API key of your OpenAI account. You can find your OpenAI API keys in your OpenAI account under the API keys section. You need to provide your API key only once. The Get inference API does not return your API key. |
|
The name of the embedding model to use. You can find the list of OpenAI embedding models here. |
When using this model the recommended similarity measure to use in the
dense_vector
field mapping is dot_product
. In the case of OpenAI models, the
embeddings are normalized to unit length in which case the dot_product
and
the cosine
measures are equivalent.
Create the index mapping
editThe mapping of the destination index - the index that contains the embeddings
that the model will create based on your input text - must be created. The
destination index must have a field with the dense_vector
field type to index the output of the used model.
PUT cohere-embeddings { "mappings": { "properties": { "content_embedding": { "type": "dense_vector", "dims": 1024, "element_type": "byte" }, "content": { "type": "text" } } } }
The name of the field to contain the generated tokens. It must be refrenced in the inference pipeline configuration in the next step. |
|
The field to contain the tokens is a |
|
The output dimensions of the model. Find this value in the Cohere documentation of the model you use. |
|
The name of the field from which to create the dense vector representation.
In this example, the name of the field is |
|
The field type which is text in this example. |
PUT hugging-face-embeddings { "mappings": { "properties": { "content_embedding": { "type": "dense_vector", "dims": 768, "element_type": "float" }, "content": { "type": "text" } } } }
The name of the field to contain the generated tokens. It must be referenced in the inference pipeline configuration in the next step. |
|
The field to contain the tokens is a |
|
The output dimensions of the model. Find this value in the HuggingFace model documentation. |
|
The name of the field from which to create the dense vector representation.
In this example, the name of the field is |
|
The field type which is text in this example. |
PUT openai-embeddings { "mappings": { "properties": { "content_embedding": { "type": "dense_vector", "dims": 1536, "element_type": "float", "similarity": "dot_product" }, "content": { "type": "text" } } } }
The name of the field to contain the generated tokens. It must be refrenced in the inference pipeline configuration in the next step. |
|
The field to contain the tokens is a |
|
The output dimensions of the model. Find this value in the OpenAI documentation of the model you use. |
|
The faster` dot_product` function can be used to calculate similarity because OpenAI embeddings are normalised to unit length. You can check the OpenAI docs about which similarity function to use. |
|
The name of the field from which to create the dense vector representation.
In this example, the name of the field is |
|
The field type which is text in this example. |
Create an ingest pipeline with an inference processor
editCreate an ingest pipeline with an inference processor and use the model you created above to infer against the data that is being ingested in the pipeline.
PUT _ingest/pipeline/cohere_embeddings { "processors": [ { "inference": { "model_id": "cohere_embeddings", "input_output": { "input_field": "content", "output_field": "content_embedding" } } } ] }
The name of the inference endpoint you created by using the
Create inference API, it’s referred to as |
|
Configuration object that defines the |
PUT _ingest/pipeline/hugging_face_embeddings { "processors": [ { "inference": { "model_id": "hugging_face_embeddings", "input_output": { "input_field": "content", "output_field": "content_embedding" } } } ] }
The name of the inference endpoint you created by using the
Create inference API, it’s referred to as |
|
Configuration object that defines the |
response = client.ingest.put_pipeline( id: 'openai_embeddings', body: { processors: [ { inference: { model_id: 'openai_embeddings', input_output: { input_field: 'content', output_field: 'content_embedding' } } } ] } ) puts response
PUT _ingest/pipeline/openai_embeddings { "processors": [ { "inference": { "model_id": "openai_embeddings", "input_output": { "input_field": "content", "output_field": "content_embedding" } } } ] }
The name of the inference endpoint you created by using the
Create inference API, it’s referred to as |
|
Configuration object that defines the |
Load data
editIn this step, you load the data that you later use in the inference ingest pipeline to create embeddings from it.
Use the msmarco-passagetest2019-top1000
data set, which is a subset of the MS
MARCO Passage Ranking data set. It consists of 200 queries, each accompanied by
a list of relevant text passages. All unique passages, along with their IDs,
have been extracted from that data set and compiled into a
tsv file.
Download the file and upload it to your cluster using the
Data Visualizer
in the Machine Learning UI. Assign the name id
to the first column and content
to
the second column. The index name is test-data
. Once the upload is complete,
you can see an index named test-data
with 182469 documents.
Ingest the data through the inference ingest pipeline
editCreate the embeddings from the text by reindexing the data through the inference pipeline that uses the chosen model as the inference model.
POST _reindex?wait_for_completion=false { "source": { "index": "test-data", "size": 50 }, "dest": { "index": "cohere-embeddings", "pipeline": "cohere_embeddings" } }
The default batch size for reindexing is 1000. Reducing |
The rate limit of your Cohere account may affect the throughput of the reindexing process.
response = client.reindex( wait_for_completion: false, body: { source: { index: 'test-data', size: 50 }, dest: { index: 'openai-embeddings', pipeline: 'openai_embeddings' } } ) puts response
POST _reindex?wait_for_completion=false { "source": { "index": "test-data", "size": 50 }, "dest": { "index": "openai-embeddings", "pipeline": "openai_embeddings" } }
The default batch size for reindexing is 1000. Reducing |
The
rate limit of your OpenAI account
may affect the throughput of the reindexing process. If this happens, change
size
to 3
or a similar value in magnitude.
The call returns a task ID to monitor the progress:
GET _tasks/<task_id>
You can also cancel the reindexing process if you don’t want to wait until the reindexing process is fully complete which might take hours for large data sets:
POST _tasks/<task_id>/_cancel
Semantic search
editAfter the data set has been enriched with the embeddings, you can query the data
using semantic search. Pass a
query_vector_builder
to the k-nearest neighbor (kNN) vector search API, and
provide the query text and the model you have used to create the embeddings.
If you cancelled the reindexing process, you run the query only a part of the data which affects the quality of your results.
GET cohere-embeddings/_search { "knn": { "field": "content_embedding", "query_vector_builder": { "text_embedding": { "model_id": "cohere_embeddings", "model_text": "Muscles in human body" } }, "k": 10, "num_candidates": 100 }, "_source": [ "id", "content" ] }
As a result, you receive the top 10 documents that are closest in meaning to the
query from the cohere-embeddings
index sorted by their proximity to the query:
"hits": [ { "_index": "cohere-embeddings", "_id": "-eFWCY4BECzWLnMZuI78", "_score": 0.737484, "_source": { "id": 1690948, "content": "Oxygen is supplied to the muscles via red blood cells. Red blood cells carry hemoglobin which oxygen bonds with as the hemoglobin rich blood cells pass through the blood vessels of the lungs.The now oxygen rich blood cells carry that oxygen to the cells that are demanding it, in this case skeletal muscle cells.ther ways in which muscles are supplied with oxygen include: 1 Blood flow from the heart is increased. 2 Blood flow to your muscles in increased. 3 Blood flow from nonessential organs is transported to working muscles." } }, { "_index": "cohere-embeddings", "_id": "HuFWCY4BECzWLnMZuI_8", "_score": 0.7176013, "_source": { "id": 1692482, "content": "The thoracic cavity is separated from the abdominal cavity by the diaphragm. This is a broad flat muscle. (muscular) diaphragm The diaphragm is a muscle that separat…e the thoracic from the abdominal cavity. The pelvis is the lowest part of the abdominal cavity and it has no physical separation from it Diaphragm." } }, { "_index": "cohere-embeddings", "_id": "IOFWCY4BECzWLnMZuI_8", "_score": 0.7154432, "_source": { "id": 1692489, "content": "Muscular Wall Separating the Abdominal and Thoracic Cavities; Thoracic Cavity of a Fetal Pig; In Mammals the Diaphragm Separates the Abdominal Cavity from the" } }, { "_index": "cohere-embeddings", "_id": "C-FWCY4BECzWLnMZuI_8", "_score": 0.695313, "_source": { "id": 1691493, "content": "Burning, aching, tenderness and stiffness are just some descriptors of the discomfort you may feel in the muscles you exercised one to two days ago.For the most part, these sensations you experience after exercise are collectively known as delayed onset muscle soreness.urning, aching, tenderness and stiffness are just some descriptors of the discomfort you may feel in the muscles you exercised one to two days ago." } }, (...) ]
GET hugging-face-embeddings/_search { "knn": { "field": "content_embedding", "query_vector_builder": { "text_embedding": { "model_id": "hugging_face_embeddings", "model_text": "What's margin of error?" } }, "k": 10, "num_candidates": 100 }, "_source": [ "id", "content" ] }
As a result, you receive the top 10 documents that are closest in meaning to the
query from the hugging-face-embeddings
index sorted by their proximity to the query:
"hits": [ { "_index": "hugging-face-embeddings", "_id": "ljEfo44BiUQvMpPgT20E", "_score": 0.8522128, "_source": { "id": 7960255, "content": "The margin of error can be defined by either of the following equations. Margin of error = Critical value x Standard deviation of the statistic. Margin of error = Critical value x Standard error of the statistic. If you know the standard deviation of the statistic, use the first equation to compute the margin of error. Otherwise, use the second equation. Previously, we described how to compute the standard deviation and standard error." } }, { "_index": "hugging-face-embeddings", "_id": "lzEfo44BiUQvMpPgT20E", "_score": 0.7865497, "_source": { "id": 7960259, "content": "1 y ou are told only the size of the sample and are asked to provide the margin of error for percentages which are not (yet) known. 2 This is typically the case when you are computing the margin of error for a survey which is going to be conducted in the future." } }, { "_index": "hugging-face-embeddings1", "_id": "DjEfo44BiUQvMpPgT20E", "_score": 0.6229427, "_source": { "id": 2166183, "content": "1. In general, the point at which gains equal losses. 2. In options, the market price that a stock must reach for option buyers to avoid a loss if they exercise. For a call, it is the strike price plus the premium paid. For a put, it is the strike price minus the premium paid." } }, { "_index": "hugging-face-embeddings1", "_id": "VzEfo44BiUQvMpPgT20E", "_score": 0.6034223, "_source": { "id": 2173417, "content": "How do you find the area of a circle? Can you measure the area of a circle and use that to find a value for Pi?" } }, (...) ]
response = client.search( index: 'openai-embeddings', body: { knn: { field: 'content_embedding', query_vector_builder: { text_embedding: { model_id: 'openai_embeddings', model_text: 'Calculate fuel cost' } }, k: 10, num_candidates: 100 }, _source: [ 'id', 'content' ] } ) puts response
GET openai-embeddings/_search { "knn": { "field": "content_embedding", "query_vector_builder": { "text_embedding": { "model_id": "openai_embeddings", "model_text": "Calculate fuel cost" } }, "k": 10, "num_candidates": 100 }, "_source": [ "id", "content" ] }
As a result, you receive the top 10 documents that are closest in meaning to the
query from the openai-embeddings
index sorted by their proximity to the query:
"hits": [ { "_index": "openai-embeddings", "_id": "DDd5OowBHxQKHyc3TDSC", "_score": 0.83704096, "_source": { "id": 862114, "body": "How to calculate fuel cost for a road trip. By Tara Baukus Mello • Bankrate.com. Dear Driving for Dollars, My family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost.It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes.y family is considering taking a long road trip to finish off the end of the summer, but I'm a little worried about gas prices and our overall fuel cost. It doesn't seem easy to calculate since we'll be traveling through many states and we are considering several routes." } }, { "_index": "openai-embeddings", "_id": "ajd5OowBHxQKHyc3TDSC", "_score": 0.8345704, "_source": { "id": 820622, "body": "Home Heating Calculator. Typically, approximately 50% of the energy consumed in a home annually is for space heating. When deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important.This calculator can help you estimate the cost of fuel for different heating appliances.hen deciding on a heating system, many factors will come into play: cost of fuel, installation cost, convenience and life style are all important. This calculator can help you estimate the cost of fuel for different heating appliances." } }, { "_index": "openai-embeddings", "_id": "Djd5OowBHxQKHyc3TDSC", "_score": 0.8327426, "_source": { "id": 8202683, "body": "Fuel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel.If you are paying $4 per gallon, the trip would cost you $200.Most boats have much larger gas tanks than cars.uel is another important cost. This cost will depend on your boat, how far you travel, and how fast you travel. A 33-foot sailboat traveling at 7 knots should be able to travel 300 miles on 50 gallons of diesel fuel." } }, (...) ]