赞
踩
1、获取api_key
智谱AI开放平台网址:
https://open.bigmodel.cn/overview
2、安装库pip install zhipuai
3、执行一下代码,调用质谱api进行问答
from zhipuai import ZhipuAI
client = 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.content
print("ZhipuAI:", answer)
import gradio as gr import random import time from langchain_community.chat_models import ChatZhipuAI from zhipuai import ZhipuAI import configure llm = configure.chat client = ZhipuAI(api_key="xxx") # 填写您自己的APIKey with 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_history msg.submit(respond, [msg, chatbot], [msg, chatbot]) clear.click(lambda: None, None, chatbot, queue=False) demo.launch()
import gradio as gr import time from zhipuai import ZhipuAI from typing import * client = ZhipuAI(api_key="your api key") # 填写您自己的APIKey # https://blog.csdn.net/sinat_26917383/article/details/133950480 # https://open.bigmodel.cn/dev/api#glm-4 # https://www.cnblogs.com/ddsuifeng/p/17989484 with gr.Blocks(title="智小优") as demo: gr.HTML("""<h1 align="center">智小优</h1>""") gr.Markdown("<h1><center>Welcome to my personal AI-OR assistant (powered by zhipu)</center></h1>") chatbot = gr.Chatbot(render=True) msg = gr.Textbox(placeholder="请输入你的问题") with gr.Row(): submit = gr.Button('Submit') clear = gr.Button("Clear") def user(user_message: str, history: List[List]) -> Tuple: """ Args: user_message: 用户输入 history: 历史问答 Returns: """ return "", history + [[user_message, None]] def bot(history: List[List]) -> None: response = client.chat.completions.create( model="glm-4", # 填写需要调用的模型名称 messages=[ {"role": "user", "content": history[-1][0]} ], stream=True ) history[-1][1] = "" for chunk in response: for choice in chunk.choices: # content = choice.delta.content if content := choice.delta.content: history[-1][1] += content time.sleep(0.05) yield history msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then( bot, chatbot, chatbot ) # 触发事件监听 submit.click(user, [msg, chatbot], [msg, chatbot], queue=False).then(bot, chatbot, chatbot) clear.click(lambda: None, None, chatbot, queue=False) if __name__ == '__main__': demo.queue().launch()
参考:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。