-
Notifications
You must be signed in to change notification settings - Fork 206
feature: Add Google Gemini LLM API Backend #217
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
smirgol
wants to merge
7
commits into
semperai:master
Choose a base branch
from
smirgol:feature/gemini-llm-api
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
10de440
feat(chat): Add Gemini API as LLM backend
smirgol 15b79a5
fix(gemini): Correct thinkingConfig structure and add preview model
smirgol c1dfd67
feat(gemini): cleanup and robustness
smirgol 4185c45
feat(i18n): Add Gemini LLM API translations
smirgol 0e2c08b
feat(gemini): Add adaptive output token limits for reasoning
smirgol 1132762
refactor(gemini): Add type safety and fix reader lock handling
smirgol 7f22c20
refactor(gemini): Improve type safety, error handling, and code clarity
smirgol 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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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,113 @@ | ||
| import { useEffect } from 'react'; | ||
| import { useTranslation } from 'react-i18next'; | ||
| import { BasicPage, FormRow, NotUsingAlert } from './common'; | ||
| import { SecretTextInput } from '@/components/secretTextInput'; | ||
| import { config, updateConfig } from "@/utils/config"; | ||
|
|
||
| const GEMINI_MODELS = [ | ||
| { value: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash (recommended)' }, | ||
| { value: 'gemini-2.5-flash-lite', label: 'Gemini 2.5 Flash Lite' }, | ||
| { value: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro' }, | ||
| { value: 'gemini-3-pro-preview', label: 'Gemini 3 Pro (preview)' }, | ||
| ]; | ||
|
|
||
| const THINKING_LEVELS = [ | ||
| { value: 'off', label: 'Disabled' }, | ||
| { value: 'low', label: 'Low' }, | ||
| { value: 'high', label: 'High' }, | ||
| ]; | ||
|
|
||
| export function GeminiSettingsPage({ | ||
| geminiApiKey, | ||
| setGeminiApiKey, | ||
| geminiModel, | ||
| setGeminiModel, | ||
| geminiThinkingLevel, | ||
| setGeminiThinkingLevel, | ||
| setSettingsUpdated, | ||
| }: { | ||
| geminiApiKey: string; | ||
| setGeminiApiKey: (key: string) => void; | ||
| geminiModel: string; | ||
| setGeminiModel: (model: string) => void; | ||
| geminiThinkingLevel: string; | ||
| setGeminiThinkingLevel: (level: string) => void; | ||
| setSettingsUpdated: (updated: boolean) => void; | ||
| }) { | ||
| const { t } = useTranslation(); | ||
|
|
||
| useEffect(() => { | ||
| const storedModel = localStorage.getItem('chatvrm_gemini_model'); | ||
| const storedThinkingLevel = localStorage.getItem('chatvrm_gemini_thinking_level'); | ||
|
|
||
| if (!storedModel) { | ||
| updateConfig('gemini_model', geminiModel); | ||
| } | ||
| if (!storedThinkingLevel) { | ||
| updateConfig('gemini_thinking_level', geminiThinkingLevel); | ||
| } | ||
| }, []); // Intentionally using initial prop values only, not reactive to prop changes | ||
|
|
||
| const description = <>{t('gemini_desc')} <a href="https://ai.google.dev" target="_blank" rel="noopener noreferrer">Google AI Studio</a>.</>; | ||
|
|
||
| return ( | ||
| <BasicPage | ||
| title={t('Gemini Settings')} | ||
| description={description} | ||
| > | ||
| { config("chatbot_backend") !== "gemini" && ( | ||
| <NotUsingAlert> | ||
| {t("not_using_alert", "You are not currently using {{name}} as your {{what}} backend. These settings will not be used.", {name: t("Gemini"), what: t("ChatBot")})} | ||
| </NotUsingAlert> | ||
| ) } | ||
| <ul role="list" className="divide-y divide-gray-100 max-w-xs"> | ||
| <li className="py-4"> | ||
| <FormRow label={t('Gemini API Key')}> | ||
| <SecretTextInput | ||
| value={geminiApiKey} | ||
| onChange={(event: React.ChangeEvent<any>) => { | ||
| setGeminiApiKey(event.target.value); | ||
| updateConfig("gemini_apikey", event.target.value); | ||
| setSettingsUpdated(true); | ||
| }} | ||
| /> | ||
| </FormRow> | ||
| </li> | ||
| <li className="py-4"> | ||
| <FormRow label={t('Model')}> | ||
| <select | ||
| className="mt-2 block w-full rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-indigo-600 sm:text-sm sm:leading-6" | ||
| value={geminiModel} | ||
| onChange={(event: React.ChangeEvent<any>) => { | ||
| setGeminiModel(event.target.value); | ||
| updateConfig("gemini_model", event.target.value); | ||
| setSettingsUpdated(true); | ||
| }} | ||
| > | ||
| {GEMINI_MODELS.map((model) => ( | ||
| <option key={model.value} value={model.value}>{t(model.label)}</option> | ||
| ))} | ||
| </select> | ||
| </FormRow> | ||
| </li> | ||
| <li className="py-4"> | ||
| <FormRow label={t('Reasoning Level')}> | ||
| <select | ||
| className="mt-2 block w-full rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-indigo-600 sm:text-sm sm:leading-6" | ||
| value={geminiThinkingLevel} | ||
| onChange={(event: React.ChangeEvent<any>) => { | ||
| setGeminiThinkingLevel(event.target.value); | ||
| updateConfig("gemini_thinking_level", event.target.value); | ||
| setSettingsUpdated(true); | ||
| }} | ||
| > | ||
| {THINKING_LEVELS.map((level) => ( | ||
| <option key={level.value} value={level.value}>{t(level.label)}</option> | ||
| ))} | ||
| </select> | ||
| </FormRow> | ||
| </li> | ||
| </ul> | ||
| </BasicPage> | ||
| ); | ||
| } | ||
This file contains hidden or 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 hidden or 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 hidden or 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,164 @@ | ||
| import { Message } from "./messages"; | ||
| import { config } from '@/utils/config'; | ||
|
|
||
| function getApiKey(configKey: string) { | ||
| const apiKey = config(configKey); | ||
| if (!apiKey) { | ||
| throw new Error(`Invalid ${configKey} API Key`); | ||
| } | ||
| return apiKey; | ||
| } | ||
|
|
||
| function buildRequestBody(messages: Message[], model: string) { | ||
| const systemMessage = messages.find((msg) => msg.role === "system"); | ||
| const conversationMessages = messages.filter((msg) => msg.role !== "system"); | ||
|
|
||
| const generationConfig: any = { | ||
| maxOutputTokens: 400, | ||
| }; | ||
|
|
||
| // Model version detection: check if model name contains "gemini-3" | ||
| const isGemini3 = model.includes("gemini-3"); | ||
| const thinkingLevel = config("gemini_thinking_level"); | ||
|
|
||
| console.log("Gemini thinkingLevel config:", thinkingLevel, "isGemini3:", isGemini3); | ||
|
|
||
| if (isGemini3) { | ||
| // Gemini 3.0 only supports "low" or "high", cannot disable thinking | ||
| const effectiveLevel = thinkingLevel === "off" ? "low" : thinkingLevel | ||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| generationConfig.thinkingConfig = { | ||
| thinkingLevel: effectiveLevel, // "low" or "high" | ||
| }; | ||
| } else { | ||
| // Gemini 2.5 uses thinkingBudget nested in thinkingConfig | ||
| const isPro = model.includes("pro"); | ||
|
|
||
| let thinkingBudget: number; | ||
| if (thinkingLevel === "off") { | ||
| // Pro requires thinking (min 128), others can be 0 | ||
| thinkingBudget = isPro ? 128 : 0; | ||
| } else if (thinkingLevel === "high") { | ||
| thinkingBudget = -1; // Dynamic | ||
| } else { | ||
| // Low: consistent reasoning budget across all models | ||
| thinkingBudget = 1024; | ||
| } | ||
|
|
||
| generationConfig.thinkingConfig = { | ||
| thinkingBudget, | ||
| }; | ||
| } | ||
|
|
||
| const body: any = { | ||
| contents: conversationMessages.map((msg) => ({ | ||
| role: msg.role === "assistant" ? "model" : "user", | ||
| parts: [{ text: msg.content }], | ||
| })), | ||
| generationConfig, | ||
| }; | ||
|
|
||
| if (systemMessage) { | ||
| body.systemInstruction = { | ||
| parts: [{ text: systemMessage.content }], | ||
| }; | ||
| } | ||
|
|
||
| return body; | ||
| } | ||
|
|
||
| async function getResponseStream(messages: Message[]) { | ||
| const apiKey = getApiKey("gemini_apikey"); | ||
| const model = config("gemini_model"); | ||
|
|
||
| const headers: Record<string, string> = { | ||
| "x-goog-api-key": apiKey, | ||
| "Content-Type": "application/json" | ||
| }; | ||
|
|
||
| const requestBody = buildRequestBody(messages, model); | ||
| console.log("Gemini request body:", JSON.stringify(requestBody, null, 2)); | ||
|
|
||
| // @todo: v1beta endpoint is subject to change, but required to support both 2.5 and 3.0 model at this time (30.11.2025) | ||
| const res = await fetch( | ||
| `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`, | ||
| { | ||
| headers, | ||
| method: "POST", | ||
| body: JSON.stringify(requestBody), | ||
| } | ||
| ); | ||
|
|
||
| const reader = res.body?.getReader(); | ||
| if (res.status !== 200 || !reader) { | ||
| if (res.status === 401) { | ||
| throw new Error("Invalid Gemini API key"); | ||
| } | ||
| if (res.status === 400) { | ||
| const errorBody = await res.text(); | ||
| throw new Error(`Invalid request to Gemini API: ${errorBody}`); | ||
| } | ||
| if (res.status === 403) { | ||
| throw new Error("Gemini API access forbidden - check API key permissions"); | ||
| } | ||
| if (res.status === 429) { | ||
| throw new Error("Gemini API rate limit exceeded"); | ||
| } | ||
| if (res.status >= 500) { | ||
| throw new Error("Gemini API server error - please try again later"); | ||
| } | ||
|
|
||
| throw new Error(`Gemini chat error (${res.status})`); | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| const stream = new ReadableStream({ | ||
| async start(controller: ReadableStreamDefaultController) { | ||
| const decoder = new TextDecoder("utf-8"); | ||
| try { | ||
| let combined = ""; | ||
| while (true) { | ||
| const { done, value } = await reader.read(); | ||
| if (done) break; | ||
| const data = decoder.decode(value); | ||
| const chunks = data | ||
| .split("data:") | ||
| .filter((val) => !!val && val.trim() !== "[DONE]"); | ||
|
|
||
| for (const chunk of chunks) { | ||
| if (chunk.length > 0 && chunk[0] === ":") { | ||
| continue; | ||
| } | ||
| combined += chunk; | ||
|
|
||
| try { | ||
| const json = JSON.parse(combined); | ||
| const messagePiece = json.candidates?.[0]?.content?.parts?.[0]?.text; | ||
| combined = ""; | ||
| if (!!messagePiece) { | ||
| controller.enqueue(messagePiece); | ||
| } | ||
| } catch (error) { | ||
| // JSON not yet complete, continue buffering | ||
| } | ||
| } | ||
| } | ||
| } catch (error) { | ||
| console.error(error); | ||
| controller.error(error); | ||
| } finally { | ||
| reader.releaseLock(); | ||
| controller.close(); | ||
| } | ||
| }, | ||
| async cancel() { | ||
| await reader?.cancel(); | ||
| reader.releaseLock(); | ||
| }, | ||
| }); | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return stream; | ||
| } | ||
|
|
||
| export async function getGeminiChatResponseStream(messages: Message[]) { | ||
| return getResponseStream(messages); | ||
| } | ||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.