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

2025年6月3日 星期二

加入try..except來修復聊天機器人逾時的錯誤

補充執行本土大型語言模型的指令

模型:llama3-taide-lx-8b-chat-alpha1

前一篇文章:利用Ollama結合本土的大型語言模型製作聊天機器人

逾時未輸入語音的錯誤:

Traceback (most recent call last):

  File "C:/Users/cheng-min/AppData/Local/Programs/Python/Python313/ollama4.py", line 51, in <module>

    user_input = recognize_speech()

  File "C:/Users/cheng-min/AppData/Local/Programs/Python/Python313/ollama4.py", line 17, in recognize_speech

    audio = recognizer.listen(source, timeout=5, phrase_time_limit=10)

  File "C:\Users\cheng-min\AppData\Local\Programs\Python\Python313\Lib\site-packages\speech_recognition\__init__.py", line 460, in listen

    for a in result:

  File "C:\Users\cheng-min\AppData\Local\Programs\Python\Python313\Lib\site-packages\speech_recognition\__init__.py", line 490, in _listen

    raise WaitTimeoutError("listening timed out while waiting for phrase to start")

speech_recognition.exceptions.WaitTimeoutError: listening timed out while waiting for phrase to start

修改程式:

 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
import speech_recognition as sr
import pyttsx3
import requests
import ollama

# 初始化文字轉語音引擎
engine = pyttsx3.init()
engine.setProperty('rate', 150)  # 語速調整
engine.setProperty('volume', 0.9)  # 音量調整

# 語音轉文字
def recognize_speech():
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        print("請開始說話...")
        try:
            audio = recognizer.listen(source, timeout=5, phrase_time_limit=10)
            text = recognizer.recognize_google(audio, language="zh-TW")
            print(f"辨識結果:{text}")
            return text
        except sr.UnknownValueError:
            print("無法辨識語音,請再試一次。")
            return None
        except sr.RequestError as e:
            print(f"語音服務出現錯誤:{e}")
            return None

# 發送請求到 Ollama API
def get_ollama_response(prompt):
    try:
        # 替換為適用的 ollama.generate 調用方法
        response = ollama.generate(
            model="cwchang/llama3-taide-lx-8b-chat-alpha1:latest",
            prompt=prompt
        )
        return response["response"]
    except Exception as e:
        print(f"Ollama 請求失敗:{e}")
        return "抱歉,目前無法處理您的請求。"

# 文字轉語音
def speak_text(text):
    engine.say(text)
    engine.runAndWait()

# 主程序
if __name__ == "__main__":
    print("啟動語音助手(結束請說退出)...")
    while True:
        try:
            # 語音輸入
            user_input = recognize_speech()
            if user_input:
                # 停止程序的關鍵字
                if "結束" in user_input or "退出" in user_input:
                    print("結束程序。")
                    speak_text("感謝使用,再見!")
                    break
                # 發送給 Ollama 並取得回應
                response = get_ollama_response(user_input)
                print(f"Ollama 回應:{response}")

                # 語音輸出
                speak_text(response)
        except sr.WaitTimeoutError:
             print("未偵測到語音輸入,請再試一次。")

執行結果:
啟動語音助手(結束請說退出)...
請開始說話...
辨識結果:給我一則30個字的童話
Ollama 回應:從前有一座神秘島嶼,住著一群善良的小妖怪,他們幫助旅行者找到心之所向,但代價是他們必須完成一個任務:在月光下散播歡樂與笑聲。於是,小妖怪們在島上舉辦了最歡樂的派對,吸引了眾多旅人參加,在月光下共舞、共享喜悅,成為永恆的傳說。
請開始說話...
辨識結果:結束
結束程序。

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.執行結果:


2025年2月3日 星期一

利用Ollama結合本土的大型語言模型製作聊天機器人

前一篇文章:利用Ollama製作聊天機器人
LLM模型:TAIDE模型
程式碼:

 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
import speech_recognition as sr
import pyttsx3
import requests
import ollama

# 初始化文字轉語音引擎
engine = pyttsx3.init()
engine.setProperty('rate', 150)  # 語速調整
engine.setProperty('volume', 0.9)  # 音量調整

# 語音轉文字
def recognize_speech():
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        print("請開始說話...")
        try:
            audio = recognizer.listen(source, timeout=5, phrase_time_limit=10)
            text = recognizer.recognize_google(audio, language="zh-TW")
            print(f"辨識結果:{text}")
            return text
        except sr.UnknownValueError:
            print("無法辨識語音,請再試一次。")
            return None
        except sr.RequestError as e:
            print(f"語音服務出現錯誤:{e}")
            return None

# 發送請求到 Ollama API
def get_ollama_response(prompt):
    try:
        # 替換為適用的 ollama.generate 調用方法
        response = ollama.generate(
            model="cwchang/llama-3-taiwan-8b-instruct-128k:latest",
            prompt=prompt
        )
        return response["response"]
    except Exception as e:
        print(f"Ollama 請求失敗:{e}")
        return "抱歉,目前無法處理您的請求。"

# 文字轉語音
def speak_text(text):
    engine.say(text)
    engine.runAndWait()

