Upload ollama-example.py
Browse files- ollama-example.py +74 -0
ollama-example.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
def send_request_to_ollama(prompt, model="TaiwanPro-rs"):
|
| 7 |
+
"""向Ollama發送請求並獲取回應"""
|
| 8 |
+
url = "http://localhost:11434/api/generate"
|
| 9 |
+
|
| 10 |
+
data = {
|
| 11 |
+
"model": model,
|
| 12 |
+
"prompt": prompt,
|
| 13 |
+
"stream": False
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
response = requests.post(url, json=data)
|
| 18 |
+
response.raise_for_status()
|
| 19 |
+
return response.json()["response"]
|
| 20 |
+
except requests.exceptions.RequestException as e:
|
| 21 |
+
print(f"請求錯誤: {e}")
|
| 22 |
+
return f"錯誤: {str(e)}"
|
| 23 |
+
|
| 24 |
+
def initialize_markdown_file():
|
| 25 |
+
"""初始化Markdown文件並寫入頭部信息"""
|
| 26 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 27 |
+
|
| 28 |
+
with open("output.md", "w", encoding="utf-8") as file:
|
| 29 |
+
file.write(f"# Ollama TaiwanPro-r 請求結果\n\n")
|
| 30 |
+
file.write(f"生成時間: {timestamp}\n\n")
|
| 31 |
+
file.write(f"模型: TaiwanPro-r\n\n")
|
| 32 |
+
|
| 33 |
+
print(f"已初始化 output.md 文件")
|
| 34 |
+
|
| 35 |
+
def append_to_markdown(index, prompt, response):
|
| 36 |
+
"""將單個請求和回應添加到Markdown文件"""
|
| 37 |
+
with open("output.md", "a", encoding="utf-8") as file:
|
| 38 |
+
file.write(f"## 請求 {index}\n\n")
|
| 39 |
+
file.write(f"### 提示\n\n```\n{prompt}\n```\n\n")
|
| 40 |
+
file.write(f"### 回應\n\n{response}\n\n---\n\n")
|
| 41 |
+
|
| 42 |
+
print(f"已將請求 {index} 的結果寫入 output.md")
|
| 43 |
+
|
| 44 |
+
def main():
|
| 45 |
+
# 準備五則請求
|
| 46 |
+
requests = [
|
| 47 |
+
"介紹台灣的夜市文化",
|
| 48 |
+
"寫一首關於台北101的現代詩",
|
| 49 |
+
"請說明台灣的健保系統如何運作",
|
| 50 |
+
"分析台灣科技產業的發展歷程",
|
| 51 |
+
"台灣的原住民族有哪些,他們的文化特色是什麼?"
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
# 初始化markdown文件
|
| 55 |
+
initialize_markdown_file()
|
| 56 |
+
|
| 57 |
+
print("開始向Ollama的TaiwanPro-r模型發送請求...")
|
| 58 |
+
|
| 59 |
+
for i, prompt in enumerate(requests, 1):
|
| 60 |
+
print(f"發送請求 {i}/{len(requests)}: {prompt[:30]}...")
|
| 61 |
+
response = send_request_to_ollama(prompt)
|
| 62 |
+
print(f"已收到請求 {i} 的回應")
|
| 63 |
+
|
| 64 |
+
# 立即將結果添加到文件中
|
| 65 |
+
append_to_markdown(i, prompt, response)
|
| 66 |
+
|
| 67 |
+
# 避免過快發送請求
|
| 68 |
+
if i < len(requests):
|
| 69 |
+
time.sleep(1)
|
| 70 |
+
|
| 71 |
+
print("所有請求已完成,所有結果已保存至 output.md")
|
| 72 |
+
|
| 73 |
+
if __name__ == "__main__":
|
| 74 |
+
main()
|