2025年9月28日 星期日

LangChain 學習筆記 : 串接 LLM 模型 (二)

晚上繼續測試 LangChain, 本篇旨在測試串接谷歌 Gemini 的方法.

本系列之前的文章參考 :


關於谷歌原生的 Gemini 串接套件 google-generativeai 用法參考 :



5. 安裝 langchain-google-genai 套件 :    

LangChain 用來串接 Gemini 的套件為 langchain-google-genai, 與前一篇串接 GPT 模型一樣, langchain-google-genai 套件只是封裝了透過谷歌原生套件 google-generativeai 串接 Gemini 模型的介面而已, 它無法單獨與 Gemini 聊天, 必須搭配 google-generativeai 當底層介面才行. 

不過, 由於 langchain-google-genai 與 google-generativeai 這兩個套件在安裝時會與相依套件 google-ai-generativelanguage 有版本衝突問題 (安裝時會出現 ERROR 訊息), 我向 ChatGPT 尋求解決方案, 經測試發現只要指定特定版本即可順利安裝, 若已安裝此兩套件出現錯誤, 請先用下列指令解除安裝 :

pip uninstall -y google-ai-generativelanguage google-generativeai langchain-google-genai  

D:\python\test>pip uninstall -y google-ai-generativelanguage google-generativeai langchain-google-genai
Found existing installation: google-ai-generativelanguage 0.7.0
Uninstalling google-ai-generativelanguage-0.7.0:
  Successfully uninstalled google-ai-generativelanguage-0.7.0
Found existing installation: google-generativeai 0.8.5
Uninstalling google-generativeai-0.8.5:
  Successfully uninstalled google-generativeai-0.8.5
Found existing installation: langchain-google-genai 2.1.12
Uninstalling langchain-google-genai-2.1.12:
  Successfully uninstalled langchain-google-genai-2.1.12

然後指定安裝 0.6.15 版的 google-ai-generativelanguage : 

pip install google-ai-generativelanguage==0.6.15    

D:\python\test>pip install google-ai-generativelanguage==0.6.15   
Collecting google-ai-generativelanguage==0.6.15
  Using cached google_ai_generativelanguage-0.6.15-py3-none-any.whl.metadata (5.7 kB)
Requirement already satisfied: google-api-core!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1->google-ai-generativelanguage==0.6.15) (2.19.2)
Requirement already satisfied: google-auth!=2.24.0,!=2.25.0,<3.0.0dev,>=2.14.1 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from google-ai-generativelanguage==0.6.15) (2.22.0)
Requirement already satisfied: proto-plus<2.0.0dev,>=1.22.3 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from google-ai-generativelanguage==0.6.15) (1.24.0)
Requirement already satisfied: protobuf!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<6.0.0dev,>=3.20.2 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from google-ai-generativelanguage==0.6.15) (5.28.1)
Requirement already satisfied: googleapis-common-protos<2.0.dev0,>=1.56.2 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from google-api-core!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1->google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1->google-ai-generativelanguage==0.6.15) (1.65.0)
Requirement already satisfied: requests<3.0.0.dev0,>=2.18.0 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from google-api-core!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1->google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1->google-ai-generativelanguage==0.6.15) (2.31.0)
Requirement already satisfied: grpcio<2.0dev,>=1.33.2 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1->google-ai-generativelanguage==0.6.15) (1.66.1)
Requirement already satisfied: grpcio-status<2.0.dev0,>=1.33.2 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1->google-ai-generativelanguage==0.6.15) (1.66.1)
Requirement already satisfied: cachetools<6.0,>=2.0.0 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from google-auth!=2.24.0,!=2.25.0,<3.0.0dev,>=2.14.1->google-ai-generativelanguage==0.6.15) (5.3.1)
Requirement already satisfied: pyasn1-modules>=0.2.1 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from google-auth!=2.24.0,!=2.25.0,<3.0.0dev,>=2.14.1->google-ai-generativelanguage==0.6.15) (0.3.0)
Requirement already satisfied: rsa<5,>=3.1.4 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from google-auth!=2.24.0,!=2.25.0,<3.0.0dev,>=2.14.1->google-ai-generativelanguage==0.6.15) (4.9)
Requirement already satisfied: six>=1.9.0 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from google-auth!=2.24.0,!=2.25.0,<3.0.0dev,>=2.14.1->google-ai-generativelanguage==0.6.15) (1.17.0)
Requirement already satisfied: urllib3<2.0 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from google-auth!=2.24.0,!=2.25.0,<3.0.0dev,>=2.14.1->google-ai-generativelanguage==0.6.15) (1.26.19)
Requirement already satisfied: charset-normalizer<4,>=2 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from requests<3.0.0.dev0,>=2.18.0->google-api-core!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1->google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1->google-ai-generativelanguage==0.6.15) (3.2.0)
Requirement already satisfied: idna<4,>=2.5 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from requests<3.0.0.dev0,>=2.18.0->google-api-core!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1->google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1->google-ai-generativelanguage==0.6.15) (3.4)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from requests<3.0.0.dev0,>=2.18.0->google-api-core!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1->google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1->google-ai-generativelanguage==0.6.15) (2025.6.15)
Requirement already satisfied: pyasn1>=0.1.3 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from rsa<5,>=3.1.4->google-auth!=2.24.0,!=2.25.0,<3.0.0dev,>=2.14.1->google-ai-generativelanguage==0.6.15) (0.5.0)
Using cached google_ai_generativelanguage-0.6.15-py3-none-any.whl (1.3 MB)
Installing collected packages: google-ai-generativelanguage
Successfully installed google-ai-generativelanguage-0.6.15

