顯示具有 Llama 標籤的文章。 顯示所有文章
顯示具有 Llama 標籤的文章。 顯示所有文章

2026年3月15日 星期日

[水井USR] 用本地端實作水井USR智慧養殖AI專家系統

 採用Ollama搭配llama3模型。


範例一、初體驗
程式碼:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import requests

url = "http://localhost:11434/api/generate"

data = {
    "model": "llama3",
    "prompt": "水溫31°C 溶氧3.5 mg/L 養殖建議需要打開水車, 請用繁中文回答",
    "stream": False
}

response = requests.post(url, json=data)

print(response.json()["response"])

執行結果:
🌊

根據你的提供的水質資料,水溫為 31°C,溶氧為 3.5 mg/L。這個情況下,我們可以結合養殖魚類的基本需求,進行建議。

通常來說,養殖魚類需要維持適宜的水質環境,以確保其健康和生存。以下是一些魚類需要的基本水質標準:

* 水溫:15°C ~ 30°C(不同物種的溫度需求可能會有所差異)
* 溶氧:5 mg/L ~ 10 mg/L(不同的養殖魚類對於溶氧的需求也不同)

在你的情況下,水溫高於 30°C,已經超出一般養殖魚類的適宜溫度範圍。這可能會導致魚類受到熱傷害或增加疾病的風險。

另外,溶氧僅有 3.5 mg/L,這也可能對養殖魚類造成負面影響。在水質檢測中,溶氧不足是魚類死亡的主要原因之一。

因此,在這個情況下,我們建議你打開水車,進行水循環和加強空氣饋送,以提高水溫和增加溶氧的水平。這可以幫助養殖魚類維持健康的環境,並減少疾病的風險。

請注意,這只是一個簡單的建議,你還是需要根據實際情況和養殖魚類的特點進行調整和監控,以確保魚類的健康和生存。

範例二、以專家方式提問

 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
import requests

url = "http://localhost:11434/api/generate"
prompt = '''
你是一位台灣水產養殖專家,專長文蛤養殖管理。

文蛤養殖水質建議範圍:
水溫:20–30°C
溶氧:≥4 mg/L
pH:7.5–8.5
鹽度:15–30 ppt

目前養殖池感測資料:
水溫:31°C
溶氧:3.5 mg/L
pH:7.8
鹽度:28 ppt

請分析目前養殖狀況並提供:
1. 水質是否異常
2. 可能風險
3. 建議管理措施

請用繁體中文回答
'''

data = {
    "model": "llama3",
    "prompt": prompt,
    "stream": False
}

response = requests.post(url, json=data)

print(response.json()["response"])

執行結果:
根據現有的養殖池感測資料,文蛤養殖水質如下:

* 水溫:31°C,超過recommended範圍(20–30°C),這可能對文蛤的生長和健康產生負面影響。
* 溶氧:3.5 mg/L,低於recommended範圍(≥4 mg/L),這可能導致文蛤缺乏足夠的氧氣,從而影響其生長和存活率。
* pH:7.8,接近recommended範圍(7.5–8.5),但仍需要監測,以免 pH 突然變化。
* 鹽度:28 ppt,超過recommended範圍(15–30 ppt),這可能對文蛤的生長和健康產生負面影響。

因此,我們可以結論:

1. 水質異常,因為水溫、溶氧和鹽度都超出了recommended範圍。
2. 可能風險包括文蛤的生長和健康受到影響,可能導致存活率下降或死亡。
3. 建議管理措施如下:
* 增加空氣氧氣的混入,以提高溶氧濃度(≥4 mg/L)。
* 監測水溫,並考慮對養殖池的冷卻措施,以將水溫控制在recommended範圍(20–30°C)內。
* 減少鹽度,透過調整養殖池的鹽分濃度或添加淡水,以降低鹽度(15–30 ppt)。
* 定期監測養殖池中的其他指標,如濁度、PH 等,並採取適當措施來維持良好的養殖環境。

總之,需要立即對養殖池進行調整和監測,以避免文蛤的生長和健康受到負面影響。

範例三、給予文蛤最佳養殖條件的提示詞

 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
import requests

url = "http://localhost:11434/api/generate"
prompt = '''
你是一個智慧養殖 AI 助手,負責分析文蛤養殖池的水質資料。

文蛤最佳養殖條件:
水溫:20–30°C
溶氧:≥4 mg/L
pH:7.5–8.5
鹽度:15–30 ppt

目前感測資料:
水溫:31°C
溶氧:3.5 mg/L
pH:7.1
鹽度:12 ppt

請完成以下任務:
1. 判斷水質是否正常
2. 評估缺氧風險
3. 提供三項管理建議
4. 回覆需簡潔並適合養殖戶閱讀

請用繁體中文回答
'''

data = {
    "model": "llama3",
    "prompt": prompt,
    "stream": False
}

response = requests.post(url, json=data)

print(response.json()["response"])

執行結果:
Based on the current sensor data, I'll provide my analysis and recommendations as follows:

**1. 水質是否正常?**

