-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat (provider/google-vertex): Add imagen support. (#4124)
- Loading branch information
Showing
9 changed files
with
365 additions
and
6 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'@ai-sdk/google-vertex': patch | ||
--- | ||
|
||
feat (provider/google-vertex): Add imagen support. |
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
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,22 @@ | ||
import 'dotenv/config'; | ||
import { vertex } from '@ai-sdk/google-vertex'; | ||
import { experimental_generateImage as generateImage } from 'ai'; | ||
import fs from 'fs'; | ||
|
||
async function main() { | ||
const { image } = await generateImage({ | ||
model: vertex.image('imagen-3.0-generate-001'), | ||
prompt: 'A burrito launched through a tunnel', | ||
providerOptions: { | ||
vertex: { | ||
aspectRatio: '16:9', | ||
}, | ||
}, | ||
}); | ||
|
||
const filename = `image-${Date.now()}.png`; | ||
fs.writeFileSync(filename, image.uint8Array); | ||
console.log(`Image saved to ${filename}`); | ||
} | ||
|
||
main().catch(console.error); |
134 changes: 134 additions & 0 deletions
134
packages/google-vertex/src/google-vertex-image-model.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,134 @@ | ||
import { JsonTestServer } from '@ai-sdk/provider-utils/test'; | ||
import { GoogleVertexImageModel } from './google-vertex-image-model'; | ||
import { describe, it, expect, vi } from 'vitest'; | ||
|
||
const prompt = 'A cute baby sea otter'; | ||
|
||
const model = new GoogleVertexImageModel('imagen-3.0-generate-001', { | ||
provider: 'google-vertex', | ||
baseURL: 'https://api.example.com', | ||
headers: { 'api-key': 'test-key' }, | ||
}); | ||
|
||
describe('GoogleVertexImageModel', () => { | ||
describe('doGenerate', () => { | ||
const server = new JsonTestServer( | ||
'https://api.example.com/models/imagen-3.0-generate-001:predict', | ||
); | ||
|
||
server.setupTestEnvironment(); | ||
|
||
function prepareJsonResponse() { | ||
server.responseBodyJson = { | ||
predictions: [ | ||
{ bytesBase64Encoded: 'base64-image-1' }, | ||
{ bytesBase64Encoded: 'base64-image-2' }, | ||
], | ||
}; | ||
} | ||
|
||
it('should pass the correct parameters', async () => { | ||
prepareJsonResponse(); | ||
|
||
await model.doGenerate({ | ||
prompt, | ||
n: 2, | ||
size: undefined, | ||
providerOptions: { vertex: { aspectRatio: '1:1' } }, | ||
}); | ||
|
||
expect(await server.getRequestBodyJson()).toStrictEqual({ | ||
instances: [{ prompt }], | ||
parameters: { | ||
sampleCount: 2, | ||
aspectRatio: '1:1', | ||
}, | ||
}); | ||
}); | ||
|
||
it('should pass headers', async () => { | ||
prepareJsonResponse(); | ||
|
||
const modelWithHeaders = new GoogleVertexImageModel( | ||
'imagen-3.0-generate-001', | ||
{ | ||
provider: 'google-vertex', | ||
baseURL: 'https://api.example.com', | ||
headers: { | ||
'Custom-Provider-Header': 'provider-header-value', | ||
}, | ||
}, | ||
); | ||
|
||
await modelWithHeaders.doGenerate({ | ||
prompt, | ||
n: 2, | ||
size: undefined, | ||
providerOptions: {}, | ||
headers: { | ||
'Custom-Request-Header': 'request-header-value', | ||
}, | ||
}); | ||
|
||
const requestHeaders = await server.getRequestHeaders(); | ||
|
||
expect(requestHeaders).toStrictEqual({ | ||
'content-type': 'application/json', | ||
'custom-provider-header': 'provider-header-value', | ||
'custom-request-header': 'request-header-value', | ||
}); | ||
}); | ||
|
||
it('should extract the generated images', async () => { | ||
prepareJsonResponse(); | ||
|
||
const result = await model.doGenerate({ | ||
prompt, | ||
n: 2, | ||
size: undefined, | ||
providerOptions: {}, | ||
}); | ||
|
||
expect(result.images).toStrictEqual(['base64-image-1', 'base64-image-2']); | ||
}); | ||
|
||
it('throws when size is specified', async () => { | ||
const model = new GoogleVertexImageModel('imagen-3.0-generate-001', { | ||
provider: 'vertex', | ||
baseURL: 'https://example.com', | ||
}); | ||
|
||
await expect( | ||
model.doGenerate({ | ||
prompt: 'test prompt', | ||
n: 1, | ||
size: '1024x1024', | ||
providerOptions: {}, | ||
}), | ||
).rejects.toThrow(/Google Vertex does not support the `size` option./); | ||
}); | ||
|
||
it('sends aspect ratio in the request', async () => { | ||
prepareJsonResponse(); | ||
|
||
await model.doGenerate({ | ||
prompt: 'test prompt', | ||
n: 1, | ||
size: undefined, | ||
providerOptions: { | ||
vertex: { | ||
aspectRatio: '16:9', | ||
}, | ||
}, | ||
}); | ||
|
||
expect(await server.getRequestBodyJson()).toStrictEqual({ | ||
instances: [{ prompt: 'test prompt' }], | ||
parameters: { | ||
sampleCount: 1, | ||
aspectRatio: '16:9', | ||
}, | ||
}); | ||
}); | ||
}); | ||
}); |
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,86 @@ | ||
import { ImageModelV1, JSONValue } from '@ai-sdk/provider'; | ||
import { | ||
Resolvable, | ||
postJsonToApi, | ||
combineHeaders, | ||
createJsonResponseHandler, | ||
resolve, | ||
} from '@ai-sdk/provider-utils'; | ||
import { z } from 'zod'; | ||
import { googleVertexFailedResponseHandler } from './google-vertex-error'; | ||
|
||
export type GoogleVertexImageModelId = | ||
| 'imagen-3.0-generate-001' | ||
| 'imagen-3.0-fast-generate-001'; | ||
|
||
interface GoogleVertexImageModelConfig { | ||
provider: string; | ||
baseURL: string; | ||
headers?: Resolvable<Record<string, string | undefined>>; | ||
fetch?: typeof fetch; | ||
} | ||
|
||
// https://cloud.google.com/vertex-ai/generative-ai/docs/image/generate-images | ||
export class GoogleVertexImageModel implements ImageModelV1 { | ||
readonly specificationVersion = 'v1'; | ||
|
||
get provider(): string { | ||
return this.config.provider; | ||
} | ||
|
||
constructor( | ||
readonly modelId: GoogleVertexImageModelId, | ||
private config: GoogleVertexImageModelConfig, | ||
) {} | ||
|
||
async doGenerate({ | ||
prompt, | ||
n, | ||
size, | ||
providerOptions, | ||
headers, | ||
abortSignal, | ||
}: Parameters<ImageModelV1['doGenerate']>[0]): Promise< | ||
Awaited<ReturnType<ImageModelV1['doGenerate']>> | ||
> { | ||
if (size) { | ||
throw new Error( | ||
'Google Vertex does not support the `size` option. Use ' + | ||
'`providerOptions.vertex.aspectRatio` instead. See ' + | ||
'https://cloud.google.com/vertex-ai/generative-ai/docs/image/generate-images#aspect-ratio', | ||
); | ||
} | ||
|
||
const body = { | ||
instances: [{ prompt }], | ||
parameters: { | ||
sampleCount: n, | ||
...(providerOptions.vertex ?? {}), | ||
}, | ||
}; | ||
|
||
const { value: response } = await postJsonToApi({ | ||
url: `${this.config.baseURL}/models/${this.modelId}:predict`, | ||
headers: combineHeaders(await resolve(this.config.headers), headers), | ||
body, | ||
failedResponseHandler: googleVertexFailedResponseHandler, | ||
successfulResponseHandler: createJsonResponseHandler( | ||
vertexImageResponseSchema, | ||
), | ||
abortSignal: abortSignal, | ||
fetch: this.config.fetch, | ||
}); | ||
|
||
return { | ||
images: response.predictions.map( | ||
(p: { bytesBase64Encoded: string }) => p.bytesBase64Encoded, | ||
), | ||
}; | ||
} | ||
} | ||
|
||
// minimal version of the schema, focussed on what is needed for the implementation | ||
// this approach limits breakages when the API changes and increases efficiency | ||
const vertexImageResponseSchema = z.object({ | ||
predictions: z.array(z.object({ bytesBase64Encoded: z.string() })), | ||
}); |
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
Oops, something went wrong.