深圳易百讯网站建设公司,旅游产品推广方案,wordpress语言中文版,朝阳区seopython实现在线 ChatGLM调用
1. 申请调用权限#xff1a;
收钱进入到质谱AI开放平台#xff0c;点击“开始使用”或者“开发者工具台”进行注册#xff1a; 对于需要使用 API key 来搭建应用的话#xff0c;需要点击右边红框中的查看 API key#xff0c;就会进入到我们…python实现在线 ChatGLM调用
1. 申请调用权限
收钱进入到质谱AI开放平台点击“开始使用”或者“开发者工具台”进行注册 对于需要使用 API key 来搭建应用的话需要点击右边红框中的查看 API key就会进入到我们个人的 API 管理列表中。 在该界面我们就可以看到我们获取到的 API 所对应的应用名字和 API key 了。 我们可以点击 添加新的 API key 并输入对应的名字即可生成新的 API key。
2. 调用智谱 AI API
智谱 AI 提供了 SDK 和原生 HTTP 来实现模型 API 的调用建议使用 SDK 进行调用以获得更好的编程体验。
运行环境Python3.7使用 pip 安装 zhipuai 软件包及其依赖
pip install zhipuai创建client
from zhipuai import ZhipuAIclient ZhipuAI(api_key, # 填写您的 APIKey
) 同步调用
from zhipuai import ZhipuAI
client ZhipuAI(api_key) # 填写您自己的APIKey
response client.chat.completions.create(model, # 填写需要调用的模型名称messages[{role: user, content: 你好},{role: assistant, content: 我是人工智能助手},{role: user, content: 你叫什么名字},{role: assistant, content: 我叫chatGLM},{role: user, content: 你都可以做些什么事}],
)
print(response.choices[0].message)SSE 调用
from zhipuai import ZhipuAI
client ZhipuAI(api_key) # 请填写您自己的APIKey
response client.chat.completions.create(model, # 填写需要调用的模型名称messages[{role: system, content: 你是一个人工智能助手你叫叫chatGLM},{role: user, content: 你好你叫什么名字},],streamTrue,
)
for chunk in response:print(chunk.choices[0].delta)HTTP方式调用
import json# HTTP方式调用智普清言API
import requests
from zhipuai.core._jwt_token import generate_tokenclass ZhipuAILLM:def __init__(self, api_key, modelglm-4):self.api_key api_keyself.model modelself.base_url https://open.bigmodel.cn/api/paas/v4/chat/completionsdef __call__(self, prompt):payload {model: self.model,messages: [{role: user,content: prompt}],}token generate_token(self.api_key)headers {Authorization: fBearer {token},Content-Type: application/json,}response requests.post(f{self.base_url}, jsonpayload, headersheaders)if response.status_code 200:byte_string response.contentstring byte_string.decode(utf-8)data json.loads(string)print(json.dumps(data))return data[choices][0][message][content]else:raise Exception(fError calling Zhipu AI: {response.text})api_key # 填写您自己的APIKey
llm ZhipuAILLM(api_key)response llm(What is the capital of France?)
print(response)langchain方式调用
from langchain_openai import ChatOpenAI
import jwt
import time
from langchain_core.messages import AIMessage, HumanMessage, SystemMessagezhipuai_api_key # 填写您自己的APIKeyclass ChatZhiPuAI(ChatOpenAI):def __init__(self, model_name, api_key):super().__init__(model_namemodel_name, openai_api_keygenerate_token(api_key, 10), openai_api_basehttps://open.bigmodel.cn/api/paas/v4)def invoke(self, question):messages [HumanMessage(contentquestion),]return super().invoke(messages)question input(请输入问题)
chat ChatZhiPuAI(model_nameglm-4, api_keyzhipuai_api_key)response chat.invoke(question)
print(response)参考链接 https://github.com/MetaGLM/zhipuai-sdk-python-v4 http://t.csdnimg.cn/4HnKC https://datawhalechina.github.io/llm-universe/#/C2/5.%20%E8%B0%83%E7%94%A8%E6%99%BA%E8%B0%B1%20AI(ChatGLM)