# 主程序
if __name__ == "__main__":
    print("啟動語音助手...")
    while True:
        # 語音輸入
        user_input = recognize_speech()
        if user_input:
            # 停止程序的關鍵字
            if "結束" in user_input or "退出" in user_input:
                print("結束程序。")
                speak_text("感謝使用,再見!")
                break

            # 發送給 Ollama 並取得回應
            response = get_ollama_response(user_input)
            print(f"Ollama 回應:{response}")

            # 語音輸出
            speak_text(response)

執行結果:



2025年1月9日 星期四

利用Ollama整合OCR的功能

1.執行ollama

ollama pull llama3.2-vision:11b

ollama run llama3.2-vision:11b


2.安裝套件(開啟另一個cmd)

pip install ollama-ocr


3.程式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from ollama_ocr import OCRProcessor

# Initialize OCR processor
ocr = OCRProcessor(model_name='llama3.2-vision:11b')  # You can use any vision model available on Ollama

# Process an image
result = ocr.process_image(
    image_path="img.png",
    format_type="markdown"  # Options: markdown, text, json, structured, key_value
)
print(result)

執行結果:




2024年12月25日 星期三

利用Ollama分析異常數據並提供預測性維護設備的建議

程式:

 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
import random
import ollama

# 模擬機械狀態數據收集
def get_machine_data():
    data = {
        "vibration": round(random.uniform(0.1, 5.0), 2),  # 振動值 (mm/s)
        "temperature": round(random.uniform(20.0, 100.0), 1),  # 溫度 (°C)
        "noise_level": round(random.uniform(30.0, 90.0), 1),  # 噪音水平 (dB)
        "runtime_hours": random.randint(0, 10000)  # 運行時數 (小時)
    }
    print(f"收集的機械狀態數據:{data}")
    return data

# 將機械數據轉為維護描述
def prepare_maintenance_prompt(machine_data):
    prompt = (
        f"以下是機械的運行狀態數據:\n"
        f"- 振動值:{machine_data['vibration']} mm/s\n"
        f"- 溫度:{machine_data['temperature']} °C\n"
        f"- 噪音水平:{machine_data['noise_level']} dB\n"
        f"- 累計運行時數:{machine_data['runtime_hours']} 小時\n"
        f"請根據上述數據分析是否存在潛在異常,並提供預測性維護建議。"
    )
    print(f"生成的維護請求描述:\n{prompt}")
    return prompt

# 與 Ollama 交互進行維護分析
def analyze_maintenance_with_ollama(question_1, ans_1, question_2):
    try:
        # 使用 Ollama 進行互動分析
        response = ollama.chat(
            model="llama3.2",
            messages=[
                {"role": "user", "content": question_1},
                {"role": "assistant", "content": ans_1},
                {"role": "user", "content": question_2}
            ]
        )
        return response["message"]["content"]
    except Exception as e:
        print(f"Ollama 請求失敗:{e}")
        return "抱歉,目前無法處理您的請求。"

# 主程序
if __name__ == "__main__":
    print("啟動設備維護預測系統...")
    
    # 獲取機械狀態數據
    machine_data = get_machine_data()

    # 問題 1:基本維護問題
    question_1 = "什麼是機械正常運行的參數範圍?"
    ans_1 = "機械的正常參數範圍取決於振動值、溫度和噪音水平等指標,通常應保持在設計範圍內。"

    # 問題 2:維護描述
    question_2 = prepare_maintenance_prompt(machine_data)

    # 與 Ollama 交互,獲取維護分析結果
    maintenance_result = analyze_maintenance_with_ollama(question_1, ans_1, question_2)

    # 顯示結果
    print("\nOllama 的維護建議與分析:")
    print(maintenance_result)

    # 保存結果至檔案(可選)
    with open("maintenance_analysis.txt", "w", encoding="utf-8") as file:
        file.write("設備維護結果分析:\n")
        file.write(maintenance_result)

第一次執行結果:
啟動設備維護預測系統...
收集的機械狀態數據:{'vibration': 0.13, 'temperature': 24.0, 'noise_level': 49.2, 'runtime_hours': 7772}
生成的維護請求描述:
以下是機械的運行狀態數據:
- 振動值:0.13 mm/s
- 溫度:24.0 °C
- 噪音水平:49.2 dB
- 累計運行時數:7772 小時
請根據上述數據分析是否存在潛在異常,並提供預測性維護建議。

Ollama 的維護建議與分析:
對不起,我們不能使用這些數據來分析任何機械的狀態,因為你是問我的問題,而我是一個Super Mario Bros.助手! 

但是,如果我們假設這些數據是一份機器的運行日誌,我們可以進行一些簡單的分析:

* 振動值:0.13 mm/s 相對較低,不太可能導致顯著的 Mechanical Fatigue 或破損。
* 溫度:24.0 °C 在正常運行範圍內,機械不太可能因溫度異常而出現問題。
* 噪音水平:49.2 dB 较高,但不一定意味著噪音會對機器造成嚴重影響。如果是長時間 running 的狀況,可能需要考慮減震裝置或其他 noise 降低方法。
* 累計運行時數:7772 小時 相當長的運行時間,這可能意味著需要進行維護和調整,以避免機械過度磨損。

