{"record":{"id":"6ae55711e409d4e6","repo":"vercel/ai","slug":"vectors-must-have-the-same-length","errorCode":null,"errorMessage":"Vectors must have the same length","messagePattern":"Vectors must have the same length","errorType":"validation","errorClass":"InvalidArgumentError","httpStatus":null,"severity":"error","filePath":"packages/ai/src/util/cosine-similarity.ts","lineNumber":16,"sourceCode":"import { InvalidArgumentError } from '../error/invalid-argument-error';\n\n/**\n * Calculates the cosine similarity between two vectors. This is a useful metric for\n * comparing the similarity of two vectors such as embeddings.\n *\n * @param vector1 - The first vector.\n * @param vector2 - The second vector.\n *\n * @returns The cosine similarity between vector1 and vector2, or 0 if either vector is the zero vector.\n *\n * @throws {InvalidArgumentError} If the vectors do not have the same length.\n */\nexport function cosineSimilarity(vector1: number[], vector2: number[]): number {\n  if (vector1.length !== vector2.length) {\n    throw new InvalidArgumentError({\n      parameter: 'vector1,vector2',\n      value: { vector1Length: vector1.length, vector2Length: vector2.length },\n      message: `Vectors must have the same length`,\n    });\n  }\n\n  const n = vector1.length;\n\n  if (n === 0) {\n    return 0; // Return 0 for empty vectors if no error is thrown\n  }\n\n  let magnitudeSquared1 = 0;\n  let magnitudeSquared2 = 0;\n  let dotProduct = 0;\n\n  for (let i = 0; i < n; i++) {\n    const value1 = vector1[i];","sourceCodeStart":1,"sourceCodeEnd":34,"githubUrl":"https://github.com/vercel/ai/blob/69428b1f8b037e4d118fb4853428d5c4e620493c/packages/ai/src/util/cosine-similarity.ts#L1-L34","documentation":"Error \"Vectors must have the same length\" thrown in vercel/ai.","triggerScenarios":"Thrown at packages/ai/src/util/cosine-similarity.ts:16 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":[],"exampleFix":null,"handlingStrategy":null,"validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"69428b1f8b037e4d118fb4853428d5c4e620493c","analyzedAt":"2026-08-30T12:32:21.016Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}