Skip to content

Commit

Permalink
[DOCS] Adds inference API end-to-end example (#103042) (#103317)
Browse files Browse the repository at this point in the history
Co-authored-by: David Kyle <[email protected]>
  • Loading branch information
szabosteve and davidkyle authored Dec 12, 2023
1 parent 5144d25 commit 47b906a
Show file tree
Hide file tree
Showing 2 changed files with 277 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,276 @@
[[semantic-search-inference]]
=== Tutorial: semantic search with the {infer} API
++++
<titleabbrev>Semantic search with the {infer} API</titleabbrev>
++++

The instructions in this tutorial shows you how to use the {infer} API with the
Open AI service to perform semantic search on your data. The following example
uses OpenAI's `text-embedding-ada-002` second generation embedding model. You
can use any OpenAI models, they are all supported by the {infer} API.


[discrete]
[[infer-openai-requirements]]
==== Requirements

An https://openai.com/[OpenAI account] is required to use the {infer} API with
the OpenAI service.


[discrete]
[[infer-text-embedding-task]]
==== Create the inference task

Create the {infer} task by using the <<put-inference-api>>:

[source,console]
------------------------------------------------------------
PUT _inference/text_embedding/openai_embeddings <1>
{
"service": "openai",
"service_settings": {
"api_key": "<api_key>" <2>
},
"task_settings": {
"model": "text-embedding-ada-002" <3>
}
}
------------------------------------------------------------
// TEST[skip:TBD]
<1> The task type is `text_embedding` in the path.
<2> The API key of your OpenAI account. You can find your OpenAI API keys in
your OpenAI account under the
https://platform.openai.com/api-keys[API keys section]. You need to provide
your API key only once. The <<get-inference-api>> does not return your API
key.
<3> The name of the embedding model to use. You can find the list of OpenAI
embedding models
https://platform.openai.com/docs/guides/embeddings/embedding-models[here].


[discrete]
[[infer-openai-mappings]]
==== Create the index mapping

The 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, `dense_vector`>>
field type to index the output of the OpenAI model.

[source,console]
--------------------------------------------------
PUT openai-embeddings
{
"mappings": {
"properties": {
"content_embedding": { <1>
"type": "dense_vector", <2>
"dims": 1536, <3>
"element_type": "byte",
"similarity": "dot_product" <4>
},
"content": { <5>
"type": "text" <6>
}
}
}
}
--------------------------------------------------
<1> The name of the field to contain the generated tokens. It must be refrenced
in the {infer} pipeline configuration in the next step.
<2> The field to contain the tokens is a `dense_vector` field.
<3> The output dimensions of the model. Find this value in the
https://platform.openai.com/docs/guides/embeddings/embedding-models[OpenAI documentation]
of the model you use.
<4> The faster` dot_product` function can be used to calculate similarity
because OpenAI embeddings are normalised to unit length. You can check the
https://platform.openai.com/docs/guides/embeddings/which-distance-function-should-i-use[OpenAI docs]
about which similarity function to use.
<5> The name of the field from which to create the sparse vector representation.
In this example, the name of the field is `content`. It must be referenced in
the {infer} pipeline configuration in the next step.
<6> The field type which is text in this example.


[discrete]
[[infer-openai-inference-ingest-pipeline]]
==== Create an ingest pipeline with an inference processor

Create an <<ingest,ingest pipeline>> with an
<<inference-processor,{infer} processor>> and use the OpenAI model you created
above to infer against the data that is being ingested in the
pipeline.

[source,console]
--------------------------------------------------
PUT _ingest/pipeline/openai_embeddings
{
"processors": [
{
"inference": {
"model_id": "openai_embeddings", <1>
"input_output": { <2>
"input_field": "content",
"output_field": "content_embedding"
}
}
}
]
}
--------------------------------------------------
<1> The name of the inference model you created by using the
<<put-inference-api>>.
<2> Configuration object that defines the `input_field` for the {infer} process
and the `output_field` that will contain the {infer} results.

////
[source,console]
----
DELETE _ingest/pipeline/openai_embeddings
----
// TEST[continued]
////


[discrete]
[[infer-load-data]]
==== Load data

In this step, you load the data that you later use in the {infer} 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
https://github.com/elastic/stack-docs/blob/main/docs/en/stack/ml/nlp/data/msmarco-passagetest2019-unique.tsv[tsv file].

Download the file and upload it to your cluster using the
{kibana-ref}/connect-to-elasticsearch.html#upload-data-kibana[Data Visualizer]
in the {ml-app} 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.


[discrete]
[[reindexing-data-infer]]
==== Ingest the data through the {infer} ingest pipeline

Create the embeddings from the text by reindexing the data throught the {infer}
pipeline that uses the OpenAI model as the inference model.

[source,console]
----
POST _reindex?wait_for_completion=false
{
"source": {
"index": "test-data",
"size": 50 <1>
},
"dest": {
"index": "openai-embeddings",
"pipeline": "openai_embeddings"
}
}
----
// TEST[skip:TBD]
<1> The default batch size for reindexing is 1000. Reducing `size` to a smaller
number makes the update of the reindexing process quicker which enables you to
follow the progress closely and detect errors early.

NOTE: The
https://platform.openai.com/account/limits[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:

[source,console]
----
GET _tasks/<task_id>
----
// TEST[skip:TBD]

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:

[source,console]
----
POST _tasks/<task_id>/_cancel
----
// TEST[skip:TBD]


[discrete]
[[infer-semantic-search]]
==== Semantic search

After the dataset has been enriched with the embeddings, you can query the data
using {ref}/knn-search.html#knn-semantic-search[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.

NOTE: If you cancelled the reindexing process, you run the query only a part of
the data which affects the quality of your results.

[source,console]
--------------------------------------------------
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"
]
}
--------------------------------------------------
// TEST[skip:TBD]

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:

[source,consol-result]
--------------------------------------------------
"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."
}
},
(...)
]
--------------------------------------------------
// NOTCONSOLE
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,4 @@ include::{es-repo-dir}/tab-widgets/semantic-search/hybrid-search-widget.asciidoc
** The https://github.com/elastic/elasticsearch-labs[`elasticsearch-labs`] repo contains a number of interactive semantic search examples in the form of executable Python notebooks, using the {es} Python client

include::semantic-search-elser.asciidoc[]
include::semantic-search-inference.asciidoc[]

0 comments on commit 47b906a

Please sign in to comment.