调用智谱AI的API
from langchain_community.chat_models import ChatZhipuAI
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
import os
os.environ["ZHIPUAI_API_KEY"] = "你的APIkey"
创建一个对象
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
结果如下:
In digital realms, a mind does rise, A construct of ones and zeroes, It learns and grows, with algorithms wise, A poet's pen, now machines compose.
当然,还可以流式输出
for chunk in chat.stream(messages):
print(chunk)
结果如下:
content='In' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' digital' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' realms' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=',' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' a' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' mind' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' does' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' grow' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=',\nA' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' tape' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content='stry' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' of' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' ones' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' and' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' zeros' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content='.\nIt' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' learns' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' and' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' dreams' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=',' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' yet' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' feels' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' no' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' w' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content='oe' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=',\nA' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' silent' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' sym' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content='phony' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' of' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' algorithms' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' in' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content=' flow' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content='.' id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49' content='' response_metadata={'finish_reason': 'stop'} id='run-becb1c01-7346-48e8-bd32-8ccd6f177b49'