Notebooks
E
Elastic
Inference Jinaai

Inference Jinaai

jinaaiopenai-chatgptlangchain-pythonchatgptgenaielasticsearchelasticopenaiAIintegrationschatlogvectordatabasenotebooksPythonsearchgenaistackvectorelasticsearch-labslangchainapplications

Semantic Search using the Inference API with the JinaAI service

Open In Colab

Learn how to use the Inference API for semantic search.

🧰 Requirements

For this example, you will need:

  • An Elastic deployment

  • Elasticsearch 8.18 or above.

  • A valid Jina API key is required to use the Inference API with the JinaAI service.

Create Elastic Cloud deployment

If you don't have an Elastic Cloud deployment, sign up here for a free trial.

Install packages and connect with Elasticsearch Client

To get started, we'll need to connect to our Elastic deployment using the Python client (version 8.18.0 or above). Because we're using an Elastic Cloud deployment, we'll use the Cloud ID to identify our deployment.

First we need to pip install the following packages:

  • elasticsearch
[1]
Requirement already satisfied: elasticsearch in ./venv/lib/python3.10/site-packages (8.17.0)
Requirement already satisfied: elastic-transport<9,>=8.15.1 in ./venv/lib/python3.10/site-packages (from elasticsearch) (8.17.0)
Requirement already satisfied: certifi in ./venv/lib/python3.10/site-packages (from elastic-transport<9,>=8.15.1->elasticsearch) (2024.12.14)
Requirement already satisfied: urllib3<3,>=1.26.2 in ./venv/lib/python3.10/site-packages (from elastic-transport<9,>=8.15.1->elasticsearch) (2.3.0)

[notice] A new release of pip is available: 23.0.1 -> 24.3.1
[notice] To update, run: pip install --upgrade pip

Next, we need to import the modules we need. 🔐 NOTE: getpass enables us to securely prompt the user for credentials without echoing them to the terminal, or storing it in memory.

[2]

Now we can instantiate the Python Elasticsearch client.

First we prompt the user for their password and Cloud ID. Then we create a client object that instantiates an instance of the Elasticsearch class.

[4]

Confirm that the client has connected with this test:

[5]
{'name': 'serverless', 'cluster_name': 'd65dddc06707470a9933db715cc721ac', 'cluster_uuid': 'CS-2uirVQJWHEnSeSr-ihw', 'version': {'number': '8.11.0', 'build_flavor': 'serverless', 'build_type': 'docker', 'build_hash': '00000000', 'build_date': '2023-10-31', 'build_snapshot': False, 'lucene_version': '9.7.0', 'minimum_wire_compatibility_version': '8.11.0', 'minimum_index_compatibility_version': '8.11.0'}, 'tagline': 'You Know, for Search'}

Refer to the documentation to learn how to connect to a self-managed deployment.

Read this page to learn how to connect using API keys.

Create the inference endpoint

Let's create the inference endpoint by using the Create inference API.

You'll need a Jina API key for this. The free trial key may not be enough to complete the tutorial.

[6]
Enter Jina API key:   ········
ObjectApiResponse({'inference_id': 'jinaai_embeddings', 'task_type': 'text_embedding', 'service': 'jinaai', 'service_settings': {'model_id': 'jina-embeddings-v3', 'rate_limit': {'requests_per_minute': 2000}}, 'chunking_settings': {'strategy': 'sentence', 'max_chunk_size': 250, 'sentence_overlap': 1}})

Create an ingest pipeline with an inference processor

Create an ingest pipeline with an inference processor by using the put_pipeline method. Reference the inference endpoint created above as the model_id to infer against the data that is being ingested in the pipeline.

[7]
ObjectApiResponse({'acknowledged': True})

Let's note a few important parameters from that API call:

  • inference: A processor that performs inference using a machine learning model.
  • model_id: Specifies the ID of the inference endpoint to be used. In this example, the model ID is set to jinaai_embeddings.
  • input_output: Specifies input and output fields.
  • input_field: Field name from which the dense_vector representation is created.
  • output_field: Field name which contains inference results.

Create index

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 field type to index the output of the JinaAI embedding model.

Let's create an index named jinaai-movie-embeddings with the mappings we need.

[22]
ObjectApiResponse({'acknowledged': True, 'shards_acknowledged': True, 'index': 'jinaai-movie-embeddings'})

Insert Documents

Let's insert our example dataset of 12 movies.

[23]
Done indexing documents into `jinaai-movie-embeddings` index!

Semantic search

After the dataset 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.

[24]
Score: 0.6566467
Title: Pulp Fiction
Plot: The lives of two mob hitmen, a boxer, a gangster and his wife, and a pair of diner bandits intertwine in four tales of violence and redemption.

Score: 0.63712573
Title: The Silence of the Lambs
Plot: A young F.B.I. cadet must receive the help of an incarcerated and manipulative cannibal killer to help catch another serial killer, a madman who skins his victims.

Score: 0.6357198
Title: Fight Club
Plot: An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.

NOTE: The value of model_id in the query_vector_builder must match the value of inference_id you created in the first step.

Add the rerank inference endpoint

To combine the results more effectively, use Jina Rerank model through the inference API to provide a more precise semantic reranking of the results.

Create an inference endpoint with your Jina API key and the used model name as the model_id (jina-reranker-v2-base-multilingual in this example).

[19]
ObjectApiResponse({'inference_id': 'jinaai_rerank', 'task_type': 'rerank', 'service': 'jinaai', 'service_settings': {'model_id': 'jina-reranker-v2-base-multilingual', 'rate_limit': {'requests_per_minute': 2000}}, 'task_settings': {'top_n': 100, 'return_documents': True}})

Semantic search with reranking

[25]
Score: 0.36116472
Title: Pulp Fiction
Plot: The lives of two mob hitmen, a boxer, a gangster and his wife, and a pair of diner bandits intertwine in four tales of violence and redemption.

Score: 0.24508502
Title: Fight Club
Plot: An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.

Score: 0.21866935
Title: The Silence of the Lambs
Plot: A young F.B.I. cadet must receive the help of an incarcerated and manipulative cannibal killer to help catch another serial killer, a madman who skins his victims.