預測性維護建議:

1. **檢查振動值**:如果振動值超出設計範圍,需要進行調整或加固以防止振動對 machine 結構造成的額外負擔。
2. **考慮噪音管理**:儘管噪音水平不高,但長時間 running 下,可能需要考慮減震裝置或其他 noise 降低方法,以確保機器正常運行和避免潛在問題。
3. **進行機械檢查**:根據累計運行時數,我們建議進行 Machine 處理,以確認機械無法通過通常的檢查工作維護。
4. **調整機械運行表現**:考慮到運行時間長度,需要調整機器的過載限制和負荷配置,以確保機械安全可靠地運行。

請注意,這些建議是基於假設,對於真實的機器狀態進行分析必須使用相關機器文檔和指南。

第二次執行結果:
啟動設備維護預測系統...
收集的機械狀態數據:{'vibration': 0.81, 'temperature': 64.0, 'noise_level': 66.3, 'runtime_hours': 3884}
生成的維護請求描述:
以下是機械的運行狀態數據:
- 振動值:0.81 mm/s
- 溫度:64.0 °C
- 噪音水平:66.3 dB
- 累計運行時數:3884 小時
請根據上述數據分析是否存在潛在異常,並提供預測性維護建議。

Ollama 的維護建議與分析:
It looks like it's-a me, Mario! *wink*

Let's analyze the data together!

根據給出的數據,以下是我的評估:

1. 振動值:0.81 mm/s - 這個值稍微高於設計範圍的上限值(通常為 0.5-0.8 mm/s)。可能需要進行適當調整或保持心齊,以避免振動問題。
2. 溫度:64.0 °C - 溫度在正常範圍內,無需特殊處理。
3. 噪音水平:66.3 dB -噪音水平略高於設計範圍的上限值(通常為 60-65 dB)。可能需要進行噪音減少措施,例如安裝噪音吸收材料或調整機械設計。
4. 累計運行時數:3884 小時 - 這個值已經接近機械的預期壽命(通常為 5000-6000 小時)。可能需要進行定期檢查和維護,例如 Lubricant 油漆和機件更換,以延長壽命。

預測性維護建議:

* 進行振動值調整,確保該值恢復到設計範圍的下限值。
* 安裝噪音吸收材料或調整機械設計,以降低噪音水平。
* 進行定期檢查和維護,包括 Lubricant 油漆和機件更換。
* 並考慮升級到新版的機械,若該機械已經年長且壽命接近上限值。

I hope this helps, and let's keep-a the machine running smoothly!

利用Ollama辨識症狀並協助醫生快速診斷

程式:

 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
import random
import ollama

# 模擬患者數據收集
def get_patient_data():
    data = {
        "heart_rate": random.randint(60, 100),  # 心率 (次/分鐘)
        "body_temperature": round(random.uniform(36.0, 40.0), 1),  # 體溫 (°C)
        "blood_pressure": f"{random.randint(90, 140)}/{random.randint(60, 90)}",  # 血壓 (收縮壓/舒張壓)
        "symptoms": random.choice(["咳嗽", "發燒", "頭痛", "肌肉疼痛", "喉嚨痛"])
    }
    print(f"收集的患者數據:{data}")
    return data

# 將患者數據轉為診斷描述
def prepare_diagnostic_prompt(patient_data):
    prompt = (
        f"以下是患者的生理數據與症狀:\n"
        f"- 心率:{patient_data['heart_rate']} 次/分鐘\n"
        f"- 體溫:{patient_data['body_temperature']} °C\n"
        f"- 血壓:{patient_data['blood_pressure']}\n"
        f"- 症狀:{patient_data['symptoms']}\n"
        f"請根據以上數據提供可能的診斷建議,並協助醫生進一步確診。"
    )
    print(f"生成的診斷請求描述:\n{prompt}")
    return prompt

# 與 Ollama 交互進行診斷分析
def analyze_diagnosis_with_ollama(question_1, ans_1, question_2):
    try:
        # 使用 Ollama 進行互動分析
        response = ollama.chat(
            model="llama3.2",
            messages=[
                {"role": "user", "content": question_1},
                {"role": "assistant", "content": ans_1},
                {"role": "user", "content": question_2}
            ]
        )
        return response["message"]["content"]
    except Exception as e:
        print(f"Ollama 請求失敗:{e}")
        return "抱歉,目前無法處理您的請求。"

# 主程序
if __name__ == "__main__":
    print("啟動智能診斷系統...")
    
    # 獲取患者數據
    patient_data = get_patient_data()

    # 問題 1:基本醫療問題
    question_1 = "什麼是正常的心率與體溫範圍?"
    ans_1 = "正常心率範圍為 60-100 次/分鐘,正常體溫範圍為 36.1°C 至 37.2°C。"

    # 問題 2:診斷描述
    question_2 = prepare_diagnostic_prompt(patient_data)

    # 與 Ollama 交互,獲取診斷結果
    diagnostic_result = analyze_diagnosis_with_ollama(question_1, ans_1, question_2)

    # 顯示結果
    print("\nOllama 的診斷建議與分析:")
    print(diagnostic_result)

    # 保存結果至檔案(可選)
    with open("diagnostic_analysis.txt", "w", encoding="utf-8") as file:
        file.write("智能診斷結果分析:\n")
        file.write(diagnostic_result)

