-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug-api.js
More file actions
231 lines (194 loc) · 7.19 KB
/
debug-api.js
File metadata and controls
231 lines (194 loc) · 7.19 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// API 診斷工具 - 在瀏覽器 Console 中運行
// 幫助診斷 Gemini API 連接問題
console.log('🔍 開始 Gemini API 診斷...');
// 測試用的 API Key(請替換為您的實際 API Key)
const TEST_API_KEY = 'YOUR_API_KEY_HERE'; // 請在這裡輸入您的 API Key
// 不同的測試模型
const TEST_MODELS = [
'gemini-2.5-flash',
'gemini-2.0-flash',
'gemini-1.5-flash',
'gemini-1.5-pro'
];
// 測試 API 連接
async function testGeminiAPI(apiKey, modelName) {
console.log(`\n🧪 測試模型: ${modelName}`);
const url = `https://generativelanguage.googleapis.com/v1beta/models/${modelName}:generateContent?key=${apiKey}`;
const requestBody = {
contents: [
{
parts: [
{
text: "請用繁體中文回覆「測試成功」"
}
]
}
],
generationConfig: {
temperature: 0.7,
topK: 40,
topP: 0.95,
maxOutputTokens: 100
}
};
try {
console.log('📡 發送請求到:', url.replace(apiKey, apiKey.substring(0, 10) + '...'));
console.log('📋 請求內容:', JSON.stringify(requestBody, null, 2));
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(requestBody)
});
console.log('📨 回應狀態:', response.status, response.statusText);
console.log('📨 回應標頭:', Object.fromEntries(response.headers.entries()));
const responseText = await response.text();
console.log('📄 原始回應內容:', responseText);
if (!response.ok) {
console.log(`❌ ${modelName} 失敗: HTTP ${response.status}`);
try {
const errorData = JSON.parse(responseText);
console.log('❌ 錯誤詳情:', errorData);
} catch (e) {
console.log('❌ 無法解析錯誤回應為 JSON');
}
return { success: false, error: `HTTP ${response.status}: ${responseText}` };
}
try {
const data = JSON.parse(responseText);
console.log('✅ 成功解析 JSON 回應:', data);
if (data.error) {
console.log('❌ API 返回錯誤:', data.error);
return { success: false, error: data.error.message || data.error };
}
if (!data.candidates || data.candidates.length === 0) {
console.log('❌ 沒有候選回應');
if (data.promptFeedback) {
console.log('📝 Prompt 反饋:', data.promptFeedback);
return { success: false, error: `內容被過濾: ${data.promptFeedback.blockReason || '未知原因'}` };
}
return { success: false, error: '沒有收到有效的回應' };
}
const candidate = data.candidates[0];
console.log('📋 候選回應:', candidate);
if (candidate.finishReason && candidate.finishReason !== 'STOP') {
console.log('⚠️ 回應被阻止:', candidate.finishReason);
return { success: false, error: `回應被阻止: ${candidate.finishReason}` };
}
if (candidate.content?.parts?.[0]?.text) {
const generatedText = candidate.content.parts[0].text;
console.log(`✅ ${modelName} 成功! 回應:`, generatedText);
return { success: true, text: generatedText, model: modelName };
} else {
console.log('❌ 回應格式異常:', candidate);
return { success: false, error: '回應格式不正確' };
}
} catch (parseError) {
console.log('❌ JSON 解析失敗:', parseError);
console.log('❌ 原始內容:', responseText);
return { success: false, error: `JSON 解析失敗: ${parseError.message}` };
}
} catch (networkError) {
console.log('❌ 網路錯誤:', networkError);
return { success: false, error: `網路錯誤: ${networkError.message}` };
}
}
// 測試基本連接
async function testBasicConnection() {
console.log('\n🌐 測試基本 Google API 連接...');
try {
const response = await fetch('https://generativelanguage.googleapis.com/v1beta/models', {
method: 'GET'
});
console.log('🌐 基本連接狀態:', response.status);
if (response.status === 403 || response.status === 401) {
console.log('✅ 能連接到 Google API(需要認證)');
return true;
} else if (response.status === 200) {
console.log('✅ 能連接到 Google API');
return true;
} else {
console.log('❌ Google API 連接異常:', response.status);
return false;
}
} catch (error) {
console.log('❌ 無法連接到 Google API:', error);
return false;
}
}
// 主要診斷函數
async function diagnoseAPI() {
console.log('🚀 開始完整診斷...\n');
// 1. 檢查 API Key
if (TEST_API_KEY === 'YOUR_API_KEY_HERE' || !TEST_API_KEY) {
console.log('❌ 請在腳本中設定您的 API Key (TEST_API_KEY)');
return;
}
if (!TEST_API_KEY.startsWith('AIza')) {
console.log('⚠️ API Key 格式可能不正確,應該以 "AIza" 開頭');
}
console.log('✅ API Key 格式檢查通過');
// 2. 測試基本連接
const basicConnection = await testBasicConnection();
if (!basicConnection) {
console.log('❌ 基本網路連接失敗,請檢查網路環境');
return;
}
// 3. 測試各個模型
const results = [];
for (const model of TEST_MODELS) {
const result = await testGeminiAPI(TEST_API_KEY, model);
results.push({ model, ...result });
}
// 4. 總結結果
console.log('\n📊 診斷結果總結:');
console.log('=' * 50);
const successful = results.filter(r => r.success);
const failed = results.filter(r => !r.success);
if (successful.length > 0) {
console.log(`✅ 成功的模型 (${successful.length}):`);
successful.forEach(r => {
console.log(` - ${r.model}: "${r.text}"`);
});
}
if (failed.length > 0) {
console.log(`❌ 失敗的模型 (${failed.length}):`);
failed.forEach(r => {
console.log(` - ${r.model}: ${r.error}`);
});
}
// 5. 建議
console.log('\n💡 建議:');
if (successful.length > 0) {
console.log(`✅ 建議使用模型: ${successful[0].model}`);
console.log('✅ API 連接正常,可以使用擴充功能');
} else {
console.log('❌ 所有模型都失敗,請檢查:');
console.log(' 1. API Key 是否正確');
console.log(' 2. Google Cloud Console 中是否啟用了 Generative Language API');
console.log(' 3. API Key 是否有正確的權限');
console.log(' 4. 網路環境是否允許訪問 Google API');
}
}
// 導出函數供手動使用
window.geminiDiagnostic = {
diagnoseAPI,
testGeminiAPI,
testBasicConnection,
TEST_MODELS
};
console.log('\n📋 診斷工具已載入!');
console.log('💡 使用方法:');
console.log('1. 修改腳本開頭的 TEST_API_KEY 為您的實際 API Key');
console.log('2. 執行: geminiDiagnostic.diagnoseAPI()');
console.log('3. 或手動測試單個模型: geminiDiagnostic.testGeminiAPI("your-api-key", "gemini-2.5-flash")');
// 如果 API Key 已設定,自動開始診斷
if (TEST_API_KEY !== 'YOUR_API_KEY_HERE' && TEST_API_KEY) {
setTimeout(() => {
diagnoseAPI();
}, 1000);
} else {
console.log('⚠️ 請設定 API Key 後重新運行診斷');
}