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 = os.getenv("ZHIPU_4_API") 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')