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)

執行結果: