File size: 1,193 Bytes
0319a9a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
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')
|