Spaces:
Paused
Paused
File size: 5,606 Bytes
8c741f6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | /**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { CachedContent, RequestOptions } from "../../types";
import { CachedContentUrl, getHeaders, makeServerRequest } from "./request";
import {
CachedContentCreateParams,
CachedContentUpdateParams,
ListCacheResponse,
ListParams,
_CachedContentUpdateRequestFields,
} from "../../types/server";
import { RpcTask } from "./constants";
import {
GoogleGenerativeAIError,
GoogleGenerativeAIRequestInputError,
} from "../errors";
import { formatSystemInstruction } from "../requests/request-helpers";
/**
* Class for managing GoogleAI content caches.
* @public
*/
export class GoogleAICacheManager {
constructor(
public apiKey: string,
private _requestOptions?: RequestOptions,
) {}
/**
* Upload a new content cache
*/
async create(
createOptions: CachedContentCreateParams,
): Promise<CachedContent> {
const newCachedContent: CachedContent = { ...createOptions };
if (createOptions.ttlSeconds) {
if (createOptions.expireTime) {
throw new GoogleGenerativeAIRequestInputError(
"You cannot specify both `ttlSeconds` and `expireTime` when creating" +
" a content cache. You must choose one.",
);
}
if (createOptions.systemInstruction) {
newCachedContent.systemInstruction = formatSystemInstruction(
createOptions.systemInstruction,
);
}
newCachedContent.ttl = createOptions.ttlSeconds.toString() + "s";
delete (newCachedContent as CachedContentCreateParams).ttlSeconds;
}
if (!newCachedContent.model) {
throw new GoogleGenerativeAIRequestInputError(
"Cached content must contain a `model` field.",
);
}
if (!newCachedContent.model.includes("/")) {
// If path is not included, assume it's a non-tuned model.
newCachedContent.model = `models/${newCachedContent.model}`;
}
const url = new CachedContentUrl(
RpcTask.CREATE,
this.apiKey,
this._requestOptions,
);
const headers = getHeaders(url);
const response = await makeServerRequest(
url,
headers,
JSON.stringify(newCachedContent),
);
return response.json();
}
/**
* List all uploaded content caches
*/
async list(listParams?: ListParams): Promise<ListCacheResponse> {
const url = new CachedContentUrl(
RpcTask.LIST,
this.apiKey,
this._requestOptions,
);
if (listParams?.pageSize) {
url.appendParam("pageSize", listParams.pageSize.toString());
}
if (listParams?.pageToken) {
url.appendParam("pageToken", listParams.pageToken);
}
const headers = getHeaders(url);
const response = await makeServerRequest(url, headers);
return response.json();
}
/**
* Get a content cache
*/
async get(name: string): Promise<CachedContent> {
const url = new CachedContentUrl(
RpcTask.GET,
this.apiKey,
this._requestOptions,
);
url.appendPath(parseCacheName(name));
const headers = getHeaders(url);
const response = await makeServerRequest(url, headers);
return response.json();
}
/**
* Update an existing content cache
*/
async update(
name: string,
updateParams: CachedContentUpdateParams,
): Promise<CachedContent> {
const url = new CachedContentUrl(
RpcTask.UPDATE,
this.apiKey,
this._requestOptions,
);
url.appendPath(parseCacheName(name));
const headers = getHeaders(url);
const formattedCachedContent: _CachedContentUpdateRequestFields = {
...updateParams.cachedContent,
};
if (updateParams.cachedContent.ttlSeconds) {
formattedCachedContent.ttl =
updateParams.cachedContent.ttlSeconds.toString() + "s";
delete (formattedCachedContent as CachedContentCreateParams).ttlSeconds;
}
if (updateParams.updateMask) {
url.appendParam(
"update_mask",
updateParams.updateMask.map((prop) => camelToSnake(prop)).join(","),
);
}
const response = await makeServerRequest(
url,
headers,
JSON.stringify(formattedCachedContent),
);
return response.json();
}
/**
* Delete content cache with given name
*/
async delete(name: string): Promise<void> {
const url = new CachedContentUrl(
RpcTask.DELETE,
this.apiKey,
this._requestOptions,
);
url.appendPath(parseCacheName(name));
const headers = getHeaders(url);
await makeServerRequest(url, headers);
}
}
/**
* If cache name is prepended with "cachedContents/", remove prefix
*/
function parseCacheName(name: string): string {
if (name.startsWith("cachedContents/")) {
return name.split("cachedContents/")[1];
}
if (!name) {
throw new GoogleGenerativeAIError(
`Invalid name ${name}. ` +
`Must be in the format "cachedContents/name" or "name"`,
);
}
return name;
}
function camelToSnake(str: string): string {
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
}
|