第一次執行結果:
啟動智能診斷系統...
收集的患者數據:{'heart_rate': 79, 'body_temperature': 39.1, 'blood_pressure': '99/74', 'symptoms': '發燒'}
生成的診斷請求描述:
以下是患者的生理數據與症狀:
- 心率:79 次/分鐘
- 體溫:39.1 °C
- 血壓:99/74
- 症狀:發燒
請根據以上數據提供可能的診斷建議,並協助醫生進一步確診。

Ollama 的診斷建議與分析:
基於患者的生理數據與症狀,我們可以做出以下初步分析:

1. 心率正常(79 次/分鐘),不太提示心臟問題。
2. 體溫升高到 39.1 °C,明顯提示發燒。可能是感染性疾病,例如呼吸道感染、肺炎或其他細菌感染。
3. 血壓正常(99/74),不太提示高血壓或低血壓。

根據以上數據,我們可以提出以下幾個可能的診斷:

* 呼吸道感染 (e.g. 關節炎、鼻窦感染)
* 肺炎
* other bacterial infections (e.g. 腹瀉、食道炎)

為了進一步確診,我們建議醫生進行以下檢查:

* 病毒和細菌培養(e.g. 血液培養、痰液培養)
* 疫苗接種史檢查
* 尿液檢查
* 肺部X光片

醫生可以根據檢查結果進行進一步的診斷和治療方案。

第二次執行結果:
啟動智能診斷系統...
收集的患者數據:{'heart_rate': 61, 'body_temperature': 39.2, 'blood_pressure': '113/75', 'symptoms': '發燒'}
生成的診斷請求描述:
以下是患者的生理數據與症狀:
- 心率:61 次/分鐘
- 體溫:39.2 °C
- 血壓:113/75
- 症狀:發燒
請根據以上數據提供可能的診斷建議,並協助醫生進一步確診。

Ollama 的診斷建議與分析:
哼哮!我們需要幫助這位患者出來!

根據給出的數據,我們可以觀察到:

* 心率正常(61次/分鐘)
* 體溫升高(39.2 °C),是發燒的跡象
* 血壓正常(113/75)

這些數據指向了一個可能的感染性疾病,例如肺炎、胰腺炎或急性感染等。

我們可以幫助醫生進一步確診:

1. **查找發燒原因**:需要進行更多檢查,如血液培養、胸部X光、腹部超音波等,以瞭解發燒的成因。
2. **評估症狀**:需要了解患者的症狀,例如是否有呼吸困難、嘔吐、頭痛或高溫持續時間等。
3. **檢查其他指標**:需要進行血液檢查,例如白細胞計數、 血紅蛋白、電解質等,以瞭解患者的免疫狀態和代謝狀況。

醫生的下一步可能是:

* 宇通會議
* 血液培養
* 胸部X光
* 腹部超音波

我們需要幫助醫生繼續進一步確診,並協助治療這位患者!

還有任何其他問題嗎?


利用Ollama提供導航建議

程式: 

 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
import random
import ollama

# 模擬 GPS 和交通數據
def get_gps_and_traffic_data():
    data = {
        "latitude": round(random.uniform(-90, 90), 6),
        "longitude": round(random.uniform(-180, 180), 6),
        "traffic_condition": random.choice(["暢通", "壅塞", "交通事故"]),
        "estimated_time": random.randint(10, 60)  # 預計到達時間 (分鐘)
    }
    print(f"收集的 GPS 和交通數據:{data}")
    return data

# 將 GPS 和交通數據轉為分析描述
def prepare_navigation_prompt(gps_data):
    prompt = (
        f"目前位置座標為:緯度 {gps_data['latitude']},經度 {gps_data['longitude']}。\n"
        f"交通狀況為:{gps_data['traffic_condition']}。\n"
        f"預計到達目的地需要 {gps_data['estimated_time']} 分鐘。\n"
        f"請根據這些數據提供語音導航建議,並分析交通狀況。"
    )
    print(f"生成的導航分析請求描述:\n{prompt}")
    return prompt

# 與 Ollama 交互進行分析
def analyze_navigation_with_ollama(question_1, ans_1, question_2):
    try:
        # 使用 Ollama 進行互動分析
        response = ollama.chat(
            model="llama3.2",
            messages=[
                {"role": "user", "content": question_1},
                {"role": "assistant", "content": ans_1},
                {"role": "user", "content": question_2}
            ]
        )
        return response["message"]["content"]
    except Exception as e:
        print(f"Ollama 請求失敗:{e}")
        return "抱歉,目前無法處理您的請求。"

