|
| 1 | +const MODEL_ID = "text-embedding-005"; |
| 2 | +const REGION = "us-central1"; |
| 3 | + |
| 4 | +interface Parameters { |
| 5 | + autoTruncate?: boolean; |
| 6 | + outputDimensionality?: number; |
| 7 | +} |
| 8 | + |
| 9 | +interface Instance { |
| 10 | + task_type?: |
| 11 | + | "RETRIEVAL_DOCUMENT" |
| 12 | + | "RETRIEVAL_QUERY" |
| 13 | + | "SEMANTIC_SIMILARITY" |
| 14 | + | "CLASSIFICATION" |
| 15 | + | "CLUSTERING" |
| 16 | + | "QUESTION_ANSWERING" |
| 17 | + | "FACT_VERIFICATION" |
| 18 | + | "CODE_RETRIEVAL_QUERY"; |
| 19 | + title?: string; |
| 20 | + content: string; |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * Options for generating embeddings. |
| 25 | + */ |
| 26 | +interface Options { |
| 27 | + /** |
| 28 | + * The project ID that the model is in. |
| 29 | + * @default 'PropertiesService.getScriptProperties().getProperty("PROJECT_ID")' |
| 30 | + */ |
| 31 | + projectId?: string; |
| 32 | + |
| 33 | + /** |
| 34 | + * The ID of the model to use. |
| 35 | + * @default 'text-embedding-005'. |
| 36 | + */ |
| 37 | + model?: string; |
| 38 | + |
| 39 | + /** |
| 40 | + * Additional parameters to pass to the model. |
| 41 | + */ |
| 42 | + parameters?: Parameters; |
| 43 | + |
| 44 | + /** |
| 45 | + * The region that the model is in. |
| 46 | + * @default 'us-central1' |
| 47 | + */ |
| 48 | + region?: string; |
| 49 | + |
| 50 | + /** |
| 51 | + * The OAuth token to use to authenticate the request. |
| 52 | + * @default `ScriptApp.getOAuthToken()` |
| 53 | + */ |
| 54 | + token?: string; |
| 55 | +} |
| 56 | + |
| 57 | +const getProjectId = (): string => { |
| 58 | + const projectId = |
| 59 | + PropertiesService.getScriptProperties().getProperty("PROJECT_ID"); |
| 60 | + if (!projectId) { |
| 61 | + throw new Error("PROJECT_ID not found in script properties"); |
| 62 | + } |
| 63 | + |
| 64 | + return projectId; |
| 65 | +}; |
| 66 | + |
| 67 | +/** |
| 68 | + * Generate embeddings for the given text content. |
| 69 | + * |
| 70 | + * @param content - The text content to generate embeddings for. |
| 71 | + * @param options - Options for the embeddings generation. |
| 72 | + * @returns The generated embeddings. |
| 73 | + * |
| 74 | + * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/text-embeddings-api |
| 75 | + */ |
| 76 | +export function getTextEmbeddings( |
| 77 | + contentOrContentArray: string | string[], |
| 78 | + options: Options = {}, |
| 79 | +): number[][] { |
| 80 | + const inputs = Array.isArray(contentOrContentArray) |
| 81 | + ? contentOrContentArray |
| 82 | + : [contentOrContentArray]; |
| 83 | + |
| 84 | + return getBatchedEmbeddings( |
| 85 | + inputs.map((content) => ({ content })), |
| 86 | + options, |
| 87 | + ); |
| 88 | +} |
| 89 | + |
| 90 | +/** |
| 91 | + * Generate embeddings for the given instances in parallel UrlFetchApp requests. |
| 92 | + * |
| 93 | + * @param instances - The instances to generate embeddings for. |
| 94 | + * @param options - Options for the embeddings generation. |
| 95 | + * @returns The generated embeddings. |
| 96 | + * |
| 97 | + * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/text-embeddings-api |
| 98 | + */ |
| 99 | +export function getBatchedEmbeddings( |
| 100 | + instances: Instance[], |
| 101 | + { |
| 102 | + parameters = {}, |
| 103 | + model = MODEL_ID, |
| 104 | + projectId = getProjectId(), |
| 105 | + region = REGION, |
| 106 | + token = ScriptApp.getOAuthToken(), |
| 107 | + }: Options = {}, |
| 108 | +): number[][] { |
| 109 | + const chunks = chunkArray(instances, 5); |
| 110 | + const requests = chunks.map((instances) => ({ |
| 111 | + url: `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/publishers/google/models/${model}:predict`, |
| 112 | + method: "post" as const, |
| 113 | + headers: { |
| 114 | + Authorization: `Bearer ${token}`, |
| 115 | + "Content-Type": "application/json", |
| 116 | + }, |
| 117 | + muteHttpExceptions: true, |
| 118 | + contentType: "application/json", |
| 119 | + payload: JSON.stringify({ |
| 120 | + instances, |
| 121 | + parameters, |
| 122 | + }), |
| 123 | + })); |
| 124 | + |
| 125 | + const responses = UrlFetchApp.fetchAll(requests); |
| 126 | + |
| 127 | + const results = responses.map((response) => { |
| 128 | + if (response.getResponseCode() !== 200) { |
| 129 | + throw new Error(response.getContentText()); |
| 130 | + } |
| 131 | + |
| 132 | + return JSON.parse(response.getContentText()); |
| 133 | + }); |
| 134 | + |
| 135 | + return results.flatMap((result) => |
| 136 | + result.predictions.map( |
| 137 | + (prediction: { embeddings: { values: number[] } }) => |
| 138 | + prediction.embeddings.values, |
| 139 | + ), |
| 140 | + ); |
| 141 | +} |
| 142 | + |
| 143 | +/** |
| 144 | + * Calculates the dot product of two vectors. |
| 145 | + * @param x - The first vector. |
| 146 | + * @param y - The second vector. |
| 147 | + */ |
| 148 | +function dotProduct_(x: number[], y: number[]): number { |
| 149 | + let result = 0; |
| 150 | + for (let i = 0, l = Math.min(x.length, y.length); i < l; i += 1) { |
| 151 | + result += x[i] * y[i]; |
| 152 | + } |
| 153 | + return result; |
| 154 | +} |
| 155 | + |
| 156 | +/** |
| 157 | + * Calculates the magnitude of a vector. |
| 158 | + * @param x - The vector. |
| 159 | + */ |
| 160 | +function magnitude(x: number[]): number { |
| 161 | + let result = 0; |
| 162 | + for (let i = 0, l = x.length; i < l; i += 1) { |
| 163 | + result += x[i] ** 2; |
| 164 | + } |
| 165 | + return Math.sqrt(result); |
| 166 | +} |
| 167 | + |
| 168 | +/** |
| 169 | + * Calculates the cosine similarity between two vectors. |
| 170 | + * @param x - The first vector. |
| 171 | + * @param y - The second vector. |
| 172 | + * @returns The cosine similarity value between -1 and 1. |
| 173 | + */ |
| 174 | +export function similarity(x: number[], y: number[]): number { |
| 175 | + if (x.length !== y.length) { |
| 176 | + throw new Error("Vectors must have the same length"); |
| 177 | + } |
| 178 | + return dotProduct_(x, y) / (magnitude(x) * magnitude(y)); |
| 179 | +} |
| 180 | + |
| 181 | +/** |
| 182 | + * Returns an emoji representing the similarity value. |
| 183 | + * @param value - The similarity value. |
| 184 | + */ |
| 185 | +export const similarityEmoji = (value: number): string => { |
| 186 | + if (value >= 0.9) return "🔥"; // Very high similarity |
| 187 | + if (value >= 0.7) return "✅"; // High similarity |
| 188 | + if (value >= 0.5) return "👍"; // Medium similarity |
| 189 | + if (value >= 0.3) return "🤔"; // Low similarity |
| 190 | + return "❌"; // Very low similarity |
| 191 | +}; |
| 192 | + |
| 193 | +function chunkArray<T>(array: T[], size: number): T[][] { |
| 194 | + const chunks: T[][] = []; |
| 195 | + for (let i = 0; i < array.length; i += size) { |
| 196 | + chunks.push(array.slice(i, i + size)); |
| 197 | + } |
| 198 | + return chunks; |
| 199 | +} |
0 commit comments