-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
365 lines (304 loc) · 12.8 KB
/
Copy pathutils.py
File metadata and controls
365 lines (304 loc) · 12.8 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# utils.py - 共用工具函數
"""
共用工具函數 - 提供所有Agent都可能需要的功能
"""
import base64
import os
import sys
import json
import time
import random
import re
from openai import OpenAI
import fitz
from PIL import Image
import io
from dotenv import load_dotenv
from google import genai
load_dotenv()
# 設定 Gemini API
GEMINI_API_KEY = os.getenv('GEMINI_API_KEY')
if GEMINI_API_KEY:
GEMINI_CLIENT = genai.Client(api_key=GEMINI_API_KEY)
else:
GEMINI_CLIENT = None
def get_image_base64(image_path):
"""將圖片轉換為base64"""
try:
with Image.open(image_path) as img:
if img.mode == 'RGBA':
img = img.convert('RGB')
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()
return base64.b64encode(img_byte_arr).decode('utf-8')
except Exception as e:
print(f"圖片轉換錯誤: {str(e)}")
return None
def get_pdf_base64(pdf_path):
"""將多頁 PDF 轉換為圖片後轉為 base64"""
try:
pdf_document = fitz.open(pdf_path)
images_base64 = []
for page_number in range(len(pdf_document)):
page = pdf_document[page_number]
zoom = 2
mat = fitz.Matrix(zoom, zoom)
pix = page.get_pixmap(matrix=mat)
img_bytes = pix.tobytes("png")
images_base64.append(base64.b64encode(img_bytes).decode('utf-8'))
pdf_document.close()
return images_base64
except Exception as e:
print(f"PDF轉換錯誤: {str(e)}")
return None
def call_openai_api(prompt, images=None, model="gpt-4.1-mini", max_tokens=1000,
json_mode=False, retry_limit=3):
"""
通用OpenAI API呼叫函數
Args:
prompt: 提示詞
images: 圖片 base64 列表(可選)
model: 模型名稱
max_tokens: 最大 token 數
json_mode: 是否使用 JSON 模式
retry_limit: 重試次數限制
Returns:
API 回應內容
"""
client = OpenAI()
retry_count = 0
while retry_count <= retry_limit:
try:
# 暫停以避免API限制
time.sleep(random.uniform(0.5, 2.0))
# 構建請求內容
content = [{"type": "text", "text": prompt}]
# 如果有圖片,添加到內容中
if images:
for img_base64 in images:
content.append({
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{img_base64}"
}
})
# 構建API請求
request_args = {
"model": model,
"messages": [{"role": "user", "content": content}]
}
# ========== 根據模型選擇正確的 token 參數 ==========
# o1/o4 系列模型使用 max_completion_tokens,其他模型使用 max_tokens
if model.startswith("o1") or model.startswith("o4"):
request_args["max_completion_tokens"] = max_tokens
else:
request_args["max_tokens"] = max_tokens
# ========== JSON 模式處理 ==========
if json_mode:
if model.startswith("o1") or model.startswith("o4"):
# o1/o4 系列不支援 response_format,在 prompt 中強調 JSON 格式
if "You must respond with valid JSON only" not in prompt:
content[0]["text"] = prompt + "\n\nIMPORTANT: You must respond with valid JSON only, no other text or markdown code blocks."
else:
# 其他模型使用 response_format 參數
request_args["response_format"] = {"type": "json_object"}
# ========== 添加除錯訊息 ==========
print(f"\n[API 請求詳情]")
print(f" 模型: {model}")
print(f" JSON 模式: {json_mode}")
print(f" Token 參數: {'max_completion_tokens' if model.startswith('o1') or model.startswith('o4') else 'max_tokens'} = {max_tokens}")
print(f" 圖片數量: {len(images) if images else 0}")
print(f" Prompt 長度: {len(prompt)} 字元")
# 發送請求
print(f" → 發送請求到 OpenAI API...")
response = client.chat.completions.create(**request_args)
# 檢查回應
print(f" ✓ 收到回應")
print(f" 回應物件類型: {type(response)}")
print(f" Choices 數量: {len(response.choices) if hasattr(response, 'choices') else 'N/A'}")
if response.choices and len(response.choices) > 0:
content = response.choices[0].message.content
print(f" 回應內容長度: {len(content) if content else 0} 字元")
print(f" 回應內容前 200 字元: {content[:200] if content else 'None'}...")
if content:
return content.strip()
else:
print(f" ✗ 警告: 回應內容為空")
return None
else:
print(f" ✗ 警告: 沒有 choices")
return None
except Exception as e:
retry_count += 1
# 詳細錯誤訊息
print(f"\n[API 呼叫錯誤]")
print(f" 錯誤類型: {type(e).__name__}")
print(f" 錯誤訊息: {str(e)}")
print(f" 使用模型: {model}")
print(f" JSON 模式: {json_mode}")
print(f" 圖片數量: {len(images) if images else 0}")
# 如果是 OpenAI API 錯誤,顯示更多細節
if hasattr(e, 'response'):
print(f" API 回應: {e.response}")
if hasattr(e, 'status_code'):
print(f" 狀態碼: {e.status_code}")
if retry_count > retry_limit:
print(f"\n✗ 已達最大重試次數 ({retry_limit}),放棄重試")
import traceback
print(f"\n完整錯誤追蹤:")
print("=" * 70)
print(traceback.format_exc())
print("=" * 70)
return None
wait_time = retry_count * 5
print(f" → {wait_time} 秒後進行第 {retry_count}/{retry_limit} 次重試...\n")
time.sleep(wait_time)
continue
def validate_api_key():
"""驗證API金鑰是否設置"""
api_key = os.getenv('OPENAI_API_KEY')
if not api_key:
print("錯誤: 未設定 OPENAI_API_KEY 環境變數")
print("請在 .env 檔案中設定 OPENAI_API_KEY=your_api_key")
return False
return True
def validate_image_file(image_path):
"""檢查圖片檔案是否有效"""
if not os.path.exists(image_path):
return False
# 檢查檔案大小
file_size = os.path.getsize(image_path)
if file_size == 0:
return False
# 檢查是否為有效的圖片
try:
with Image.open(image_path) as img:
img.verify()
return True
except Exception:
return False
def call_gemini_api(prompt, images=None, model="gemini-3-pro-preview", max_tokens=16000,
json_mode=False, retry_limit=3):
"""
呼叫 Google Gemini API(使用新的 Google GenAI SDK)
Args:
prompt: 提示詞
images: 圖片路徑列表(可選)
model: 模型名稱(gemini-3-pro-preview)
max_tokens: 最大 token 數
json_mode: 是否使用 JSON 模式
retry_limit: 重試次數限制
Returns:
API 回應內容
"""
if not GEMINI_CLIENT:
print("錯誤: 未設定 GEMINI_API_KEY 環境變數或 Gemini Client 初始化失敗")
return None
retry_count = 0
while retry_count <= retry_limit:
try:
# 暫停以避免API限制
time.sleep(random.uniform(0.5, 2.0))
# 構建內容列表
contents = []
# 如果有圖片,先添加圖片
if images:
for img_path in images:
try:
# 使用 PIL 讀取圖片
from PIL import Image as PILImage
img = PILImage.open(img_path)
contents.append(img)
except Exception as e:
print(f" ✗ 圖片載入錯誤: {e}")
import traceback
traceback.print_exc()
return None
# JSON 模式處理
if json_mode and "You must respond with valid JSON only" not in prompt:
prompt = prompt + "\n\nIMPORTANT: You must respond with valid JSON only, no other text or markdown code blocks."
# 添加文字提示
contents.append(prompt)
# 設定生成配置
config = {
"max_output_tokens": max_tokens,
"temperature": 0.1,
}
# JSON 模式配置
if json_mode:
config["response_mime_type"] = "application/json"
# 詳細除錯訊息
print(f"\n[Gemini API 請求詳情]")
print(f" 模型: {model}")
print(f" JSON 模式: {json_mode}")
print(f" 最大 tokens: {max_tokens}")
print(f" 圖片數量: {len(images) if images else 0}")
print(f" Prompt 長度: {len(prompt)} 字元")
# 發送請求
print(f" → 發送請求到 Gemini API...")
response = GEMINI_CLIENT.models.generate_content(
model=model,
contents=contents,
config=config
)
# 檢查回應
print(f" ✓ 收到回應")
if response.text:
content = response.text.strip()
print(f" 回應內容長度: {len(content)} 字元")
print(f" 回應內容前 200 字元: {content[:200]}...")
return content
else:
print(f" ✗ 警告: 回應內容為空")
# 檢查是否有安全過濾
if hasattr(response, 'prompt_feedback'):
print(f" Prompt Feedback: {response.prompt_feedback}")
return None
except Exception as e:
retry_count += 1
print(f"\n[Gemini API 呼叫錯誤]")
print(f" 錯誤類型: {type(e).__name__}")
print(f" 錯誤訊息: {str(e)}")
if retry_count > retry_limit:
print(f" 已達到重試上限 ({retry_limit} 次)")
import traceback
print(f"\n完整錯誤追蹤:")
traceback.print_exc()
return None
wait_time = retry_count * 10
print(f" → {wait_time} 秒後進行第 {retry_count}/{retry_limit} 次重試...\n")
time.sleep(wait_time)
continue
# 詳細錯誤訊息
print(f"\n[Gemini API 呼叫錯誤]")
print(f" 錯誤類型: {type(e).__name__}")
print(f" 錯誤訊息: {str(e)}")
print(f" 使用模型: {model}")
print(f" JSON 模式: {json_mode}")
print(f" 圖片數量: {len(images) if images else 0}")
if retry_count > retry_limit:
print(f"\n✗ 已達最大重試次數 ({retry_limit}),放棄重試")
import traceback
print(f"\n完整錯誤追蹤:")
print("=" * 70)
print(traceback.format_exc())
print("=" * 70)
return None
wait_time = retry_count * 5
print(f" → {wait_time} 秒後進行第 {retry_count}/{retry_limit} 次重試...\n")
time.sleep(wait_time)
continue
def get_image_for_gemini(image_path):
"""
將圖片路徑準備給 Gemini API 使用
新版 SDK 可以直接使用檔案路徑
Args:
image_path: 圖片路徑
Returns:
圖片路徑(新版 SDK 直接接受路徑)
"""
if not os.path.exists(image_path):
print(f"圖片不存在: {image_path}")
return None
return image_path