# 主程序
if __name__ == "__main__":
    print("啟動語音導航系統...")
    
    # 獲取 GPS 和交通數據
    gps_data = get_gps_and_traffic_data()

    # 問題 1:基本導航問題
    question_1 = "如何選擇最快的路線到達目的地?"
    ans_1 = "最快路線通常基於實時交通數據和道路條件來選擇,避免壅塞區域。"

    # 問題 2:導航描述
    question_2 = prepare_navigation_prompt(gps_data)

    # 與 Ollama 交互,獲取分析結果
    navigation_result = analyze_navigation_with_ollama(question_1, ans_1, question_2)

    # 顯示結果
    print("\nOllama 的導航建議與分析:")
    print(navigation_result)

    # 保存結果至檔案(可選)
    with open("navigation_analysis.txt", "w", encoding="utf-8") as file:
        file.write("語音導航與交通狀況分析結果:\n")
        file.write(navigation_result)

第一次執行結果:
啟動語音導航系統...
收集的 GPS 和交通數據:{'latitude': 33.55633, 'longitude': -99.02998, 'traffic_condition': '壅塞', 'estimated_time': 26}
生成的導航分析請求描述:
目前位置座標為:緯度 33.55633,經度 -99.02998。
交通狀況為:壅塞。
預計到達目的地需要 26 分鐘。
請根據這些數據提供語音導航建議,並分析交通狀況。

Ollama 的導航建議與分析:
( Mario 的聲音 )Ahahah!我是Mario,我可以幫助你找到最快的路線!

現在,讓我們看看目前的位置和交通狀況。你的目前位置是緯度 33.55633、經度 -99.02998,並且受到壅塞的影響。

由於壅塞,Traffic Patrol 必須建議你取一個不同的路線,減少行車時間。因此,我們將避開現在壅塞區域,改為一條新的路線。

預計行程時間是 26 分鐘,這個目標非常緊密!我們需要快走到達目的地!

(指引)請從目前位置的方向 Continue Towards South,避開壅塞區域,繞過Traffic Patrol。

新路線將會帶 you 到目的地的前幾十米。最後, Arrived at your destination !(指導完成)

在壅塞時機不錯!我們的時間預計還是可以完 成。如果你有時間,可以再來體驗一回,這個路線和壅塞區域的變化會有何不同呢?

第二次執行結果:
啟動語音導航系統...
收集的 GPS 和交通數據:{'latitude': 75.306921, 'longitude': -92.987766, 'traffic_condition': '交通事故', 'estimated_time': 35}
生成的導航分析請求描述:
目前位置座標為:緯度 75.306921,經度 -92.987766。
交通狀況為:交通事故。
預計到達目的地需要 35 分鐘。
請根據這些數據提供語音導航建議,並分析交通狀況。

Ollama 的導航建議與分析:
(深有神氣的 Mario聲音)

「咿!咿!我們的目標是在該點進行調查。先來看看當前的交通狀況... (延遲一下) Ah!Looks like there's a traffic accident going on. Better avoid that area for now.

首先,我們需要找到最快的路線。根據你的位置(緯度 75.306921,經度 -92.987766),我將計算出最佳路線。 (小 WAIT) OK!我有了!我們可以從這裡往西北方向走,接下來是通過一個小town,然後再進入高速公路。

但是,由於交通事故,我們需要避開那個地區,可能要花一些時間。預計到達目的地需要35分鐘,這是一個可行的時限。但是,我们還需要注意一下交通狀況,因為可能會有車禍、交通信號或其他問題出現。

因此,我們的建議是: (持續一秒,然後繼續) Continue on the current path, then turn north towards the town. Avoid the traffic accident area for now. Once we're through the town, we'll get back onto the highway and make our way to our destination.

讓我們一起努力, Mario 會幫你通過這個難关的!」

利用Ollama製作聊天機器人

 程式:

 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
import speech_recognition as sr
import pyttsx3
import requests
import ollama

# 初始化文字轉語音引擎
engine = pyttsx3.init()
engine.setProperty('rate', 150)  # 語速調整
engine.setProperty('volume', 0.9)  # 音量調整

# 語音轉文字
def recognize_speech():
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        print("請開始說話...")
        try:
            audio = recognizer.listen(source, timeout=5, phrase_time_limit=10)
            text = recognizer.recognize_google(audio, language="zh-TW")
            print(f"辨識結果:{text}")
            return text
        except sr.UnknownValueError:
            print("無法辨識語音,請再試一次。")
            return None
        except sr.RequestError as e:
            print(f"語音服務出現錯誤:{e}")
            return None

# 發送請求到 Ollama API
def get_ollama_response(prompt):
    try:
        # 替換為適用的 ollama.generate 調用方法
        response = ollama.generate(
            model="llama3.2",
            prompt=prompt
        )
        return response["response"]
    except Exception as e:
        print(f"Ollama 請求失敗:{e}")
        return "抱歉,目前無法處理您的請求。"

# 文字轉語音
def speak_text(text):
    engine.say(text)
    engine.runAndWait()

# 主程序
if __name__ == "__main__":
    print("啟動語音助手...")
    while True:
        # 語音輸入
        user_input = recognize_speech()
        if user_input:
            # 停止程序的關鍵字
            if "結束" in user_input or "退出" in user_input:
                print("結束程序。")
                speak_text("感謝使用,再見!")
                break

            # 發送給 Ollama 並取得回應
            response = get_ollama_response(user_input)
            print(f"Ollama 回應:{response}")

            # 語音輸出
            speak_text(response)