其次安裝 0.8.5 版的 google-generativeai : 

pip install google-generativeai==0.8.5 --no-deps

D:\python\test>pip install google-generativeai==0.8.5 --no-deps  
Collecting google-generativeai==0.8.5
  Using cached google_generativeai-0.8.5-py3-none-any.whl.metadata (3.9 kB)
Using cached google_generativeai-0.8.5-py3-none-any.whl (155 kB)
Installing collected packages: google-generativeai
Successfully installed google-generativeai-0.8.5

最後安裝 2.1.12 版的 langchain-google-genai : 

pip install langchain-google-genai==2.1.12 --no-deps

D:\python\test>pip install langchain-google-genai==2.1.12 --no-deps   
Collecting langchain-google-genai==2.1.12
  Using cached langchain_google_genai-2.1.12-py3-none-any.whl.metadata (7.1 kB)
Using cached langchain_google_genai-2.1.12-py3-none-any.whl (50 kB)
Installing collected packages: langchain-google-genai
Successfully installed langchain-google-genai-2.1.12


6. 檢視 langchain-google-genai 套件內容 :    

匯入 langchain_google_genai 後用 dir() 檢視其內容 : 

>>> import langchain_google_genai     
>>> dir(langchain_google_genai)   
['AqaInput', 'AqaOutput', 'ChatGoogleGenerativeAI', 'DoesNotExistsException', 'GenAIAqa', 'GoogleGenerativeAI', 'GoogleGenerativeAIEmbeddings', 'GoogleVectorStore', 'HarmBlockThreshold', 'HarmCategory', 'Modality', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_common', '_enums', '_function_utils', '_genai_extension', '_image_utils', 'chat_models', 'embeddings', 'genai_aqa', 'google_vector_store', 'llms']

其中的 ChatGoogleGenerativeAI 類別便是用來串接 Gemini 模型用的, 其建構式 ChatGoogleGenerativeAI() 的參數如下表所示 : 


 參數名稱  說明
model Gemini 模型名稱,例如 "gemini-1.5-pro",對應 API 的 model 參數
temperature 生成隨機性,範圍 0~1,對應 API 的 temperature
max_output_tokens 最大生成 token 數量,對應 API 的 max_output_tokens
top_p nucleus sampling 控制生成多樣性,對應 API 的 top_p
top_k top-k sampling 控制生成多樣性,對應 API 的 top_k
api_key Google API Key,可直接傳入或使用環境變數 GOOGLE_API_KEY
request_timeout 請求超時秒數,對應 SDK 的 timeout / request_timeout
model_kwargs 可傳遞額外參數給 Gemini SDK,例如 stop_sequences、candidate_count 等
verbose 布林值,是否印出 debug 訊息
client 可傳自訂 Gemini SDK client,一般不用


在互動環境測試如下 :

我已將 Gemini API Key 儲存在環境變數檔案 .env 裡面 (名稱為 'GEMINI_API_KEY'), 先用 dotenv 套件讀取出來放在 gemini_api_key 變數中 :

>>> from dotenv import dotenv_values    
config=dotenv_values('.env')     
gemini_api_key=config.get('GEMINI_API_KEY')    

從 langchain_google_genai 套件中匯入 ChatGoogleGenerativeAI 類別 :  

>>> from langchain_google_genai import ChatGoogleGenerativeAI   

然後呼叫 ChatGoogleGenerativeAI() 建構函式並傳入 api_key 與 model 參數來建立 ChatGoogleGenerativeAI 物件 : 

>>> chat_model=ChatGoogleGenerativeAI(api_key=gemini_api_key, model='gemini-2.5-flash')    
>>> type(chat_model)         
<class 'langchain_google_genai.chat_models.ChatGoogleGenerativeAI'>   

注意, 目前可用的 Gemini 模型如下 (之前測試使用的 1.5 版已下架, 無法串接了, 如果 model 指定舊版 1.5 版會得到 404 錯誤) : 


模型名稱 描述 適合場景 穩定性
gemini-2.5-flash 快速、低延遲的輕量模型 聊天、即時回應 穩定
gemini-2.5-pro 先進推理模型,支援長上下文 複雜問題、程式碼生成 穩定
gemini-2.5-flash-lite 更輕量的 Flash 變體 行動裝置、成本敏感應用 穩定
gemini-2.0-flash 舊 2.0 版本,快速但較舊 基本任務 穩定


這樣就可以呼叫 ChatGoogleGenerativeAI 物件的 invoke() 方法並傳入提示詞來起始一個對話 : 

>>> response=chat_model.invoke('你是誰?')     
>>> type(response)     
<class 'langchain_core.messages.ai.AIMessage'>     

檢視 invoke() 傳回的 AIMessage 物件內容 : 

>>> response   
AIMessage(content='我是一个大型语言模型,由 Google 训练。', additional_kwargs={}, response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'model_name': 'gemini-2.5-flash', 'safety_ratings': []}, id='run--9c115a61-fc2d-4c74-a611-a7da5465b65b-0')

可見模型的回應是放在其 content 屬性內 : 

>>> response.content     

'我是一个大型语言模型,由 Google 训练。'

由這兩篇測試可知 LangChain 的好處是對於不同的模型都可以用相同的 API 與模型交談. 

沒有留言 :