A valid, working PHP library to help compare vectors for embeddings

The code to compare vectors is trivial and so you do not need a library for that part of your puzzle.

For example, here is my Ruby “dot_product” method which is same same as the “cosine_similarity” method for OpenAI embeddings (unit vector length of 1):

def self.dot_product(a, b)
    a.zip(b).map { |x, y| x * y }.reduce(:+)
end

It is trivial to convert this to PHP with ChatGPT, but you should verify the Chatty guy of course:

HTH

Note, here a simple PHP function for the dot production, courtesy of the OpenAI API. Please test it before using :slight_smile: :

function dot_product($a, $b) {
    $result = array_map(function($x, $y) {
       return $x * $y;
    }, $a, $b);
   return array_sum($result);
}

Hopefully, this helps and you get the idea (how easy it is to compare linear vectors in PHP). No importing libs required. Just put the function in a loop and compare the vectors and sort the output (rank them).

1 Like