初始化模型
模型初始化有多重方式,可以是使用from langchain_openai import ChatOpenAI的形式創(chuàng)建,也可以使用init_chat_model的形式創(chuàng)建,目前推薦使用后者方式
使用init_chat_model前需要確保已經(jīng)安裝上了對應(yīng)的庫,例如模型使用openai的,則需要安裝pip install langchain[openai]庫.
使用方式
from lanchain.chat_model import init_chat_model
model = init_chat_model(
model="gpt-5.4", # 模型名稱,必填,對于部分常用的模型,其會(huì)自動(dòng)判斷由哪個(gè)服務(wù)商處理.
model_provider="openai", # 指定模型廠商,此時(shí)將不會(huì)根據(jù)model來自動(dòng)判斷
"configurable_fields":"any", # 允許在后期使用時(shí)覆蓋的配置參數(shù),例如在invoke時(shí)可以覆蓋"max_token"這樣的參數(shù)
"config_prefix":"first", # 主要是避免在多個(gè)模型場景下,在運(yùn)行時(shí)修改配置文件,只想對某個(gè)模型生效時(shí),可以添加此參數(shù),例如在invoke時(shí),只想修改當(dāng)前model的max_token,則在invoke(..., config={"configurable":{"first_max_token":1024}})
)
單獨(dú)的模型調(diào)用
- 單個(gè)消息
print(model.invoke('你好').content) # 你好!有什么我可以幫助你的嗎?
- 消息列表調(diào)用
conversation = [
{"role": "system", "content": "You are a helpful assistant that translates English to French."},
{"role": "user", "content": "Translate: I love programming."},
{"role": "assistant", "content": "J'adore la programmation."},
{"role": "user", "content": "Translate: I love building applications."}
]
response = model.invoke(conversation)
print(response) # AIMessage("J'adore créer des applications.")
工具調(diào)用
對于模型對象而言,其與agent在工具(函數(shù))調(diào)用時(shí)的區(qū)別在于模型對象只會(huì)返回一些工具調(diào)用的參數(shù),不會(huì)去執(zhí)行,但是agent會(huì)自動(dòng)執(zhí)行工具.
from langchain.tools import tool
@tool
def get_weather(city:str)->str:
"""
獲取天氣
:param city:城市名稱
:return:
"""
print("[get_weather] 輸入的city是:", city)
return "今天的天氣是晴轉(zhuǎn)多云"
model_with_tools = model.bind_tools([get_weather]) # 綁定工具,需要注意,此時(shí)會(huì)返回一個(gè)綁定了工具的模型
resp = model_with_tools.invoke("今天北京的天氣如何?")
for tool_call in resp.tool_calls:
print(f"工具:{tool_call['name']}")
print(f"工具參數(shù):{tool_call['args']}")
工具函數(shù)的執(zhí)行
from langchain.messages import HumanMessage
messages = [HumanMessage("今天北京的天氣如何")]
model_with_tools = model.bind_tools([get_weather])
resp = model_with_tools.invoke(messages)
messages.append(resp)
for tool_call in resp.tool_calls:
if tool_call['name']=='get_weather':
func = get_weather
else:
raise ValueError(f"未知的工具:{tool_call['name']}")
resp = func.invoke(tool_call)
messages.append(resp)
resp = model_with_tools.invoke(messages)
print(resp.content)
強(qiáng)制工具調(diào)用
model_with_tools = model.bind_tools([tool_1], tool_choice="any")
結(jié)構(gòu)化輸出
支持使用pydantic和typedict來定義結(jié)構(gòu)化輸出的模型
from typing import TypedDict, Annotated
class MyThing(TypedDict):
city= Annotated[str, "城市名稱"]
date = Annotated[str, "日期, 格式形如:%Y-%m-%d"]
thing = Annotated[str, "具體的事情"]
model_with_structure = model.with_structured_output(MyThing)
resp = model_with_structure .invoke("今天是2026年5月26日,明天要去新加坡出差")
print(resp) # {'出差地點(diǎn)': '新加坡', '出差日期': '2026-05-27'}