赞
踩
环境: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 ChatOpenAI from langchain_openai import ChatOpenAI import jwt import time from langchain_core.messages import AIMessage, HumanMessage, SystemMessage zhipuai_api_key="33b1667298dfc3e27b5487a4f2428c8c.WaSYvdnaLdE1e92a" def generate_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}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。