Skip to main content
Open In ColabOpen on GitHub

智谱AI

本笔记本展示了如何在LangChain中使用 ZHIPU AI API,通过 langchain.chat_models.ChatZhipuAI。

GLM-4 is a multi-lingual large language model aligned with human intent, featuring capabilities in Q&A, multi-turn dialogue, and code generation. The overall performance of the new generation base model GLM-4 has been significantly improved compared to the previous generation, supporting longer contexts; Stronger multimodality; Support faster inference speed, more concurrency, greatly reducing inference costs; Meanwhile, GLM-4 enhances the capabilities of intelligent agents.

入门指南

安装

首先,确保您的 Python 环境中已安装 zhipuai 包。运行以下命令:

#!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"

初始化智谱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?"})