0


使用LangChain调用智谱AI的glm-4对话

使用LangChain调用智谱AI的glm-4对话:

环境:JupyterLab
Python:3.12.2

下载包:

!pip install langchain -i https://mirrors.aliyun.com/pypi/simple/
!pip install zhipuai -i https://mirrors.aliyun.com/pypi/simple/
!pip install langchain_openai -i https://mirrors.ustc.edu.cn/pypi/web/simple

检查版本:

import sys
print("Python version:", sys.version_info.major,".", sys.version_info.minor,".", sys.version_info.micro)

导入包和调用:

from langchain.chains import LLMChain
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.chat_models import ChatZhipuAI
# from langchain_community.chat_models import ChatOpenAIfrom langchain_openai import ChatOpenAI
import jwt
import time
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

zhipuai_api_key="33b1667298dfc3e27b5487a4f2428c8c.WaSYvdnaLdE1e92a"defgenerate_token(apikey:str, exp_seconds:int):id, secret = apikey.split(".")
        payload ={"api_key":id,"exp":int(round(time.time()*1000))+ exp_seconds *1000,"timestamp":int(round(time.time()*1000)),}return jwt.encode(
            payload,
            secret,
            algorithm="HS256",
            headers={"alg":"HS256","sign_type":"SIGN"},)
    
chat40 = ChatOpenAI(
        model_name="glm-4",
        openai_api_base="https://open.bigmodel.cn/api/paas/v4",
        openai_api_key=generate_token(zhipuai_api_key,10),
        streaming=False,
        verbose=True)
messages =[
    HumanMessage(content="写一篇现代7言诗"),]

response = chat40.invoke(messages)print(response)

返回例子:

content='都市繁华皆入眼,\n钢铁森林披新衣。\n车水马龙如流彩,\n霓虹闪烁夜未央。\n\n信息时代传万里,\n智能助手解千愁。\n心中仍有山水意,\n何处不是桃花源?' response_metadata={'token_usage':{'completion_tokens':50,'prompt_tokens':11,'total_tokens':61},'model_name':'glm-4','system_fingerprint':None,'finish_reason':'stop','logprobs':None}

本文转载自: https://blog.csdn.net/wcuuchina/article/details/137233515
版权归原作者 wcuuchina 所有, 如有侵权,请联系我们删除。

“使用LangChain调用智谱AI的glm-4对话”的评论:

还没有评论