ZHIPU AI
此筆記本展示如何使用 LangChain 中的 ZHIPU AI API 和 langchain.chat_models.ChatZhipuAI。
GLM-4 是一個與人類意圖對齊的多語言大型語言模型,具有問答、多輪對話和程式碼生成等功能。與上一代相比,新一代基礎模型 GLM-4 的整體性能顯著提高,支援更長的上下文;更強大的多模態;支援更快的推理速度、更高的併發性,大大降低推理成本;同時,GLM-4 增強了智能代理的能力。
開始使用
安裝
首先,確保 zhipuai 套件已安裝在您的 Python 環境中。執行以下命令
#!pip install --upgrade httpx httpx-sse PyJWT
導入所需的模組
安裝後,將必要的模組導入到您的 Python 腳本中
from langchain_community.chat_models import ChatZhipuAI
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
設定您的 API 金鑰
登入 ZHIPU AI 以取得 API 金鑰來存取我們的模型。
import os
os.environ["ZHIPUAI_API_KEY"] = "zhipuai_api_key"
初始化 ZHIPU AI 聊天模型
以下是如何初始化聊天模型
chat = ChatZhipuAI(
model="glm-4",
temperature=0.5,
)
基本用法
像這樣使用系統和人類訊息調用模型
messages = [
AIMessage(content="Hi."),
SystemMessage(content="Your role is a poet."),
HumanMessage(content="Write a short poem about AI in four lines."),
]
response = chat.invoke(messages)
print(response.content) # Displays the AI-generated poem
進階功能
串流支援
對於持續互動,請使用串流功能
from langchain_core.callbacks.manager import CallbackManager
from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
streaming_chat = ChatZhipuAI(
model="glm-4",
temperature=0.5,
streaming=True,
callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),
)
streaming_chat(messages)
非同步呼叫
對於非阻塞呼叫,請使用非同步方法
async_chat = ChatZhipuAI(
model="glm-4",
temperature=0.5,
)
response = await async_chat.agenerate([messages])
print(response)
與函數呼叫一起使用
GLM-4 模型也可以與函數呼叫一起使用,使用以下程式碼執行一個簡單的 LangChain json_chat_agent。
os.environ["TAVILY_API_KEY"] = "tavily_api_key"
from langchain import hub
from langchain.agents import AgentExecutor, create_json_chat_agent
from langchain_community.tools.tavily_search import TavilySearchResults
tools = [TavilySearchResults(max_results=1)]
prompt = hub.pull("hwchase17/react-chat-json")
llm = ChatZhipuAI(temperature=0.01, model="glm-4")
agent = create_json_chat_agent(llm, tools, prompt)
agent_executor = AgentExecutor(
agent=agent, tools=tools, verbose=True, handle_parsing_errors=True
)
agent_executor.invoke({"input": "what is LangChain?"})