Skip to content

feat(genai): Adding content cache samples #4147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions genai/content-cache/content-cache-create-with-txt-gcs-pdf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Copyright 2025 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
//
// https://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.

'use strict';

// [START googlegenaisdk_contentcache_create_with_txt_gcs_pdf]

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';
async function generateContent(
projectId = GOOGLE_CLOUD_PROJECT,
location = GOOGLE_CLOUD_LOCATION
) {
const ai = new GoogleGenAI({
vertexai: true,
project: projectId,
location: location,
httpOptions: {
apiVersion: 'v1',
},
});

const systemInstruction = `
You are an expert researcher. You always stick to the facts in the sources provided, and never make up new facts.
Now look at these research papers, and answer the following questions.
`;

const contents = [
{
role: 'user',
parts: [
{
fileData: {
fileUri:
'gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf',
mimeType: 'application/pdf',
},
},
{
fileData: {
fileUri: 'gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf',
mimeType: 'application/pdf',
},
},
],
},
];

const contentCache = await ai.caches.create({
model: 'gemini-2.5-flash',
config: {
contents: contents,
systemInstruction: systemInstruction,
displayName: 'example-cache',
ttl: '86400s',
},
});

console.log(contentCache);
console.log(contentCache.name);

return contentCache.name;
}

// [END googlegenaisdk_contentcache_create_with_txt_gcs_pdf]

module.exports = {
generateContent,
};
50 changes: 50 additions & 0 deletions genai/content-cache/content-cache-delete.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright 2025 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
//
// https://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.

'use strict';

// [START googlegenaisdk_contentcache_delete]
const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateContent(
projectId = GOOGLE_CLOUD_PROJECT,
location = GOOGLE_CLOUD_LOCATION,
cacheName
) {
const ai = new GoogleGenAI({
vertexai: true,
project: projectId,
location: location,
httpOptions: {
apiVersion: 'v1',
},
});

console.log('Removing cache');
const contentCache = await ai.caches.delete({
name: cacheName,
});

console.log(contentCache.text);

return contentCache;
}
// [END googlegenaisdk_contentcache_delete]

module.exports = {
generateContent,
};
56 changes: 56 additions & 0 deletions genai/content-cache/content-cache-list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright 2025 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
//
// https://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.

'use strict';

// [START googlegenaisdk_contentcache_list]

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';
async function generateContent(
projectId = GOOGLE_CLOUD_PROJECT,
location = GOOGLE_CLOUD_LOCATION
) {
const ai = new GoogleGenAI({
vertexai: true,
project: projectId,
location: location,
httpOptions: {
apiVersion: 'v1',
},
});

const contentCacheList = await ai.caches.list();

// Access individual properties of a ContentCache object(s)
const contentCacheNames = [];
for (const contentCache of contentCacheList.pageInternal) {
console.log(
`Cache \`${contentCache.name}\` for model \`${contentCache.model}\``
);
console.log(`Last updated at: ${contentCache.updateTime}`);
console.log(`Expires at: ${contentCache.expireTime}`);
contentCacheNames.push(contentCache.name);
}
console.log();

return contentCacheNames;
}
// [END googlegenaisdk_contentcache_list]

module.exports = {
generateContent,
};
76 changes: 76 additions & 0 deletions genai/content-cache/content-cache-update.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright 2025 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
//
// https://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.

'use strict';

// [START googlegenaisdk_contentcache_update]
const {GoogleGenAI} = require('@google/genai');
const {DateTime} = require('luxon');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';


async function generateContent(
projectId = GOOGLE_CLOUD_PROJECT,
location = GOOGLE_CLOUD_LOCATION,
cacheName
) {
const ai = new GoogleGenAI({
vertexai: true,
project: projectId,
location: location,
httpOptions: {
apiVersion: 'v1',
},
});

let contentCache = await ai.caches.get({
name: cacheName,
});

console.log('Expire time', contentCache.expireTime);

contentCache = await ai.caches.update({
name: cacheName,
config: {
ttl: '36000s',
},
});

const expireTime = DateTime.fromISO(contentCache.expireTime, {zone: 'utc'});
const now = DateTime.utc();
const timeDiff = expireTime.diff(now, ['seconds']);

console.log('Expire time (after update):', expireTime.toISO());
console.log('Expire time (in seconds):', Math.floor(timeDiff.seconds));

const nextWeekUtc = DateTime.utc().plus({days: 7});
console.log('Next week (UTC):', nextWeekUtc.toISO());

contentCache = await ai.caches.update({
name: cacheName,
config: {
expireTime: nextWeekUtc,
},
});

console.log('Expire time (after update):', contentCache.expireTime);
return contentCache;
}
// [END googlegenaisdk_contentcache_update]

module.exports = {
generateContent,
};
55 changes: 55 additions & 0 deletions genai/content-cache/content-cache-use-with-txt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2025 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
//
// https://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.

'use strict';

// [START googlegenaisdk_contentcache_use_with_txt]

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';


async function generateContent(
projectId = GOOGLE_CLOUD_PROJECT,
location = GOOGLE_CLOUD_LOCATION,
cacheName
) {
const ai = new GoogleGenAI({
vertexai: true,
project: projectId,
location: location,
httpOptions: {
apiVersion: 'v1',
},
});

const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Summarize the pdfs',
config: {
cachedContent: cacheName,
},
});

console.log(response.text);

return response.text;
}
// [END googlegenaisdk_contentcache_use_with_txt]

module.exports = {
generateContent,
};
1 change: 1 addition & 0 deletions genai/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"dependencies": {
"@google/genai": "^0.13.0",
"axios": "^1.6.2",
"luxon": "^3.7.1",
"supertest": "^7.0.0"
},
"devDependencies": {
Expand Down
53 changes: 53 additions & 0 deletions genai/test/content-cache-create-use-update-delete.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright 2025 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
//
// https://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.

'use strict';

const {assert} = require('chai');
const {describe, it} = require('mocha');

const projectId = process.env.CAIP_PROJECT_ID;

const createSample = require('../content-cache/content-cache-create-with-txt-gcs-pdf.js');
const useSample = require('../content-cache/content-cache-use-with-txt.js');
const updateSample = require('../content-cache/content-cache-update.js');
const deleteSample = require('../content-cache/content-cache-delete.js');

describe('content-cache-create-use-update-delete', function () {
this.timeout(60000);
let contentCacheName;

it('should create content cache', async () => {
contentCacheName = await createSample.generateContent(projectId);
assert.isString(contentCacheName);
assert.isAbove(contentCacheName.length, 0);
});

it('should update content cache', async () => {
await updateSample.generateContent(projectId, undefined, contentCacheName);
});

it('should use content cache', async () => {
const response = await useSample.generateContent(
projectId,
undefined,
contentCacheName
);
assert.isString(response);
});

it('should delete content cache', async () => {
await deleteSample.generateContent(projectId, undefined, contentCacheName);
});
});
Loading