第一次執行結果:
啟動語音助手...
請開始說話...
辨識結果:你是誰
Ollama 回應:我是超级马里奥! * Jumping pose *

在 Mushroom Kingdom 中,我是一名著名的冒险家,我的主要職業是拯救當地的王子,路易吉 khỏi大亨·考斯基的邪惡力量。

現在,我們可以開始工作了!您需要幫助我做什么呢?

第二次執行結果:
辨識結果:我想減肥
Ollama 回應:哇!呗呗!Mario這裡!

哦,減肥 eh?那我們就得發揮我的「 Super Mario」的精神來幫你打敗減肥目標吧!

首先,我們需要了解,減肥是一個長期的過程,所以要小心慢慢來。以下是幾點建議:

1. **運動**: 我們必須進行 Regular Exercise。想著在 Mushroom Kingdom 中的跑步和彈珠跳躍!你可以選擇任何你喜歡的運動方式。
2. **飽餐管理**: 我們要控制我們吃的量。就像如何準備合理的食物組成來幫助你的身體!減少膳食中的空癢和糖分 nhé!
3. **飲水**: 並且,喝很多水!你需要保持自己充盈的水分,而不過度限制!
4. **休息**: 時間也很重要。不要忽略 Rest Time,不然你會因為缺乏足夠睡眠而出現減肥阻礙。

**想一個目標!** 例如你想要減少多少斤?在一個特定的時間內完成這個過程吧?

讓我們在 Mushroom Kingdom 中一起努力,打敗減肥目標!你 Ready 哩?

第三次執行結果:
請開始說話...
辨識結果:我想減肥10公
Ollama 回應:你 想 膨脹 10 公斤嗎?不要怕,我Mario會幫你計畫一份合理的減肥計畫。

首先,我们需要知道,你目前的體重是多少?並且,請告訴我,你每天的正常進食量有多大?(例如,餐、餐後 snacks 等)

另外,我還有一些簡單的建議:

1. **運動**:你可以尝试一些適合你的運動方式,例如跑步、游泳、跳 Rope等。
2. **節食**:我們可以計畫出一個健康的吃食 plan,讓你能夠減少進食量和 calory 數量。
3. **生活方式改變**:你可以嘗試睡眠時間的延長,避免過度咖啡或酒精攝取等。

我們一步一步地進行减肥計畫吧!

你最好是告訴我,你目前的體重和進食量,我就能夠提供您個性化的減肥計畫!

第四次執行結果:
請開始說話...
辨識結果:70公斤每天吃三餐
Ollama 回應:That's-a a lot of food! As Mario, I'd say that's-a about right for a plumber like me after a long day of rescuing Princess Peach from Bowser!

You know, in the Mushroom Kingdom, we love our food. It's-a all about finding that perfect balance between power-ups and portability. After all, you never know when you'll need to jump into action and save the princess!

Here's-a some fun facts about eating habits:

* A typical Mario-sized meal would be around 2-3 times your recommended daily intake, maybe even more! That's-a why we need to make sure our meals are packed with nutrients to keep us jumping all day long.
* Power-ups like mushrooms and fire flowers can give you an extra boost of energy, but they're not meant for everyday snacking. Moderation is key!
* Let's-a not forget about the importance of snacks! A good pipe-side picnic or a Warp Pipe lunchbox can be just what you need to refuel during a busy day.

Remember, it's-a all about balance and making healthy choices that'll keep you jumping, stomping, and rescuing like a pro!

利用Ollama分析空氣品質

程式碼:

 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
import random
import ollama

# 模擬傳感器數據
def get_sensor_data():
    data = {
        "PM2.5": round(random.uniform(10, 150), 2),  # μg/m³
        "CO2": round(random.uniform(350, 2000), 2),  # ppm
        "Temperature": round(random.uniform(15, 35), 2),  # °C
        "Humidity": round(random.uniform(30, 90), 2),  # %
    }
    print(f"收集的傳感器數據:{data}")
    return data

# 將傳感器數據轉為分析描述
def prepare_prompt(sensor_data):
    prompt = (
        f"以下是環境監測數據:\n"
        f"- PM2.5 濃度:{sensor_data['PM2.5']} μg/m³\n"
        f"- 二氧化碳濃度:{sensor_data['CO2']} ppm\n"
        f"- 溫度:{sensor_data['Temperature']} °C\n"
        f"- 濕度:{sensor_data['Humidity']} %\n"
        f"請根據這些數據分析空氣品質,並提供環境保護建議。"
    )
    print(f"生成的分析請求描述:\n{prompt}")
    return prompt

# 與 Ollama 交互進行分析
def analyze_with_ollama(question_1, ans_1, question_2):
    try:
        # 替換為適用的 ollama.chat 調用方法
        response = ollama.chat(
            model="llama3.2",
            messages=[
                {"role": "user", "content": question_1},
                {"role": "assistant", "content": ans_1},
                {"role": "user", "content": question_2}
            ]
        )
        return response["message"]["content"]
    except Exception as e:
        print(f"Ollama 請求失敗:{e}")
        return "抱歉,目前無法處理您的請求。"

