Skip to content

feat: Integrate Google Gemini API support #859

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: master
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: 4 additions & 0 deletions src/background/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
isUsingClaudeWebModel,
isUsingMoonshotApiModel,
isUsingMoonshotWebModel,
isUsingGeminiApiModel,
} from '../config/index.mjs'
import '../_locales/i18n'
import { openUrl } from '../utils/open-url'
Expand All @@ -49,6 +50,7 @@ import { generateAnswersWithBardWebApi } from '../services/apis/bard-web.mjs'
import { generateAnswersWithClaudeWebApi } from '../services/apis/claude-web.mjs'
import { generateAnswersWithMoonshotCompletionApi } from '../services/apis/moonshot-api.mjs'
import { generateAnswersWithMoonshotWebApi } from '../services/apis/moonshot-web.mjs'
import { generateAnswersWithGeminiApi } from '../services/apis/gemini-api.mjs' // Added import
import { isUsingModelName } from '../utils/model-name-convert.mjs'

function setPortProxy(port, proxyTabId) {
Expand Down Expand Up @@ -140,6 +142,8 @@ async function executeApi(session, port, config) {
session,
config.moonshotApiKey,
)
} else if (isUsingGeminiApiModel(session)) { // Added Gemini condition
await generateAnswersWithGeminiApi(port, session.question, session)
} else if (isUsingChatGLMApiModel(session)) {
await generateAnswersWithChatGLMApi(port, session.question, session)
} else if (isUsingOllamaApiModel(session)) {
Expand Down
13 changes: 13 additions & 0 deletions src/config/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ export const poeWebModelKeys = [
'poeAiWeb_Llama_2_70b',
]
export const moonshotApiModelKeys = ['moonshot_v1_8k', 'moonshot_v1_32k', 'moonshot_v1_128k']
export const geminiApiModelKeys = ['geminiApiPro']

export const AlwaysCustomGroups = [
'ollamaApiModelKeys',
Expand Down Expand Up @@ -130,6 +131,10 @@ export const ModelGroups = {
value: moonshotApiModelKeys,
desc: 'Kimi.Moonshot (API)',
},
geminiApiModelKeys: {
value: geminiApiModelKeys,
desc: 'Gemini (API)',
},
chatglmApiModelKeys: {
value: chatglmApiModelKeys,
desc: 'ChatGLM (API)',
Expand Down Expand Up @@ -267,6 +272,8 @@ export const Models = {
value: 'moonshot-v1-128k',
desc: 'Kimi.Moonshot (128k)',
},

geminiApiPro: { value: 'gemini-pro', desc: 'Gemini (API, Pro)' },
}

for (const modelName in Models) {
Expand Down Expand Up @@ -317,6 +324,7 @@ export const defaultConfig = {
claudeApiKey: '',
chatglmApiKey: '',
moonshotApiKey: '',
geminiApiKey: '',

customApiKey: '',

Expand Down Expand Up @@ -366,6 +374,7 @@ export const defaultConfig = {
'bingFree4',
'moonshotWebFree',
'moonshot_v1_8k',
'geminiApiPro', // Added Gemini API model
'chatglmTurbo',
'customModel',
'azureOpenAi',
Expand Down Expand Up @@ -508,6 +517,10 @@ export function isUsingMoonshotApiModel(configOrSession) {
return isInApiModeGroup(moonshotApiModelKeys, configOrSession)
}

export function isUsingGeminiApiModel(configOrSession) {
return isInApiModeGroup(geminiApiModelKeys, configOrSession)
}

export function isUsingChatGLMApiModel(configOrSession) {
return isInApiModeGroup(chatglmApiModelKeys, configOrSession)
}
Expand Down
13 changes: 13 additions & 0 deletions src/popup/sections/GeneralPart.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
ThemeMode,
TriggerMode,
isUsingMoonshotApiModel,
isUsingGeminiApiModel, // Added import
Models,
} from '../../config/index.mjs'
import Browser from 'webextension-polyfill'
Expand Down Expand Up @@ -331,6 +332,18 @@ export function GeneralPart({ config, updateConfig, setTabIndex }) {
)}
</span>
)}
{isUsingGeminiApiModel(config) && (
<input
type="password"
style="width: 50%;"
Copy link
Preview

Copilot AI May 31, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In React, the style prop should be provided as an object (e.g., style={{ width: '50%' }}) rather than a string literal to ensure proper rendering.

Suggested change
style="width: 50%;"
style={{ width: '50%' }}

Copilot uses AI. Check for mistakes.

value={config.geminiApiKey}
placeholder={t('Gemini API Key')} // Using t() for consistency, will add to i18n later
onChange={(e) => {
const apiKey = e.target.value
updateConfig({ geminiApiKey: apiKey })
}}
/>
)}
</span>
{isUsingSpecialCustomModel(config) && (
<input
Expand Down
73 changes: 73 additions & 0 deletions src/services/apis/gemini-api.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { getUserConfig } from '../../config/index.mjs';
import { pushRecord } from './shared.mjs'; // Assuming this is used for history
// import { fetchSSE } from '../../utils/fetch-sse.mjs'; // If streaming is needed

// Placeholder for the actual Gemini API endpoint
const GEMINI_API_ENDPOINT = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent';

export async function generateAnswersWithGeminiApi(port, question, session) {
const config = await getUserConfig();
const apiKey = config.geminiApiKey;

if (!apiKey) {
port.postMessage({ error: 'Gemini API key not configured.', done: true, session });
return;
}

try {
// Construct the request payload
// This is a placeholder structure and needs to be verified against Gemini API documentation
const payload = {
contents: [{
parts: [{
text: question,
}],
}],
// generationConfig: { // Optional: configure temperature, maxOutputTokens, etc.
// temperature: config.temperature,
// maxOutputTokens: config.maxResponseTokenLength,
// },
// safetySettings: [ // Optional: configure safety settings
// { category: 'HARM_CATEGORY_HARASSMENT', threshold: 'BLOCK_MEDIUM_AND_ABOVE' },
// { category: 'HARM_CATEGORY_HATE_SPEECH', threshold: 'BLOCK_MEDIUM_AND_ABOVE' },
// { category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT', threshold: 'BLOCK_MEDIUM_AND_ABOVE' },
// { category: 'HARM_CATEGORY_DANGEROUS_CONTENT', threshold: 'BLOCK_MEDIUM_AND_ABOVE' },
// ],
};

const response = await fetch(`${GEMINI_API_ENDPOINT}?key=${apiKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});

if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
console.error('Gemini API error:', errorData);
port.postMessage({ error: `Gemini API error: ${errorData.error?.message || errorData.message || 'Unknown error'}`, done: true, session });
return;
}

const responseData = await response.json();

// Extract the answer from the responseData
// This is a placeholder and needs to be verified against actual Gemini API response structure
// Expected structure: responseData.candidates[0].content.parts[0].text
let answer = 'No response from Gemini API.';
if (responseData.candidates && responseData.candidates[0] && responseData.candidates[0].content && responseData.candidates[0].content.parts && responseData.candidates[0].content.parts[0]) {
answer = responseData.candidates[0].content.parts[0].text;
} else {
console.error('Unexpected Gemini API response structure:', responseData);
}

pushRecord(session, question, answer);
// console.debug('Gemini conversation history', { content: session.conversationRecords });
port.postMessage({ answer: answer, done: true, session: session });

} catch (err) {
console.error('Error in generateAnswersWithGeminiApi:', err);
port.postMessage({ error: err.message || 'Failed to communicate with Gemini API.', done: true, session });
}
}