Query multiple e filtri

Introduzione agli Embeddings con l'API di OpenAI

Emmanuel Pire

Senior Software Engineer, DataCamp

Consigli basati su più datapoint

 

  • Terrifier (id: 's8170')
  • Strawberry Shortcake: Berry Bitty Adventures (id: 's8103')
Introduzione agli Embeddings con l'API di OpenAI

Query con più testi

reference_ids = ['s8170', 's8103']


reference_texts = collection.get(ids=reference_ids)["documents"]
result = collection.query( query_texts=reference_texts, n_results=3 )
Introduzione agli Embeddings con l'API di OpenAI

Risultato: query con più testi

{'ids': [['s8170', 's6939', 's7000'],['s8103', 's2968', 's3085']],
 'embeddings': None,
 'documents': [['Title: Terrifier (Movie)...',
   'Title: Haunters: The Art of the Scare (Movie)...',
   'Title: Horror Story (Movie)...'],
  ["Title: Strawberry Shortcake: Berry Bitty Adventures (TV Show)...",
   "Title: Shopkins (TV Show)...",
   "Title: Rainbow Ruby (TV Show)..."]],
 'metadatas': [[None, None, None], [None, None, None]],
 'distances': [[0.00, 0.25, 0.26], [0.00, 0.25, 0.28]]}
Introduzione agli Embeddings con l'API di OpenAI

Aggiungere metadati

import csv 

ids = []
metadatas = []

with open('netflix_titles.csv') as csvfile:
  reader = csv.DictReader(csvfile)
  for i, row in enumerate(reader):
    ids.append(row['show_id'])
    metadatas.append({
      "type":row['type'],
      "release_year": int(row['release_year'])
    })

 

  • Crea una lista di dict per i metadati
  • Crea una lista di ID per aggiungerli agli elementi esistenti
Introduzione agli Embeddings con l'API di OpenAI

Aggiungere e interrogare metadati

 

collection.update(ids=ids, metadatas=metadatas)
result = collection.query(
    query_texts=reference_texts, 
    n_results=3,
    where={ 
        "type": "Movie"
    }
)
Introduzione agli Embeddings con l'API di OpenAI

Operatori di where

where={
  "type": "Movie"
}

è uguale a

where={
  "type": {
    "$eq": "Movie"
  }
}

Elenco operatori:

  • $eq - uguale a (string, int, float)
  • $ne - diverso da (string, int, float)
  • $gt - maggiore di (int, float)
  • $gte - maggiore o uguale a (int, float)
  • $lt - minore di (int, float)
  • $lte - minore o uguale a (int, float)
Introduzione agli Embeddings con l'API di OpenAI

Più filtri where

where={
    "$and": [
        {"type": 
            {"$eq": "Movie"}
        },
        {"release_year": 
             {"$gt": 2020}
        }
    ]
}

 

  • $or: filtra se è vera almeno una condizione
Introduzione agli Embeddings con l'API di OpenAI
Titolo: A Classic Horror Story (Movie) [...]
===
Titolo: Nightbooks (Movie) [...]
===
Titolo: Irul (Movie) [...]
===
Titolo: Intrusion (Movie) [...]
===
Titolo: Things Heard & Seen (Movie) [...]
===
Titolo: A StoryBots Space Adventure (Movie) [...]
Introduzione agli Embeddings con l'API di OpenAI

Passons à la pratique !

Introduzione agli Embeddings con l'API di OpenAI

Preparing Video For Download...