hhhwmws's picture
Upload 19 files
0319a9a verified
raw
history blame
1.19 kB
from zhipuai import ZhipuAI
import os
class ZhipuClient:
def __init__(self, api_key_file_path = None):
if api_key_file_path is None:
cands = ['./datas/zhipu_key.txt', '../datas/zhipu_key.txt']
flag = False
for cand in cands:
if os.path.exists(cand):
api_key_file_path = cand
flag = True
break
if not flag:
raise ValueError("No valid api key file found.")
self.api_key = self._load_access_token(api_key_file_path)
self.client = ZhipuAI(api_key=self.api_key)
def _load_access_token(self, file_path):
with open(file_path, 'r') as file:
return file.read().strip()
def prompt2response(self, prompt):
response = self.client.chat.completions.create(
model="glm-4", # 填写需要调用的模型名称
messages=[
{"role": "user", "content": prompt}
],
)
return response.choices[0].message.content
# Usage:
# zhipu_client = ZhipuClient('../datas/zhipu_key.txt')
# response = zhipu_client.prompt2response('Your prompt here')