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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import json # 雖然 requests 會處理 json,但保留導入並無害
|
| 3 |
+
import time
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
import difflib
|
| 6 |
+
|
| 7 |
+
# 設定使用的模型名稱
|
| 8 |
+
MODELS = ["gemmapro", "gemmapro-r", "gemmapro-20kctx"]
|
| 9 |
+
OLLAMA_URL = "http://localhost:11434/api/generate"
|
| 10 |
+
|
| 11 |
+
def send_request_to_ollama(prompt, model):
|
| 12 |
+
"""向指定模型發送請求並獲取回應"""
|
| 13 |
+
data = {
|
| 14 |
+
"model": model,
|
| 15 |
+
"prompt": prompt,
|
| 16 |
+
"stream": False
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
response = requests.post(OLLAMA_URL, json=data)
|
| 21 |
+
response.raise_for_status() # 檢查 HTTP 請求是否成功 (狀態碼 2xx)
|
| 22 |
+
return response.json()["response"]
|
| 23 |
+
except requests.exceptions.RequestException as e:
|
| 24 |
+
print(f"[錯誤] 模型 {model} 請求失敗: {e}")
|
| 25 |
+
return f"[錯誤] 向 {model} 發送請求時發生錯誤: {str(e)}" # 提供更明確的錯誤訊息
|
| 26 |
+
except KeyError:
|
| 27 |
+
print(f"[錯誤] 模型 {model} 回應格式不符預期,找不到 'response' 鍵。")
|
| 28 |
+
return f"[錯誤] 模型 {model} 回應格式錯誤。"
|
| 29 |
+
except json.JSONDecodeError:
|
| 30 |
+
print(f"[錯誤] 模型 {model} 回應非有效的 JSON 格式: {response.text}")
|
| 31 |
+
return f"[錯誤] 無法解析來自 {model} 的回應。"
|
| 32 |
+
|
| 33 |
+
def initialize_markdown_file():
|
| 34 |
+
"""初始化 Markdown 報告檔案,包含 YAML metadata"""
|
| 35 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 36 |
+
metadata = {
|
| 37 |
+
"title": "多模型推理彙整報告",
|
| 38 |
+
"date": timestamp,
|
| 39 |
+
"models": MODELS,
|
| 40 |
+
"author": "自動化程式",
|
| 41 |
+
"description": "本報告整合多個模型對多個問題的回應,進行去蕪存菁後的彙整。"
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
try: # 增加檔案操作的錯誤處理
|
| 45 |
+
with open("output_moremodels.md", "w", encoding="utf-8") as file:
|
| 46 |
+
file.write("---\n")
|
| 47 |
+
for key, value in metadata.items():
|
| 48 |
+
if isinstance(value, list):
|
| 49 |
+
file.write(f"{key}:\n")
|
| 50 |
+
for item in value:
|
| 51 |
+
file.write(f" - {item}\n") # 標準 YAML 列表縮排
|
| 52 |
+
else:
|
| 53 |
+
file.write(f"{key}: {value}\n")
|
| 54 |
+
file.write("---\n\n")
|
| 55 |
+
file.write(f"# {metadata['title']}\n\n")
|
| 56 |
+
file.write(f"產出時間: {timestamp}\n\n")
|
| 57 |
+
file.write(f"使用模型: {', '.join(MODELS)}\n\n---\n\n")
|
| 58 |
+
print("[初始化] 已建立 output_moremodels.md")
|
| 59 |
+
except IOError as e:
|
| 60 |
+
print(f"[錯誤] 無法寫入檔案 output_moremodels.md: {e}")
|
| 61 |
+
# 如果無法建立檔案,後續的 append 會失敗,可以考慮在這裡中止程式
|
| 62 |
+
exit(1) # 中止程式執行
|
| 63 |
+
|
| 64 |
+
def append_to_markdown(index, prompt, responses):
|
| 65 |
+
"""將問題與各模型回應結果寫入 Markdown 檔案"""
|
| 66 |
+
try: # 增加檔案操作的錯誤處理
|
| 67 |
+
with open("output_moremodels.md", "a", encoding="utf-8") as file:
|
| 68 |
+
file.write(f"## 問題 {index}\n\n")
|
| 69 |
+
file.write(f"### 提問\n\n```\n{prompt}\n```\n\n")
|
| 70 |
+
|
| 71 |
+
for model, response in responses.items():
|
| 72 |
+
# 確保 response 是字串,避免後續處理錯誤
|
| 73 |
+
response_text = str(response) if response is not None else "[無回應]"
|
| 74 |
+
file.write(f"### 模型:{model}\n\n{response_text.strip()}\n\n")
|
| 75 |
+
|
| 76 |
+
# 自動生成摘要彙整
|
| 77 |
+
# 確保將有效的回應傳遞給摘要函數
|
| 78 |
+
valid_responses = {m: r for m, r in responses.items() if isinstance(r, str)}
|
| 79 |
+
summary = summarize_responses(prompt, valid_responses) # 傳遞有效的回應字典
|
| 80 |
+
file.write(f"### 彙整摘要\n\n{summary}\n\n---\n\n")
|
| 81 |
+
except IOError as e:
|
| 82 |
+
print(f"[錯誤] 無法附加內容至檔案 output_moremodels.md: {e}")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def summarize_responses(prompt, responses):
|
| 86 |
+
"""
|
| 87 |
+
將多個模型的回應進行比較,提取相似的句子,並整合成通順的摘要。
|
| 88 |
+
注意:目前的實作僅基於句法相似度,可能無法完全捕捉語意。
|
| 89 |
+
"""
|
| 90 |
+
# 如果沒有有效的回應,直接返回提示訊息
|
| 91 |
+
if not responses:
|
| 92 |
+
return "沒有從任何模型收到有效回應可供摘要。"
|
| 93 |
+
|
| 94 |
+
# 將每個回應分句
|
| 95 |
+
sentence_lists = []
|
| 96 |
+
for response in responses.values():
|
| 97 |
+
# 更穩健的分句方式,處理不同結尾符號和換行
|
| 98 |
+
# 替換換行符為空格,然後用常見的句尾符號分割
|
| 99 |
+
processed_response = response.replace('\n', ' ')
|
| 100 |
+
sentences = []
|
| 101 |
+
current_sentence = ""
|
| 102 |
+
for char in processed_response:
|
| 103 |
+
current_sentence += char
|
| 104 |
+
if char in ['。', '!', '?', '.', '!', '?']: # 包含中英文句尾符號
|
| 105 |
+
trimmed_sentence = current_sentence.strip()
|
| 106 |
+
if trimmed_sentence: # 確保不是空字串
|
| 107 |
+
sentences.append(trimmed_sentence)
|
| 108 |
+
current_sentence = ""
|
| 109 |
+
# 加入最後一句(如果有的話且沒有結尾符號)
|
| 110 |
+
trimmed_sentence = current_sentence.strip()
|
| 111 |
+
if trimmed_sentence:
|
| 112 |
+
sentences.append(trimmed_sentence)
|
| 113 |
+
|
| 114 |
+
sentence_lists.append(sentences)
|
| 115 |
+
|
| 116 |
+
# 建立一個集合來儲存已處理的句子索引,避免重複處理同一個句子
|
| 117 |
+
processed_indices = set()
|
| 118 |
+
summary_sentences = []
|
| 119 |
+
all_sentences = [(i, j, sent) for i, lst in enumerate(sentence_lists) for j, sent in enumerate(lst)]
|
| 120 |
+
|
| 121 |
+
# 比較所有句子對的相似度
|
| 122 |
+
for idx1 in range(len(all_sentences)):
|
| 123 |
+
model_idx1, sent_idx1, sent1 = all_sentences[idx1]
|
| 124 |
+
# 如果這個句子已經被處理過(作為相似對的一部分),則跳過
|
| 125 |
+
if (model_idx1, sent_idx1) in processed_indices:
|
| 126 |
+
continue
|
| 127 |
+
|
| 128 |
+
best_match = None
|
| 129 |
+
max_similarity = 0.7 # 設定一個基礎閾值 (可調整)
|
| 130 |
+
|
| 131 |
+
for idx2 in range(idx1 + 1, len(all_sentences)):
|
| 132 |
+
model_idx2, sent_idx2, sent2 = all_sentences[idx2]
|
| 133 |
+
|
| 134 |
+
# 確保比較的是不同模型的回應中的句子
|
| 135 |
+
if model_idx1 == model_idx2:
|
| 136 |
+
continue
|
| 137 |
+
|
| 138 |
+
# 如果第二個句子也處理過了,跳過
|
| 139 |
+
if (model_idx2, sent_idx2) in processed_indices:
|
| 140 |
+
continue
|
| 141 |
+
|
| 142 |
+
similarity = difflib.SequenceMatcher(None, sent1, sent2).ratio()
|
| 143 |
+
|
| 144 |
+
# 找尋最高相似度且高於閾值的句子
|
| 145 |
+
if similarity > max_similarity:
|
| 146 |
+
max_similarity = similarity
|
| 147 |
+
# 選擇較短的句子作為代表
|
| 148 |
+
chosen_sentence = sent1 if len(sent1) <= len(sent2) else sent2
|
| 149 |
+
best_match = ((model_idx1, sent_idx1), (model_idx2, sent_idx2), chosen_sentence)
|
| 150 |
+
|
| 151 |
+
# 如果找到了相似度高的句子對
|
| 152 |
+
if best_match:
|
| 153 |
+
idx_pair1, idx_pair2, chosen = best_match
|
| 154 |
+
# 將這對句子都標記為已處理
|
| 155 |
+
processed_indices.add(idx_pair1)
|
| 156 |
+
processed_indices.add(idx_pair2)
|
| 157 |
+
# 加入摘要列表
|
| 158 |
+
summary_sentences.append(chosen)
|
| 159 |
+
|
| 160 |
+
# 處理剩下的、沒有找到高相似度配對的句子(可以選擇性加入)
|
| 161 |
+
# 這裡可以加入邏輯來包含那些獨特但可能重要的句子
|
| 162 |
+
# unique_sentences = []
|
| 163 |
+
# for i, lst in enumerate(sentence_lists):
|
| 164 |
+
# for j, sent in enumerate(lst):
|
| 165 |
+
# if (i, j) not in processed_indices:
|
| 166 |
+
# unique_sentences.append(sent)
|
| 167 |
+
# # 可以選擇將 unique_sentences 加入摘要,或另外呈現
|
| 168 |
+
|
| 169 |
+
# 格式化輸出
|
| 170 |
+
if not summary_sentences:
|
| 171 |
+
summary = "各模型提供了不同的觀點,未偵測到足夠相似的核心內容可供直接彙整。重點預覽如下:\n\n"
|
| 172 |
+
for model, response in responses.items():
|
| 173 |
+
preview = response.strip().replace('\n', ' ')[:100] # 截取前 100 字元預覽
|
| 174 |
+
summary += f"- **{model}**: {preview}...\n"
|
| 175 |
+
else:
|
| 176 |
+
summary = "綜合各模型的相似觀點,摘要如下:\n\n"
|
| 177 |
+
# 可以稍微整理一下摘要句子的順序或進行潤飾
|
| 178 |
+
# 目前直接列出
|
| 179 |
+
unique_summary_sentences = []
|
| 180 |
+
for sentence in summary_sentences:
|
| 181 |
+
if sentence not in unique_summary_sentences: # 再次去重,以防萬一
|
| 182 |
+
unique_summary_sentences.append(sentence)
|
| 183 |
+
|
| 184 |
+
for sentence in unique_summary_sentences:
|
| 185 |
+
summary += f"- {sentence}\n" # 自動加上結尾句號(如果需要)或保留原樣
|
| 186 |
+
|
| 187 |
+
# 注意:這裡 prompt 參數沒有被使用,如果未來摘要邏輯需要參考原始問題,可以加入
|
| 188 |
+
return summary
|
| 189 |
+
|
| 190 |
+
def main():
|
| 191 |
+
# 可自訂多個問題
|
| 192 |
+
questions = [
|
| 193 |
+
"介紹台灣的夜市文化",
|
| 194 |
+
"台灣人工智慧發展的現況與挑戰為何?"
|
| 195 |
+
]
|
| 196 |
+
|
| 197 |
+
initialize_markdown_file() # 如果這裡失敗,程式會中止
|
| 198 |
+
print("[開始] 向模型發送請求...")
|
| 199 |
+
|
| 200 |
+
for i, prompt in enumerate(questions, 1):
|
| 201 |
+
print(f"[處理中] 問題 {i}/{len(questions)}: {prompt[:30]}...")
|
| 202 |
+
model_responses = {}
|
| 203 |
+
|
| 204 |
+
for model in MODELS:
|
| 205 |
+
print(f" └▶ 模型 {model} 推理中...")
|
| 206 |
+
start_time = time.time() # 記錄開始時間
|
| 207 |
+
response = send_request_to_ollama(prompt, model)
|
| 208 |
+
end_time = time.time() # 記錄結束時間
|
| 209 |
+
elapsed_time = end_time - start_time
|
| 210 |
+
print(f" 回應耗時: {elapsed_time:.2f} 秒") # 顯示每個模型的回應時間
|
| 211 |
+
model_responses[model] = response
|
| 212 |
+
# time.sleep(1) # 根據需要調整延遲,如果 Ollama 伺服器負載不高可以縮短或移除
|
| 213 |
+
|
| 214 |
+
append_to_markdown(i, prompt, model_responses)
|
| 215 |
+
print(f"[完成] 問題 {i} 已處理並寫入檔案。")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
print("[完成] 所有問題已處理完畢,結果保���在 output_moremodels.md")
|
| 219 |
+
|
| 220 |
+
if __name__ == "__main__":
|
| 221 |
+
main()
|
output_moremodels.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: 多模型推理彙整報告
|
| 3 |
+
date: 2025-04-16 09:17:03
|
| 4 |
+
models:
|
| 5 |
+
- gemmapro
|
| 6 |
+
- gemmapro-r
|
| 7 |
+
- gemmapro-20kctx
|
| 8 |
+
author: 自動化程式
|
| 9 |
+
description: 本報告整合多個模型對多個問題的回應,進行去蕪存菁後的彙整。
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# 多模型推理彙整報告
|
| 13 |
+
|
| 14 |
+
產出時間: 2025-04-16 09:17:03
|
| 15 |
+
|
| 16 |
+
使用模型: gemmapro, gemmapro-r, gemmapro-20kctx
|
| 17 |
+
|
| 18 |
+
---
|
| 19 |
+
|