-
Notifications
You must be signed in to change notification settings - Fork 2.3k
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
feat(google-genai): Context Caching #7169
Merged
jacoblee93
merged 8 commits into
langchain-ai:main
from
chaunguyenm:google-genai-context-caching
Dec 4, 2024
Merged
Changes from 4 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
5146e14
update google-genai version and add method to create model from cache
4348cda
added test
a447435
fixed test
6658acb
lint and format
99c7b9b
added doc
8a0b33b
Merge
jacoblee93 4d88f0a
Remove unexported code
jacoblee93 a4ebc16
Fix notebook
jacoblee93 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
import { | ||
CachedContentCreateParams, | ||
CachedContentUpdateParams, | ||
FileMetadata, | ||
FileMetadataResponse, | ||
GoogleAICacheManager, | ||
ListCacheResponse, | ||
ListFilesResponse, | ||
ListParams, | ||
UploadFileResponse, | ||
GoogleAIFileManager, | ||
} from "@google/generative-ai/server"; | ||
import { | ||
CachedContent, | ||
RequestOptions, | ||
SingleRequestOptions, | ||
} from "@google/generative-ai"; | ||
|
||
export class GoogleGenerativeAIContextCache { | ||
private fileManager: GoogleAIFileManager; | ||
|
||
private cacheManager: GoogleAICacheManager; | ||
|
||
constructor( | ||
apiKey: string, | ||
fileManagerRequestOptions?: RequestOptions, | ||
cacheManagerRequestOptions?: RequestOptions | ||
) { | ||
this.fileManager = new GoogleAIFileManager( | ||
apiKey, | ||
fileManagerRequestOptions | ||
); | ||
this.cacheManager = new GoogleAICacheManager( | ||
apiKey, | ||
cacheManagerRequestOptions | ||
); | ||
} | ||
|
||
uploadFile( | ||
filePath: string, | ||
fileMetadata: FileMetadata | ||
): Promise<UploadFileResponse> { | ||
return this.fileManager.uploadFile(filePath, fileMetadata); | ||
} | ||
|
||
listFiles( | ||
listParams?: ListParams, | ||
requestOptions?: SingleRequestOptions | ||
): Promise<ListFilesResponse> { | ||
return this.fileManager.listFiles(listParams, requestOptions); | ||
} | ||
|
||
getFile( | ||
fileId: string, | ||
requestOptions?: SingleRequestOptions | ||
): Promise<FileMetadataResponse> { | ||
return this.fileManager.getFile(fileId, requestOptions); | ||
} | ||
|
||
deleteFile(fileId: string): Promise<void> { | ||
return this.fileManager.deleteFile(fileId); | ||
} | ||
|
||
createCache( | ||
createOptions: CachedContentCreateParams | ||
): Promise<CachedContent> { | ||
return this.cacheManager.create(createOptions); | ||
} | ||
|
||
listCaches(listParams?: ListParams): Promise<ListCacheResponse> { | ||
return this.cacheManager.list(listParams); | ||
} | ||
|
||
getCache(name: string): Promise<CachedContent> { | ||
return this.cacheManager.get(name); | ||
} | ||
|
||
updateCache( | ||
name: string, | ||
updateParams: CachedContentUpdateParams | ||
): Promise<CachedContent> { | ||
return this.cacheManager.update(name, updateParams); | ||
} | ||
|
||
deleteCache(name: string): Promise<void> { | ||
return this.cacheManager.delete(name); | ||
} | ||
} |
79 changes: 79 additions & 0 deletions
79
libs/langchain-google-genai/src/tests/context_caching.int.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
/* eslint-disable no-process-env */ | ||
|
||
import { test } from "@jest/globals"; | ||
|
||
import { fileURLToPath } from "node:url"; | ||
import * as path from "node:path"; | ||
|
||
import { FileState, UploadFileResponse } from "@google/generative-ai/server"; | ||
import { GoogleGenerativeAIContextCache } from "../context_caching.js"; | ||
import { ChatGoogleGenerativeAI } from "../chat_models.js"; | ||
|
||
const model = new ChatGoogleGenerativeAI({}); | ||
let fileResult: UploadFileResponse; | ||
|
||
beforeAll(async () => { | ||
// Download video file and save in src/tests/data | ||
// curl -O https://storage.googleapis.com/generativeai-downloads/data/Sherlock_Jr_FullMovie.mp4 | ||
const displayName = "Sherlock Jr. video"; | ||
|
||
const filename = fileURLToPath(import.meta.url); | ||
const dirname = path.dirname(filename); | ||
const pathToVideoFile = path.join(dirname, "/data/Sherlock_Jr_FullMovie.mp4"); | ||
|
||
const contextCache = new GoogleGenerativeAIContextCache( | ||
process.env.GOOGLE_API_KEY || "" | ||
); | ||
fileResult = await contextCache.uploadFile(pathToVideoFile, { | ||
displayName, | ||
mimeType: "video/mp4", | ||
}); | ||
|
||
const { name } = fileResult.file; | ||
|
||
// Poll getFile() on a set interval (2 seconds here) to check file state. | ||
let file = await contextCache.getFile(name); | ||
while (file.state === FileState.PROCESSING) { | ||
// Sleep for 2 seconds | ||
await new Promise((resolve) => { | ||
setTimeout(resolve, 2_000); | ||
}); | ||
file = await contextCache.getFile(name); | ||
} | ||
|
||
const systemInstruction = | ||
"You are an expert video analyzer, and your job is to answer " + | ||
"the user's query based on the video file you have access to."; | ||
const cachedContent = await contextCache.createCache({ | ||
model: "models/gemini-1.5-flash-001", | ||
displayName: "sherlock jr movie", | ||
systemInstruction, | ||
contents: [ | ||
{ | ||
role: "user", | ||
parts: [ | ||
{ | ||
fileData: { | ||
mimeType: fileResult.file.mimeType, | ||
fileUri: fileResult.file.uri, | ||
}, | ||
}, | ||
], | ||
}, | ||
], | ||
ttlSeconds: 300, | ||
}); | ||
|
||
model.enableCachedContent(cachedContent); | ||
}, 10 * 60 * 1000); // Set timeout to 10 minutes to upload file | ||
|
||
test("Test Google AI", async () => { | ||
jacoblee93 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const res = await model.invoke( | ||
"Introduce different characters in the movie by describing " + | ||
"their personality, looks, and names. Also list the " + | ||
"timestamps they were introduced for the first time." | ||
); | ||
|
||
console.log(res); | ||
expect(res).toBeTruthy(); | ||
}); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we use a smaller file for this test? Maybe one of the files that already exist in the repo?