fix: fix GeminiProvdier config tools has empty array or object make request 400 (#3090)

Co-authored-by: archer <archer@gmail.com>
This commit is contained in:
shiro-yama 2025-03-10 11:59:14 +08:00 committed by GitHub
parent 7fb6fcdeeb
commit 3790e82ef3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 36 additions and 1 deletions

View File

@ -27,6 +27,7 @@ import OpenAI from 'openai'
import { CompletionsParams } from '.' import { CompletionsParams } from '.'
import BaseProvider from './BaseProvider' import BaseProvider from './BaseProvider'
import { filterInvalidTools } from './geminiToolUtils'
import { import {
callMCPTool, callMCPTool,
filterMCPTools, filterMCPTools,
@ -181,7 +182,6 @@ export default class GeminiProvider extends BaseProvider {
{ {
model: model.id, model: model.id,
systemInstruction: assistant.prompt, systemInstruction: assistant.prompt,
tools: tools.length > 0 ? tools : undefined,
safetySettings: this.getSafetySettings(model.id), safetySettings: this.getSafetySettings(model.id),
generationConfig: { generationConfig: {
maxOutputTokens: maxTokens, maxOutputTokens: maxTokens,
@ -192,6 +192,10 @@ export default class GeminiProvider extends BaseProvider {
}, },
this.requestOptions this.requestOptions
) )
const filteredTools = filterInvalidTools(geminiModel.tools)
if (!isEmpty(filteredTools)) {
geminiModel.tools = filteredTools
}
const chat = geminiModel.startChat({ history }) const chat = geminiModel.startChat({ history })
const messageContents = await this.getMessageContents(userLastMessage!) const messageContents = await this.getMessageContents(userLastMessage!)

View File

@ -0,0 +1,31 @@
import { CodeExecutionTool, FunctionDeclarationsTool, GoogleSearchRetrievalTool, Tool } from '@google/generative-ai'
import { isEmpty } from 'lodash'
export function filterInvalidTools(tools: Tool[] | undefined) {
return tools?.filter((e) => !isToolInvalid(e)) ?? []
}
function isToolInvalid(tool: Tool | undefined) {
if (tool == undefined) return true
if (isCodeExecutionTool(tool)) {
return isEmpty(tool.codeExecution)
} else if (isGoogleSearchRetrievalTool(tool)) {
return isEmpty(tool.googleSearchRetrieval)
} else if (isFunctionDeclarationsTool(tool)) {
return isEmpty(tool.functionDeclarations)
} else {
return true
}
}
function isCodeExecutionTool(tool: Tool): tool is CodeExecutionTool {
return (tool as CodeExecutionTool).codeExecution !== undefined
}
function isGoogleSearchRetrievalTool(tool: Tool): tool is GoogleSearchRetrievalTool {
return (tool as GoogleSearchRetrievalTool).googleSearchRetrieval !== undefined
}
function isFunctionDeclarationsTool(tool: Tool): tool is FunctionDeclarationsTool {
return (tool as FunctionDeclarationsTool).functionDeclarations !== undefined
}