一、调用智谱 AI API
1、获取api_key
智谱AI开放平台网址:
https://open.bigmodel.cn/overview
2、安装库pip install zhipuai
3、执行一下代码,调用质谱api进行问答
from zhipuai import ZhipuAIclient = ZhipuAI(api_key="xxxxx") # 填写您自己的APIKey
while True:prompt = input("user:")response = client.chat.completions.create(model="glm-4", # 填写需要调用的模型名称messages=[{"role": "user", "content": prompt}],)answer = response.choices[0].message.contentprint("ZhipuAI:", answer)
二、使用Gradio搭建聊天UI
import gradio as gr
import random
import timefrom langchain_community.chat_models import ChatZhipuAI
from zhipuai import ZhipuAIimport configurellm = configure.chat
client = ZhipuAI(api_key="xxx") # 填写您自己的APIKeywith gr.Blocks() as demo:chatbot = gr.Chatbot()msg = gr.Textbox()clear = gr.Button("清除")def respond(message, chat_history):response = client.chat.completions.create(model="glm-4", # 填写需要调用的模型名称messages=[{"role": "user", "content": message}],)chat_history.append((message, response.choices[0].message.content))return "", chat_historymsg.submit(respond, [msg, chatbot], [msg, chatbot])clear.click(lambda: None, None, chatbot, queue=False)demo.launch()
参考:
- https://blog.csdn.net/sinat_26917383/article/details/133950480
- https://zhuanlan.zhihu.com/p/681207328
- https://blog.csdn.net/Alexa_/article/details/134485161
- https://blog.csdn.net/u013558123/article/details/136118024
- https://zhuanlan.zhihu.com/p/678228971