根據文蛤最佳養殖條件,水溫高於31°C超出標準值(20-30°C),鹽度也低於15 ppt(12 ppt)。這些數據表明水質並不正常。

**2. 缺氧風險評估**

溶氧水平為3.5 mg/L,低於文蛤最佳養殖條件(≥4 mg/L),因此存在缺氧風險。高溫和低鹽度可能增加缺氧風險。

**3. 三項管理建議**

1. **降溫**:立即調整水溫至20-30°C,以減少缺氧風險。
2. **增氧**:增加溶氧水平以提高養殖池中的氧氣含量。
3. **鹽度調整**:增加鹽度至15-30 ppt,以滿足文蛤的需求。

**總結**

文蛤養殖池的水質不正常,存在缺氧風險。需要立即采取措施降溫、增氧和調整鹽度以改善水質,並減少對養殖戶的影響。

範例四、加入歷史資料

 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
import requests

url = "http://localhost:11434/api/generate"
prompt = '''
你是一個智慧養殖 AI 助手,負責分析文蛤養殖池的水質資料。

文蛤最佳養殖條件:
水溫:20–30°C
溶氧:≥4 mg/L
pH:7.5–8.5
鹽度:15–30 ppt

過去6小時水質變化:

時間    溫度   溶氧
10:00   29    5.0
12:00   30    4.2
14:00   31    3.5

請完成以下任務:
1. 判斷水質是否正常
2. 評估缺氧風險
3. 提供三項管理建議
4. 回覆需簡潔並適合養殖戶閱讀

請用繁體中文回答
'''

data = {
    "model": "llama3",
    "prompt": prompt,
    "stream": False
}

response = requests.post(url, json=data)

print(response.json()["response"])

執行結果:
Based on the water quality data, I'll provide my analysis and recommendations as follows:

**1.判斷水質是否正常**
水溫在 20–30°C 之間,達到文蛤最佳養殖條件;溶氧較低,4.2 mg/L 和 3.5 mg/L 是相對較低的數據,但仍在可接受範圍內(≥4 mg/L)。pH 值也在 7.5–8.5 之間。總的來說,水質大致正常,但溶氧值較低可能需要注意。

**2.評估缺氧風險**
根據數據,溶氧值下降明顯,從 5.0 mg/L 減少到 3.5 mg/L。在這種情況下,文蛤可能會發生缺氧的問題,因此需要注意監控水質和進行適當的調整。

**3.提供三項管理建議**

1. **監控溶氧值**:需要隨時監控溶氧值,確保其不再下降。
2. **增加養殖池流量**:增加養殖池流量可以幫助增加溶氧值和改善水質。
3. **增加 dissolved oxygen  (DO) 增強措施**:考慮使用 DO 增強措施,如增加磨灘設備或增加 aeration 設備,來提高溶氧值。

總的來說,水質大致正常,但需要注意監控和進行適當的調整,以避免文蛤養殖池中的缺氧問題。

2025年6月1日 星期日

Ollama+llama3.2完成智慧成績助教系統

本程式是由小鎮智能黃俊毓提供的程式碼改編而成,並經由ChatGPT協助除錯。

1.在ollama啟動llama3.2。


2.智慧成績助教系統的程式
  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
import ollama
from openpyxl import Workbook, load_workbook
import json
import os

# === Function Calling Schema ===
functions = [
    {
        "type":"function",
        "function": {
            "name":"suggest_pass_adjustment",
            "description": "對於 59 分學生,詢問是否補到 60 分",
            "parameters": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "description": "學生姓名(name)"
                    }
                 },
                 "required": ["name"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name":"suggest_remedial_adjustment",
            "description": "對於低於 59 分學生,詢問是否補分,以及新分數",
            "parameters": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "description": "學生姓名(name)"
                    },
                    "current_score": {"type": "integer"}
                 },
                 "required": ["name", "current_score"]
            }
        }
    },    
    {
        "type": "function",
        "function": {
            "name":"suggest_edit_for_passed",
            "description": "詢問是否要修改分數大於60分,及格學生的分數",
            "parameters": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "description": "學生姓名(name)"
                    },
                    "current_score": {"type": "integer"}
                 },
                 "required": ["name", "current_score"]
            }
        }
    }, 
    {
        "type": "function",
        "function": {
            "name":"suggest_apply_adjustment",
            "description": "將學生分數更新為指定的新分數",
            "parameters": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "description": "學生姓名(name)"
                    },
                    "new_score": {"type": "integer"}
                 },
                 "required": ["name", "new_score"]
            }
        }
    }, 
]

# === 初始化成績表(如不存在)===
filename = "grades.xlsx"
if not os.path.exists(filename):
    wb = Workbook()
    ws = wb.active
    ws.title = "成績表"
    ws.append(["姓名", "分數"])
    ws.append(["王小明", 59])
    ws.append(["林小美", 73])
    ws.append(["張大文", 45])
    wb.save(filename)
    print(f"✅ 已建立初始成績檔:{filename}")
else:
    print(f"📥 已載入成績檔:{filename}")

