( prompt: string, useSearch: boolean = false, imageData?: string )
| 903 | } |
| 904 | |
| 905 | async function callGeminiChat( |
| 906 | prompt: string, |
| 907 | useSearch: boolean = false, |
| 908 | imageData?: string |
| 909 | ): Promise<string> { |
| 910 | const client = await getGeminiClient(); |
| 911 | const modelKey = useSearch ? CONFIG_KEYS.GEMINI_SEARCH_MODEL : CONFIG_KEYS.GEMINI_CHAT_MODEL; |
| 912 | const modelName = getConfig(modelKey); |
| 913 | |
| 914 | const activePromptKey = useSearch ? CONFIG_KEYS.GEMINI_SEARCH_ACTIVE_PROMPT : CONFIG_KEYS.GEMINI_CHAT_ACTIVE_PROMPT; |
| 915 | const systemPromptName = getConfig(activePromptKey); |
| 916 | const prompts = JSON.parse(getConfig(CONFIG_KEYS.GEMINI_PROMPTS, "{}")); |
| 917 | const systemPrompt = systemPromptName ? prompts[systemPromptName] || "你是一个乐于助人的人工智能助手。" : "你是一个乐于助人的人工智能助手。"; |
| 918 | |
| 919 | const baseParts: any[] = [{ text: prompt }]; |
| 920 | if (imageData) { |
| 921 | baseParts.push({ inlineData: { mimeType: "image/png", data: imageData } }); |
| 922 | } |
| 923 | let contents: any[] = [{ role: "user", parts: baseParts }]; |
| 924 | |
| 925 | if (getConfig(CONFIG_KEYS.GEMINI_CONTEXT_ENABLED) === "on" && !useSearch) { |
| 926 | const history = JSON.parse(getConfig(CONFIG_KEYS.GEMINI_CHAT_HISTORY, "[]")); |
| 927 | const cleanHistory = history.filter((item: any) => { |
| 928 | return item.role && item.parts && item.parts.every((part: any) => |
| 929 | part.text && typeof part.text === 'string' && !part.inlineData |
| 930 | ); |
| 931 | }); |
| 932 | |
| 933 | if (history.length > 0 && history.some((item: any) => !item.role)) { |
| 934 | |
| 935 | ConfigManager.set(CONFIG_KEYS.GEMINI_CHAT_HISTORY, "[]"); |
| 936 | } else { |
| 937 | contents = [...cleanHistory, ...contents]; |
| 938 | } |
| 939 | } |
| 940 | |
| 941 | const maxTokens = parseInt(getConfig(CONFIG_KEYS.GEMINI_MAX_TOKENS, "0")); |
| 942 | const tools = useSearch ? [{ googleSearch: {} }] : undefined; |
| 943 | |
| 944 | let response; |
| 945 | try { |
| 946 | response = await client.generateContent({ |
| 947 | model: modelName, |
| 948 | contents, |
| 949 | systemInstruction: systemPrompt, |
| 950 | safetySettings: createSafetySettings(), |
| 951 | maxOutputTokens: maxTokens > 0 ? maxTokens : undefined, |
| 952 | tools |
| 953 | }); |
| 954 | |
| 955 | } catch (error: any) { |
| 956 | |
| 957 | throw error; |
| 958 | } |
| 959 | |
| 960 | if (getConfig(CONFIG_KEYS.GEMINI_CONTEXT_ENABLED) === "on" && !useSearch) { |
| 961 | const history = JSON.parse(getConfig(CONFIG_KEYS.GEMINI_CHAT_HISTORY, "[]")); |
| 962 | history.push( |
no test coverage detected