Skip to content

Fixes #332: Adds getImageModel method for image generation #422

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 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions src/gen-ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
} from "./errors";
import { CachedContent, ModelParams, RequestOptions } from "../types";
import { GenerativeModel } from "./models/generative-model";
import { ImageModel } from "./models/image-model";

export { ChatSession } from "./methods/chat-session";
export { GenerativeModel };
Expand Down Expand Up @@ -48,6 +49,20 @@ export class GoogleGenerativeAI {
return new GenerativeModel(this.apiKey, modelParams, requestOptions);
}

getImageModel(
modelParams: ModelParams,
requestOptions?: RequestOptions,
): ImageModel {
if (!modelParams.model) {
throw new GoogleGenerativeAIError(
`Must provide a model name. ` +
`Example: genai.getGenerativeModel({ model: 'my-model-name' })`,
);
}
return new ImageModel(this.apiKey, modelParams, requestOptions);
}


/**
* Creates a {@link GenerativeModel} instance from provided content cache.
*/
Expand Down
20 changes: 20 additions & 0 deletions src/methods/generate-image.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { GenerateImageRequest, GenerateImagesResult, SingleRequestOptions } from "../../types";
import { Task, makeModelRequest } from "../requests/request";

export async function generateImages(
apiKey: string,
model: string,
params: GenerateImageRequest,
requestOptions: SingleRequestOptions,
): Promise<GenerateImagesResult> {
const response = await makeModelRequest(
model,
Task.GENERATE_IMAGES,
apiKey,
/* stream */ false,
JSON.stringify(params),
requestOptions,
);
return response.json();
}

4 changes: 3 additions & 1 deletion src/models/generative-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
GenerateContentResult,
GenerateContentStreamResult,
GenerationConfig,
ImageModelParams,
ModelParams,
Part,
RequestOptions,
Expand Down Expand Up @@ -85,7 +86,8 @@ export class GenerativeModel {
);
this.cachedContent = modelParams.cachedContent;
}



/**
* Makes a single non-streaming call to the model
* and returns an object containing a single {@link GenerateContentResponse}.
Expand Down
45 changes: 45 additions & 0 deletions src/models/image-model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { BaseImageParams, GenerateImagesResult, ImageModelParams, SingleRequestOptions } from "../../types";
import { RequestOptions } from "../server";
import {generateImages} from "../methods/generate-image"
export class ImageModel{
model:string;
modelParams:ImageModelParams;

constructor(
public apiKey: string,
modelParams: ImageModelParams,
private _requestOptions: RequestOptions = {},
)
{
if (modelParams.model.includes("/")) {
// Models may be named "models/model-name" or "tunedModels/model-name"
this.model = modelParams.model;
} else {
// If path is not included, assume it's a non-tuned model.
this.model = `models/${modelParams.model}`;
}
this.modelParams=modelParams;
}


async generateImages(prompt:string,requestConfig?:BaseImageParams,requestOptions?:SingleRequestOptions
):Promise<GenerateImagesResult>{
const Params: ImageModelParams={
model:this.model,
...requestConfig,
}

const generativeModelRequestOptions: SingleRequestOptions = {
...this._requestOptions,
...requestOptions,
};

return generateImages(this.apiKey,this.model,{
instances:[{prompt}],
paramaters: {
...this.modelParams,
...Params,
},
},generativeModelRequestOptions);
}
}
1 change: 1 addition & 0 deletions src/requests/request-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
GoogleGenerativeAIError,
GoogleGenerativeAIRequestInputError,
} from "../errors";
import { generateImages } from "../methods/generate-image";

export function formatSystemInstruction(
input?: string | Part | Content,
Expand Down
2 changes: 2 additions & 0 deletions src/requests/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ export enum Task {
COUNT_TOKENS = "countTokens",
EMBED_CONTENT = "embedContent",
BATCH_EMBED_CONTENTS = "batchEmbedContents",
GENERATE_IMAGES="predict",

}

export class RequestUrl {
Expand Down
54 changes: 54 additions & 0 deletions types/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,44 @@ export interface BaseParams {
generationConfig?: GenerationConfig;
}

export interface BaseImageParams{

guidanceScale?:number;
seed?:number;
safetyFilterLevel?:safetyFilterLevel;
personGeneration?:PersonGeneration;
includeSafetyAttributes?:boolean;
includeRaiReason?:boolean;
language?:ImagePromptLanguage;
outputMimeType?:string;
outputCompressionQuality?:number;
addWatermark?:boolean;
enhancePrompt?:boolean;
}
enum safetyFilterLevel{
BLOCK_LOW_AND_ABOVE='BLOCK_LOW_AND_ABOVE',
BLOCK_NONE='BLOCK_NONE',
BLOCK_ONLY_HIGH='BLOCK_ONLY_HIGH',
BLOCK_MEDIUM_AND_ABOVE='BLOCK_MEDIUM_AND_ABOVE'

}

enum PersonGeneration{
DONT_ALLOW='DONT_ALLOW',
ALLOW_ADULT='ALLOW_ADULT',
ALLOW_ALL='ALLOW_ALL'
}
enum ImagePromptLanguage{
auto ='auto',
en='en',
ja='ja',
ko='ko',
hi='hi'
}

export interface ImageModelParams extends BaseImageParams{
model: string;
}
/**
* Params passed to {@link GoogleGenerativeAI.getGenerativeModel}.
* @public
Expand Down Expand Up @@ -61,6 +99,16 @@ export interface GenerateContentRequest extends BaseParams {
cachedContent?: string;
}


/**
* Request sent to `generateImage` endpoint.
* @public
*/
export interface GenerateImageRequest{
instances:Array<{prompt:string}>;
paramaters:BaseImageParams;
}

/**
* Request sent to `generateContent` endpoint.
* @internal
Expand Down Expand Up @@ -153,6 +201,12 @@ export interface CountTokensRequest {
contents?: Content[];
}

export interface ImageModelParams {
model: string;
aspectRatio?: string;
}


/**
* Params for calling {@link GenerativeModel.countTokens}
* @internal
Expand Down
18 changes: 18 additions & 0 deletions types/responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,24 @@ export interface GenerateContentResult {
response: EnhancedGenerateContentResponse;
}

interface Image{
gcsUri?:string;
bytesBase64Encoded:string;
mimeType:string;
}


interface GeneratedImage{
image?:Image[];
raiFilterReason?:string[];
enhancedPrompt?:string[];

}

export interface GenerateImagesResult{
predictions?:GeneratedImage[];
}

/**
* Result object returned from generateContentStream() call.
* Iterate over `stream` to get chunks as they come in and/or
Expand Down