|
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 |
|
|
|
|
|
|
|
|
|
|