Helper function to calculate cosine similarity between two embeddings
| 24 | |
| 25 | // Helper function to calculate cosine similarity between two embeddings |
| 26 | double cosine_similarity(const std::vector<double>& a, |
| 27 | const std::vector<double>& b) { |
| 28 | if (a.size() != b.size()) { |
| 29 | return 0.0; |
| 30 | } |
| 31 | |
| 32 | double dot_product = 0.0; |
| 33 | double norm_a = 0.0; |
| 34 | double norm_b = 0.0; |
| 35 | |
| 36 | for (size_t i = 0; i < a.size(); ++i) { |
| 37 | dot_product += a[i] * b[i]; |
| 38 | norm_a += a[i] * a[i]; |
| 39 | norm_b += b[i] * b[i]; |
| 40 | } |
| 41 | |
| 42 | if (norm_a == 0.0 || norm_b == 0.0) { |
| 43 | return 0.0; |
| 44 | } |
| 45 | |
| 46 | return dot_product / (std::sqrt(norm_a) * std::sqrt(norm_b)); |
| 47 | } |
| 48 | |
| 49 | // Helper function to extract embedding as a vector of doubles |
| 50 | std::vector<double> extract_embedding(const nlohmann::json& data, |