当前位置:   article > 正文

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

langchain 智谱

使用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
  • 1
  • 2
  • 3

检查版本:

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

导入包和调用:

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)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

返回例子:

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}
  • 1
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/805075
推荐阅读
相关标签
  

闽ICP备14008679号