-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
168 lines (151 loc) · 5.93 KB
/
Copy pathbackground.js
File metadata and controls
168 lines (151 loc) · 5.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
const DEFAULT_MODEL = "gemini-2.5-flash";
const FORMS_URL_PATTERN = /https:\/\/docs\.google\.com\/forms\/.*/;
function isGoogleFormUrl(url) {
return FORMS_URL_PATTERN.test(url);
}
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.url) {
if (isGoogleFormUrl(changeInfo.url)) {
chrome.action.enable(tabId);
} else {
chrome.action.disable(tabId);
}
}
});
chrome.tabs.onActivated.addListener((activeInfo) => {
chrome.tabs.get(activeInfo.tabId, (tab) => {
if (isGoogleFormUrl(tab.url)) {
chrome.action.enable(activeInfo.tabId);
} else {
chrome.action.disable(activeInfo.tabId);
}
});
});
function buildPrompt(formTitle, questions, userInstructions) {
const instructions = userInstructions?.trim()
? `User instructions: ${userInstructions.trim()}`
: "User instructions: Provide clear, concise, form-appropriate answers.";
// Prepare detailed question information
const detailedQuestions = questions.map(q => ({
id: q.id,
type: q.type,
question: q.title,
options: q.options || []
}));
return [
"You are an AI form-filling assistant. Your job is to answer EVERY question with a reasonable, appropriate answer.",
instructions,
"",
"CRITICAL: You must answer EVERY single question. Do not skip any questions.",
"",
"ANSWER FORMAT - Return ONLY this JSON structure, no explanation:",
"{\"answers\":[",
" {\"id\":\"q_1\",\"type\":\"checkbox\",\"answer\":[\"Option1\"]},",
" {\"id\":\"q_2\",\"type\":\"short_text\",\"answer\":\"your answer\"}",
"]}",
"",
"QUESTION TYPES AND HOW TO ANSWER:",
"1. short_text → single string answer",
"2. long_text → single string answer (can be multiple sentences)",
"3. radio → single string from the options array",
"4. checkbox → ARRAY of strings from the options array",
"5. dropdown → single string from the options array",
"6. date → string in YYYY-MM-DD format",
"7. time → string in HH:MM format",
"",
"CHECKBOX RULES (MOST IMPORTANT):",
"- checkbox type MUST return an array like [\"Option A\"]",
"- NEVER return [] for checkbox - this is wrong",
"- ALWAYS choose at least ONE option that makes sense",
"- Choose options based on the question context and your instructions",
"",
"EXAMPLES OF CORRECT ANSWERS:",
"Checkbox: {\"id\":\"q_1\",\"type\":\"checkbox\",\"answer\":[\"Option A\",\"Option B\"]}",
"Radio: {\"id\":\"q_2\",\"type\":\"radio\",\"answer\":\"Option C\"}",
"Text: {\"id\":\"q_3\",\"type\":\"short_text\",\"answer\":\"Sample answer\"}",
"Dropdown: {\"id\":\"q_4\",\"type\":\"dropdown\",\"answer\":\"Option D\"}",
"",
"FORM TO FILL:",
`Title: ${formTitle || 'Untitled Form'}`,
"Questions (use all of these to generate answers):",
JSON.stringify(detailedQuestions, null, 2),
"",
"Now respond ONLY with the JSON containing answers for ALL questions."
].join("\n");
}
async function callGemini({ apiKey, model, formTitle, questions, userInstructions }) {
const prompt = buildPrompt(formTitle, questions, userInstructions);
const chosenModel = model || DEFAULT_MODEL;
const url = `https://generativelanguage.googleapis.com/v1beta/models/${chosenModel}:generateContent?key=${encodeURIComponent(apiKey)}`;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
contents: [
{
parts: [{ text: prompt }]
}
],
generationConfig: {
temperature: 0.3,
topP: 0.8
}
})
});
if (!response.ok) {
const errorJson = await response.json();
const status = errorJson?.error?.status;
const message = errorJson?.error?.message;
throw new Error(`Gemini API error: ${status} - ${message}`);
}
const data = await response.json();
const outputText = data?.candidates?.[0]?.content?.parts?.[0]?.text || "";
console.log("[GF Background] Raw AI response:", outputText);
return outputText;
}
function safeJsonParse(text) {
try {
console.log("[GF Background] Attempting JSON parse on:", text.substring(0, 200));
return JSON.parse(text);
} catch (e) {
console.log("[GF Background] JSON parse failed, trying regex match");
const match = text.match(/\{[\s\S]*\}/);
if (!match) {
console.error("[GF Background] No JSON object found in response");
return null;
}
try {
return JSON.parse(match[0]);
} catch (e2) {
console.error("[GF Background] Failed to parse extracted JSON:", match[0].substring(0, 200));
return null;
}
}
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.type !== "GENERATE_ANSWERS") return false;
(async () => {
try {
const { apiKey, model, formTitle, questions, userInstructions } = message.payload || {};
if (!apiKey) {
sendResponse({ ok: false, error: "Missing Gemini API key." });
return;
}
const outputText = await callGemini({ apiKey, model, formTitle, questions, userInstructions });
const parsed = safeJsonParse(outputText);
if (!parsed?.answers) {
sendResponse({ ok: false, error: "Failed to parse Gemini response." });
return;
}
console.log("[GF Background] Parsed answers count:", parsed.answers.length);
const checkboxAnswers = parsed.answers.filter(a => a.type === "checkbox");
console.log("[GF Background] Checkbox answers with empty arrays:", checkboxAnswers.filter(a => !Array.isArray(a.answer) || a.answer.length === 0).map(a => ({ id: a.id, answer: a.answer })));
sendResponse({ ok: true, data: parsed });
} catch (error) {
sendResponse({ ok: false, error: error?.message || "Unknown error." });
}
})();
return true;
});