diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 30706fce2..8e462470b 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -17,6 +17,30 @@ class Gemini extends BaseLLM { apiBase: "https://generativelanguage.googleapis.com/v1beta/", }; + // Function to convert completion options to Gemini format + private _convertArgs(options: CompletionOptions) { + const finalOptions: any = {}; // Initialize an empty object + + // Map known options + if (options.topK) { + finalOptions.topK = options.topK; + } + if (options.topP) { + finalOptions.topP = options.topP; + } + if (options.temperature !== undefined && options.temperature !== null) { + finalOptions.temperature = options.temperature; + } + if (options.maxTokens) { + finalOptions.maxOutputTokens = options.maxTokens; + } + if (options.stop) { + finalOptions.stopSequences = options.stop.filter((x) => x.trim() !== ""); + } + + return { generationConfig: finalOptions }; // Wrap options under 'generationConfig' + } + protected async *_streamComplete( prompt: string, options: CompletionOptions, @@ -48,7 +72,10 @@ class Gemini extends BaseLLM { options: CompletionOptions, ): AsyncGenerator { // Ensure this.apiBase is used if available, otherwise use default - const apiBase = this.apiBase || Gemini.defaultOptions?.apiBase || "https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase + const apiBase = + this.apiBase || + Gemini.defaultOptions?.apiBase || + "https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase const isV1API = apiBase.includes("/v1/"); // Conditionally apply removeSystemMessage @@ -94,8 +121,19 @@ class Gemini extends BaseLLM { `models/${options.model}:streamGenerateContent?key=${this.apiKey}`, this.apiBase, ); - const body = { - contents: messages.map((msg) => { + // This feels hacky to repeat code from above function but was the quickest + // way to ensure system message re-formatting isn't done if user has specified v1 + const apiBase = + this.apiBase || + Gemini.defaultOptions?.apiBase || + "https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase + const isV1API = apiBase.includes("/v1/"); + + const contents = messages + .map((msg) => { + if (msg.role === "system" && !isV1API) { + return null; // Don't include system message in contents + } return { role: msg.role === "assistant" ? "model" : "user", parts: @@ -103,7 +141,17 @@ class Gemini extends BaseLLM { ? [{ text: msg.content }] : msg.content.map(this._continuePartToGeminiPart), }; - }), + }) + .filter((c) => c !== null); + + const body = { + ...this._convertArgs(options), + contents, + // if this.systemMessage is defined, reformat it for Gemini API + ...(this.systemMessage && + !isV1API && { + systemInstruction: { parts: [{ text: this.systemMessage }] }, + }), }; const response = await this.fetch(apiURL, { method: "POST",