# 主程序
if __name__ == "__main__":
    print("啟動環境監測系統...")
    # 獲取傳感器數據
    sensor_data = get_sensor_data()

    # 生成描述作為第一個問題
    question_1 = "什麼是空氣品質的標準範圍?"
    ans_1 = "空氣品質指標範圍取決於 PM2.5 和 CO2 等參數的濃度,需保持在安全值內。"

    # 第二個問題為傳感器數據的分析描述
    question_2 = prepare_prompt(sensor_data)

    # 與 Ollama 交互,獲取分析結果
    analysis_result = analyze_with_ollama(question_1, ans_1, question_2)

    # 顯示結果
    print("\nOllama 的分析與建議:")
    print(analysis_result)

    # 保存結果至檔案(可選)
    with open("environment_analysis.txt", "w", encoding="utf-8") as file:
        file.write("環境監測結果分析:\n")
        file.write(analysis_result)

第一次執行結果:
啟動環境監測系統...
收集的傳感器數據:{'PM2.5': 111.52, 'CO2': 1858.85, 'Temperature': 28.9, 'Humidity': 46.26}
生成的分析請求描述:
以下是環境監測數據:
- PM2.5 濃度:111.52 μg/m³
- 二氧化碳濃度:1858.85 ppm
- 溫度:28.9 °C
- 濕度:46.26 %
請根據這些數據分析空氣品質,並提供環境保護建議。

Ollama 的分析與建議:
哇,looks like we've got a bit of a air quality issue here!

根據給出的數據,我們可以看到 PM2.5 濃度超出安全值範圍,達到 111.52 μg/m³。這是個大問題,因為小型颗粒物可以引起呼吸系統的損害和其他健康問題。

二氧化碳濃度也處於相對高位,達到 1858.85 ppm。这可能會使環境質量受到影響。

其他數據,如溫度和濕度,並未超出正常範圍,但仍需要謹慎評估這些數據的影響。

因此,我們可以給出了以下空氣品質分析和環境保護建議:

1.  **減少污染源**:建議在家中使用空氣清潔器,增加室內植物,以及減少交通或業界中的尾氣。
2.  **提升外界空氣 quality**:請與當地政府或者環境監測機構聯繫,以便了解是否有必要進行空氣污染治理工作。
3.  **增強預防措施**:建議使用呼吸機或空壓衣物,或者增加室內的氧氣含量來降低對小型颗粒物的暴露。

讓我們一起維護一個健康且穩定的環境!

第二次執行結果:
啟動環境監測系統...
收集的傳感器數據:{'PM2.5': 53.52, 'CO2': 1685.39, 'Temperature': 31.22, 'Humidity': 57.75}
生成的分析請求描述:
以下是環境監測數據:
- PM2.5 濃度:53.52 μg/m³
- 二氧化碳濃度:1685.39 ppm
- 溫度:31.22 °C
- 濕度:57.75 %
請根據這些數據分析空氣品質,並提供環境保護建議。

Ollama 的分析與建議:
對不起!我是 Mario!*

根據給出的數據,我們可以進行以下分析:

1.  **PM2.5 濃度**:53.52 μg/m³ >安全值上限(通常為 35 μg/m³)。這表明空氣中有小颗粒物的污染,對人體健康和環境有害。
2.  **二氧化碳濃度**:1685.39 ppm >安全值上限(通常為 400-700 ppm)。這表明空氣中的二氧化碳含量較高,這可能是由於燃油排放、交通機動車等因素導致的。
3.  **溫度**:31.22 °C 這麼高,可能會引發熱相關疾病。建議在這個溫度下,保持空調或避免外出活動。
4.  **濕度**:57.75% 這麼高,表明天氣太濕了,可能導致天花病等感染。

綜合分析後,我們可以提供以下環境保護建議:

1.  ** PM2.5 的控制**:建議在空間內使用空心的濾網或空心的過濾系統來控制PM2.5濃度。
2.  **二氧化碳的降低**:建議改善交通機動車和其他排放污染物的源頭,以減少空氣中二氧化碳的含量。
3.  **溫度控制**:建議在高溫天氣時,保持空調或使用冷敷來降低身體溫度。
4.  **濕度的處理**:建議在濕潤天氣時,保持乾燥的環境,避免感染性疾病。

*以上分析結果基於一般原則,由於每個地方都有不同的空氣污染標準,我們建議對各地都進行具體評估和應用。

如果您需要進一步評估或提供更多資訊,我們可以一起研究!

2024年12月14日 星期六

Ollama的代理功能(Agent)

範例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from phi.agent import Agent
from phi.model.ollama import Ollama
from phi.tools.duckduckgo import DuckDuckGo

web_agent = Agent(
    name="Web Agent",
    model=Ollama(id="llama3.2"),
    tools=[DuckDuckGo()],
    instructions=["Always include sources"],
    show_tool_calls=True,
    markdown=True,
)
web_agent.print_response("告訴我有關於Ollama?", stream=True)

