赞
踩
之前写过一篇怎么调用文心一言api的文章了,一般来说,我不是很愿意做重复的工作,因为比较懒嘛,那为什么又写这篇文章呢?主要是文心一言申请api_key等还不是太方便,开通服务也把人绕的晕,而调用智谱就容易多了。
首先访问智谱AI开放平台 (bigmodel.cn),进行注册或登录:
点击“开发工作台”:
点击“查看Api key”:
于是可看到我们的Api key了:
调用代码如下:
版本1:
- from zhipuai import ZhipuAI
-
- def get_ai_response(prompt_text):
- client = ZhipuAI(api_key="")
- # api_key换成自己的api_key即可
-
- response = client.chat.completions.create(
- model="glm-4",
- messages=[
- {
- "role": "user",
- "content": prompt_text
- }
- ],
- top_p=0.7,
- temperature=0.95,
- max_tokens=1024,
- stream=True,
- )
-
- # 打印用户的提问
- # print(prompt_text)
-
- # 在循环中逐次打印回复内容,并在每条回复后面添加换行符
- for chunk in response:
- for choice in chunk.choices:
- print(choice.delta.content, end="", flush=True) # 移除换行符,使得内容连在一起
- print("\n") # 在所有回复结束后添加一个换行符
-
- def main():
- while True:
- prompt_text = input("请输入您的问题或输入'退出'结束对话:")
- if prompt_text.lower() == "退出":
- break
- get_ai_response(prompt_text)
-
- if __name__ == "__main__":
- main()
版本2:
- import tkinter as tk
- from tkinter import scrolledtext, messagebox
- from threading import Thread
- from zhipuai import ZhipuAI
-
-
- def get_ai_response_in_thread(prompt_text, text_widget):
- try:
- client = ZhipuAI(api_key="")
-
- response = client.chat.completions.create(
- model="glm-4",
- messages=[
- {
- "role": "user",
- "content": prompt_text
- }
- ],
- top_p=0.7,
- temperature=0.95,
- max_tokens=1024,
- stream=True,
- )
-
- # 在GUI中显示响应
- for chunk in response:
- for choice in chunk.choices:
- text_widget.insert(tk.END, choice.delta.content)
- text_widget.see(tk.END) # 滚动到最后
- text_widget.update_idletasks() # 强制更新GUI
-
- except Exception as e:
- messagebox.showerror("Error", str(e))
-
-
- def on_submit():
- prompt_text = input_entry.get()
- if prompt_text.lower() == "退出":
- root.destroy()
- else:
- thread = Thread(target=get_ai_response_in_thread, args=(prompt_text, output_text))
- thread.start()
-
-
- root = tk.Tk()
- root.title("ZhipuAI Chatbot")
-
- input_label = tk.Label(root, text="请输入您的问题或输入'退出'结束对话:")
- input_label.pack(pady=10)
-
- input_entry = tk.Entry(root, width=50)
- input_entry.pack()
-
- submit_button = tk.Button(root, text="提交", command=on_submit)
- submit_button.pack(pady=10)
-
- output_scroll = scrolledtext.ScrolledText(root, height=20, width=50)
- output_text = output_scroll
- output_scroll.pack(pady=10, expand=True, fill="both")
-
- root.mainloop()
因为本人账号欠费,暂时无法演示。
这次就到这了,下次再见,与大家共勉。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。