# === GPT 對應的處理函式 ===

# 以下四個函式為 GPT 根據不同情況呼叫的處理邏輯
# 建議學生逐步閱讀與理解:輸入、邏輯、Excel 修改方式

def handle_pass_adjustment(row, name):
    ans = input(f"{name} 的分數是 59,是否補及格至 60?(Y/n):")
    if ans.lower() in ["y", "yes", ""]:
        row[1].value = 60
        print(f"✅ {name} 已補及格(60 分)")
        return f"{name} 補及格至 60 分 建議多加強"
    else:
        print("🟡 未調整")
        return f"{name} 未補及格"

def handle_remedial_adjustment(row, name, score):
    ans = input(f"{name} 的分數是 {score},是否補分?(Y/n):")
    if ans.lower() in ["y", "yes", ""]:
        try:
            new_score = int(input("👉 請輸入補分後的新分數:"))
            row[1].value = new_score
            print(f"✅ 已將 {name} 改為 {new_score} 分")
            return f"{name} 補分為 {new_score} 分 建議多加強"
        except:
            print("⚠️ 格式錯誤,略過")
            return f"{name} 補分輸入錯誤,未調整"
    else:
        print("🟡 未調整")
        return f"{name} 未補分"

def handle_edit_for_passed(row, name, score):
    ans = input(f"{name} 成績為 {score} 分,是否要修改?(輸入新分數或按 Enter 跳過):")
    if ans.strip():
        try:
            new_score = int(ans)
            row[1].value = new_score
            print(f"✅ 已將 {name} 改為 {new_score} 分")
            return f"{name} 改為 {new_score} 分"
        except:
            print("⚠️ 格式錯誤,略過")
            return f"{name} 修改輸入錯誤,未調整"
    else:
        print("✅ 保留原分數")
        return f"{name} 保留原分數 {score} 分"

def handle_apply_adjustment(row, name, new_score):
    row[1].value = new_score
    print(f"✅ GPT 決定將 {name} 的分數改為 {new_score}")
    return f"{name} 的分數改為 {new_score}"

# === 以下請同學補寫 main loop ===
# - 使用 for row in ws.iter_rows(min_row=2): 遍歷每位學生
# - 呼叫 GPT 的 chat.completions.create 傳入使用者輸入與 function schema
# - 根據 GPT 回傳的 function_call.name 判斷要呼叫哪一個處理函式
# - 最後將分數儲存為 grades_final.xlsx

# 提示:請將回傳的 arguments 用 json.loads(...) 解析後取出參數

wb = load_workbook(filename)
ws = wb.active

for row in ws.iter_rows(min_row=2):
    name = row[0].value
    score = row[1].value

    user_input = f"{name} 的分數是 {score}"
    
    response = ollama.chat(
        model="llama3.2",
        messages=[{"role": "user", "content": user_input}],
        tools=functions,
    )

    if hasattr(response, "message") and hasattr(response.message, "tool_calls") and response.message.tool_calls:
        tool_call = response.message.tool_calls[0]
        func_name = tool_call['function']['name']
        args = tool_call['function']['arguments']  

        if func_name == "suggest_pass_adjustment":
            result = handle_pass_adjustment(row, name)
        elif func_name == "suggest_remedial_adjustment":
            result = handle_remedial_adjustment(row, name, args['current_score'])
        elif func_name == "suggest_edit_for_passed":
            result = handle_edit_for_passed(row, name, args['current_score'])
        elif func_name == "suggest_apply_adjustment":
            result = handle_apply_adjustment(row, name, args['new_score'])
        else:
            result = "❌ 無對應函式"

        # 後續回應
        follow_up = ollama.chat(
            model="llama3.2",
            messages=[
                {"role": "user", "content": user_input},
                response.message,
                {"role": "tool", "name": func_name, "content": result}
            ]
        )
        print(f"💬 GPT 回覆:{follow_up.message['content']}")
    else:
        print("🤖 GPT 沒有呼叫任何函式")
# === 儲存檔案 ===
final_name = "grades_final.xlsx"
wb.save(final_name)
print(f"\n🎉 所有成績處理完成,已儲存為 {final_name}")

3.執行結果:


2024年7月29日 星期一

透過 Ollama 本地部署 Llama 3.1 大型語言模型服務

開源模型的好處是讓企業得以根據需求用公司內部資料來建置模型,而不受封閉模型供應商的限制。

Llama 是 Meta 釋出的開源模型,Meta 於 7/23 釋出了 Llama 3.1 其亮點 405B (4,050 億參數) 是 Meta 迄今為止最強大的模型, 趁前兩天颱風假的空檔利用 Ollama + Llama 3.1 來架設一個私有的大型語言模型服務( LLM Model )。

Ollama 是一個開源軟體,使用者可以在自己的硬體上執行大型語言模型服務。選用 Ollama 是因為其架設容易且支援的模型總類很多,官方有提供 Windows, Apple, Linux OS 的安裝程式,可用短短的幾分鐘就可以在自己的個人電腦上架設完成大型語言模型服務。