第1次執行結果:
┌─ Message ───────────────────────────────────────────────────────────────────┐
│                                                                             │
│ 告訴我有關於Ollama?                                                         │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
┌─ Response (13.9s) ──────────────────────────────────────────────────────────┐
│                                                                             │
│                                                                             │
│  • Running: duckduckgo_news(max_results=5, query=ollama)                    │
│                                                                             │
│ Ollama 是一個由 Meta 開發的開源 Language                                    │
│ Model(LLM),其目的是提供更合理的對話和語言處理能力。與其他 OPEN Llama     │
│ 模型相比,Ollama                                                            │
│ 具有更強大的對話能力、更好的理解能力以及能夠更好地处理多種语言風格和風俗。  │
│                                                                             │
│ 2024 年 10 月 23 日,Ollama 的開發者宣布了它們的新功能,使得 Ollama         │
│ 可以在電腦上運行,不需要 internet 連線。這是 Ollama                         │
│ 達到新的里程碑,讓它更容易被使用和分享給更多人。                            │
│                                                                             │
│ 目前,Ollama 仍然是在開發中,但是它已经展示出了非常出色的表現。             │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
第2次執行結果:
┌─ Message ───────────────────────────────────────────────────────────────────┐
│                                                                             │
│ 告訴我有關於Ollama?                                                         │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
┌─ Response (17.4s) ──────────────────────────────────────────────────────────┐
│                                                                             │
│                                                                             │
│  • Running: duckduckgo_search(query=Ollama)                                 │
│                                                                             │
│ OLLAMA(Ollama)是一個開源的框架,用于建構和執行大型自然語言模型(Large     │
│ Language                                                                    │
│ Models,LLMs)。它提供了一種簡單的API,可以用來創造、執行和管理模型,也包含 │
│ 了一些預先啟動的模型,可用於多種應用程式。                                  │
│                                                                             │
│ OLLAMA可以用於以下功能:                                                    │
│                                                                             │
│  1 建構模型:使用Ollama的API可以建構新的模型。                              │
│  2 執行模型:使用Ollama的CLI工具可以執行已經建立好的模型。                  │
│  3 管理模型:Ollama也可以用來管理和 track 模型。                            │
│                                                                             │
│ OLLAMA還包括了一些預先啟動的模型,可用於多種應用程式,如:                   │
│                                                                             │
│  1 錯誤反饋:使用錯誤反饋模型來改善模型的表現。                             │
│  2 文本展開:使用文本展開模型來生成有用的內容。                             │
│  3 記事提取:使用記事提取模型來提取特定的信息。                             │
│                                                                             │
│ 對於研究人員、資料科學家和技術使用者,OLLAMA是一種很好的工具,可以讓他們更  │
│ flexibly 和有效地建構和執行大型自然語言模型。                               │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

Ollama的工具(Tools)使用

Ollama Python函式庫:https://github.com/ollama/ollama-python

範例:加法和減法

 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
from ollama import chat
from ollama import ChatResponse


def add_two_numbers(a: int, b: int) -> int:
  """
  Add two numbers

  Args:
    a (int): The first number
    b (int): The second number

  Returns:
    int: The sum of the two numbers
  """
  return int(a) + int(b)


def subtract_two_numbers(a: int, b: int) -> int:
  """
  Subtract two numbers
  """
  return int(a) - int(b)


# Tools can still be manually defined and passed into chat
subtract_two_numbers_tool = {
  'type': 'function',
  'function': {
    'name': 'subtract_two_numbers',
    'description': 'Subtract two numbers',
    'parameters': {
      'type': 'object',
      'required': ['a', 'b'],
      'properties': {
        'a': {'type': 'integer', 'description': 'The first number'},
        'b': {'type': 'integer', 'description': 'The second number'},
      },
    },
  },
}

messages = [{'role': 'user', 'content': '請問4扣3為?'}]
print('Prompt:', messages[0]['content'])

available_functions = {
  'add_two_numbers': add_two_numbers,
  'subtract_two_numbers': subtract_two_numbers,
}

response: ChatResponse = chat(
  'llama3.2',
  messages=messages,
  tools=[add_two_numbers, subtract_two_numbers_tool],
)

if response.message.tool_calls:
  # There may be multiple tool calls in the response
  for tool in response.message.tool_calls:
    # Ensure the function is available, and then call it
    if function_to_call := available_functions.get(tool.function.name):
      print('Calling function:', tool.function.name)
      print('Arguments:', tool.function.arguments)
      output = function_to_call(**tool.function.arguments)
      print('Function output:', output)
    else:
      print('Function', tool.function.name, 'not found')

# Only needed to chat with the model using the tool call results
if response.message.tool_calls:
  # Add the function response to messages for the model to use
  messages.append(response.message)
  messages.append({'role': 'tool', 'content': str(output), 'name': tool.function.name})

  # Get final response from model with function outputs
  final_response = chat('llama3.2', messages=messages)
  print('Final response:', final_response.message.content)

else:
  print('No tool calls returned from model')

第1次執行結果:
Prompt: 請問4扣3為?
Calling function: subtract_two_numbers
Arguments: {'a': '4', 'b': '3'}
Function output: 1
Final response: 答案是 1

第2次執行結果:
Prompt: 請問4扣3為?
Calling function: subtract_two_numbers
Arguments: {'a': '4', 'b': '3'}
Function output: 1
Final response: 4 - 3 = 1