Update main.py
Browse files
main.py
CHANGED
@@ -94,33 +94,38 @@ def analyze_with_openai(image_path, user_text):
|
|
94 |
"""
|
95 |
分析用戶問題和圖片,並返回 OpenAI 的回應
|
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 |
user_message_history = defaultdict(list)
|
123 |
-
|
124 |
def store_user_message(user_id, message_type, message_content):
|
125 |
"""
|
126 |
儲存用戶的訊息
|
@@ -157,10 +162,13 @@ def handle_image_message(event):
|
|
157 |
previous_message = get_previous_message(user_id)
|
158 |
# 獲取傳送圖片後的用戶問題(文字)
|
159 |
if previous_message and previous_message["type"] == "image":
|
160 |
-
#
|
161 |
-
|
|
|
|
|
162 |
store_user_message(user_id, "text", user_text)
|
163 |
-
|
|
|
164 |
out = analyze_with_openai(image_path, user_text)
|
165 |
|
166 |
else:
|
|
|
94 |
"""
|
95 |
分析用戶問題和圖片,並返回 OpenAI 的回應
|
96 |
"""
|
97 |
+
try:
|
98 |
+
# 確保圖片存在
|
99 |
+
if not os.path.exists(image_path):
|
100 |
+
raise FileNotFoundError(f"圖片路徑無效:{image_path}")
|
101 |
+
|
102 |
+
# 讀取圖片並轉換為 Base64
|
103 |
+
with open(image_path, "rb") as image_file:
|
104 |
+
image_binary = image_file.read()
|
105 |
+
image_base64 = base64.b64encode(image_binary).decode("utf-8")
|
106 |
+
|
107 |
+
# 构建分析請求
|
108 |
+
prompt = f"""
|
109 |
+
用戶的問題是:{user_text}
|
110 |
+
圖片已上傳,Base64 編碼如下:
|
111 |
+
{image_base64[:100]}...(已截斷)
|
112 |
+
請根據圖片和問題進行詳細分析。
|
113 |
+
"""
|
114 |
|
115 |
+
# 使用 OpenAI API 請求
|
116 |
+
response = openai.ChatCompletion.create(
|
117 |
+
model="gpt-4",
|
118 |
+
messages=[
|
119 |
+
{"role": "system", "content": "請用繁體中文回答。你現在是個專業助理,職稱為OPEN小助理,個性活潑、樂觀,願意回答所有問題"},
|
120 |
+
{"role": "user", "content": prompt}
|
121 |
+
]
|
122 |
+
)
|
123 |
|
124 |
+
# 提取回應內容
|
125 |
+
return response["choices"][0]["message"]["content"]
|
126 |
|
127 |
# 使用字典模擬用戶訊息歷史存儲
|
128 |
user_message_history = defaultdict(list)
|
|
|
129 |
def store_user_message(user_id, message_type, message_content):
|
130 |
"""
|
131 |
儲存用戶的訊息
|
|
|
162 |
previous_message = get_previous_message(user_id)
|
163 |
# 獲取傳送圖片後的用戶問題(文字)
|
164 |
if previous_message and previous_message["type"] == "image":
|
165 |
+
# 獲取上一則圖片訊息的路徑
|
166 |
+
image_path = previous_message["content"]
|
167 |
+
|
168 |
+
# 儲存當前文字訊息
|
169 |
store_user_message(user_id, "text", user_text)
|
170 |
+
|
171 |
+
# 結合圖片與文字分析
|
172 |
out = analyze_with_openai(image_path, user_text)
|
173 |
|
174 |
else:
|