|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2025 Google LLC |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +import { AIError } from './errors'; |
| 19 | +import { logger } from './logger'; |
| 20 | +import { |
| 21 | + CitationMetadata, |
| 22 | + CountTokensRequest, |
| 23 | + GenerateContentCandidate, |
| 24 | + GenerateContentRequest, |
| 25 | + GenerateContentResponse, |
| 26 | + HarmSeverity, |
| 27 | + InlineDataPart, |
| 28 | + PromptFeedback, |
| 29 | + SafetyRating, |
| 30 | + AIErrorCode, |
| 31 | +} from './types'; |
| 32 | +import { |
| 33 | + GoogleAIGenerateContentResponse, |
| 34 | + GoogleAIGenerateContentCandidate, |
| 35 | + GoogleAICountTokensRequest, |
| 36 | +} from './types/googleai'; |
| 37 | + |
| 38 | +/** |
| 39 | + * This SDK supports both the Vertex AI Gemini API and the Gemini Developer API (using Google AI). |
| 40 | + * The public API prioritizes the format used by the Vertex AI Gemini API. |
| 41 | + * We avoid having two sets of types by translating requests and responses between the two API formats. |
| 42 | + * This translation allows developers to switch between the Vertex AI Gemini API and the Gemini Developer API |
| 43 | + * with minimal code changes. |
| 44 | + * |
| 45 | + * In here are functions that map requests and responses between the two API formats. |
| 46 | + * Requests in the Vertex AI format are mapped to the Google AI format before being sent. |
| 47 | + * Responses from the Google AI backend are mapped back to the Vertex AI format before being returned to the user. |
| 48 | + */ |
| 49 | + |
| 50 | +/** |
| 51 | + * Maps a Vertex AI {@link GenerateContentRequest} to a format that can be sent to Google AI. |
| 52 | + * |
| 53 | + * @param generateContentRequest The {@link GenerateContentRequest} to map. |
| 54 | + * @returns A {@link GenerateContentResponse} that conforms to the Google AI format. |
| 55 | + * |
| 56 | + * @throws If the request contains properties that are unsupported by Google AI. |
| 57 | + * |
| 58 | + * @internal |
| 59 | + */ |
| 60 | +export function mapGenerateContentRequest( |
| 61 | + generateContentRequest: GenerateContentRequest, |
| 62 | +): GenerateContentRequest { |
| 63 | + generateContentRequest.safetySettings?.forEach(safetySetting => { |
| 64 | + if (safetySetting.method) { |
| 65 | + throw new AIError( |
| 66 | + AIErrorCode.UNSUPPORTED, |
| 67 | + 'SafetySetting.method is not supported in the the Gemini Developer API. Please remove this property.', |
| 68 | + ); |
| 69 | + } |
| 70 | + }); |
| 71 | + |
| 72 | + if (generateContentRequest.generationConfig?.topK) { |
| 73 | + const roundedTopK = Math.round(generateContentRequest.generationConfig.topK); |
| 74 | + |
| 75 | + if (roundedTopK !== generateContentRequest.generationConfig.topK) { |
| 76 | + logger.warn( |
| 77 | + 'topK in GenerationConfig has been rounded to the nearest integer to match the format for requests to the Gemini Developer API.', |
| 78 | + ); |
| 79 | + generateContentRequest.generationConfig.topK = roundedTopK; |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + return generateContentRequest; |
| 84 | +} |
| 85 | + |
| 86 | +/** |
| 87 | + * Maps a {@link GenerateContentResponse} from Google AI to the format of the |
| 88 | + * {@link GenerateContentResponse} that we get from VertexAI that is exposed in the public API. |
| 89 | + * |
| 90 | + * @param googleAIResponse The {@link GenerateContentResponse} from Google AI. |
| 91 | + * @returns A {@link GenerateContentResponse} that conforms to the public API's format. |
| 92 | + * |
| 93 | + * @internal |
| 94 | + */ |
| 95 | +export function mapGenerateContentResponse( |
| 96 | + googleAIResponse: GoogleAIGenerateContentResponse, |
| 97 | +): GenerateContentResponse { |
| 98 | + const generateContentResponse = { |
| 99 | + candidates: googleAIResponse.candidates |
| 100 | + ? mapGenerateContentCandidates(googleAIResponse.candidates) |
| 101 | + : undefined, |
| 102 | + prompt: googleAIResponse.promptFeedback |
| 103 | + ? mapPromptFeedback(googleAIResponse.promptFeedback) |
| 104 | + : undefined, |
| 105 | + usageMetadata: googleAIResponse.usageMetadata, |
| 106 | + }; |
| 107 | + |
| 108 | + return generateContentResponse; |
| 109 | +} |
| 110 | + |
| 111 | +/** |
| 112 | + * Maps a Vertex AI {@link CountTokensRequest} to a format that can be sent to Google AI. |
| 113 | + * |
| 114 | + * @param countTokensRequest The {@link CountTokensRequest} to map. |
| 115 | + * @param model The model to count tokens with. |
| 116 | + * @returns A {@link CountTokensRequest} that conforms to the Google AI format. |
| 117 | + * |
| 118 | + * @internal |
| 119 | + */ |
| 120 | +export function mapCountTokensRequest( |
| 121 | + countTokensRequest: CountTokensRequest, |
| 122 | + model: string, |
| 123 | +): GoogleAICountTokensRequest { |
| 124 | + const mappedCountTokensRequest: GoogleAICountTokensRequest = { |
| 125 | + generateContentRequest: { |
| 126 | + model, |
| 127 | + ...countTokensRequest, |
| 128 | + }, |
| 129 | + }; |
| 130 | + |
| 131 | + return mappedCountTokensRequest; |
| 132 | +} |
| 133 | + |
| 134 | +/** |
| 135 | + * Maps a Google AI {@link GoogleAIGenerateContentCandidate} to a format that conforms |
| 136 | + * to the Vertex AI API format. |
| 137 | + * |
| 138 | + * @param candidates The {@link GoogleAIGenerateContentCandidate} to map. |
| 139 | + * @returns A {@link GenerateContentCandidate} that conforms to the Vertex AI format. |
| 140 | + * |
| 141 | + * @throws If any {@link Part} in the candidates has a `videoMetadata` property. |
| 142 | + * |
| 143 | + * @internal |
| 144 | + */ |
| 145 | +export function mapGenerateContentCandidates( |
| 146 | + candidates: GoogleAIGenerateContentCandidate[], |
| 147 | +): GenerateContentCandidate[] { |
| 148 | + const mappedCandidates: GenerateContentCandidate[] = []; |
| 149 | + let mappedSafetyRatings: SafetyRating[]; |
| 150 | + if (mappedCandidates) { |
| 151 | + candidates.forEach(candidate => { |
| 152 | + // Map citationSources to citations. |
| 153 | + let citationMetadata: CitationMetadata | undefined; |
| 154 | + if (candidate.citationMetadata) { |
| 155 | + citationMetadata = { |
| 156 | + citations: candidate.citationMetadata.citationSources, |
| 157 | + }; |
| 158 | + } |
| 159 | + |
| 160 | + // Assign missing candidate SafetyRatings properties to their defaults if undefined. |
| 161 | + if (candidate.safetyRatings) { |
| 162 | + mappedSafetyRatings = candidate.safetyRatings.map(safetyRating => { |
| 163 | + return { |
| 164 | + ...safetyRating, |
| 165 | + severity: safetyRating.severity ?? HarmSeverity.HARM_SEVERITY_UNSUPPORTED, |
| 166 | + probabilityScore: safetyRating.probabilityScore ?? 0, |
| 167 | + severityScore: safetyRating.severityScore ?? 0, |
| 168 | + }; |
| 169 | + }); |
| 170 | + } |
| 171 | + |
| 172 | + // videoMetadata is not supported. |
| 173 | + // Throw early since developers may send a long video as input and only expect to pay |
| 174 | + // for inference on a small portion of the video. |
| 175 | + if (candidate.content?.parts.some(part => (part as InlineDataPart)?.videoMetadata)) { |
| 176 | + throw new AIError( |
| 177 | + AIErrorCode.UNSUPPORTED, |
| 178 | + 'Part.videoMetadata is not supported in the Gemini Developer API. Please remove this property.', |
| 179 | + ); |
| 180 | + } |
| 181 | + |
| 182 | + const mappedCandidate = { |
| 183 | + index: candidate.index, |
| 184 | + content: candidate.content, |
| 185 | + finishReason: candidate.finishReason, |
| 186 | + finishMessage: candidate.finishMessage, |
| 187 | + safetyRatings: mappedSafetyRatings, |
| 188 | + citationMetadata, |
| 189 | + groundingMetadata: candidate.groundingMetadata, |
| 190 | + }; |
| 191 | + mappedCandidates.push(mappedCandidate); |
| 192 | + }); |
| 193 | + } |
| 194 | + |
| 195 | + return mappedCandidates; |
| 196 | +} |
| 197 | + |
| 198 | +export function mapPromptFeedback(promptFeedback: PromptFeedback): PromptFeedback { |
| 199 | + // Assign missing SafetyRating properties to their defaults if undefined. |
| 200 | + const mappedSafetyRatings: SafetyRating[] = []; |
| 201 | + promptFeedback.safetyRatings.forEach(safetyRating => { |
| 202 | + mappedSafetyRatings.push({ |
| 203 | + category: safetyRating.category, |
| 204 | + probability: safetyRating.probability, |
| 205 | + severity: safetyRating.severity ?? HarmSeverity.HARM_SEVERITY_UNSUPPORTED, |
| 206 | + probabilityScore: safetyRating.probabilityScore ?? 0, |
| 207 | + severityScore: safetyRating.severityScore ?? 0, |
| 208 | + blocked: safetyRating.blocked, |
| 209 | + }); |
| 210 | + }); |
| 211 | + |
| 212 | + const mappedPromptFeedback: PromptFeedback = { |
| 213 | + blockReason: promptFeedback.blockReason, |
| 214 | + safetyRatings: mappedSafetyRatings, |
| 215 | + blockReasonMessage: promptFeedback.blockReasonMessage, |
| 216 | + }; |
| 217 | + return mappedPromptFeedback; |
| 218 | +} |
0 commit comments