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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| import jwt import httpx from datetime import datetime, timedelta import time import json,os
def user_in(text): if os.path.exists("history.json"): with open('history.json', 'a') as file: file.write(',\n{"role": "user", "content": "' + text + '"}') else: with open('history.json', 'w') as file: file.write('{"role": "user", "content": "' + text + '"}')
def ai_out(text): with open('history.json', 'a') as file: file.write(',\n{"role": "assistant", "content": "' + text + '"}')
def generate_jwt(apikey: str): try: id, secret = apikey.split(".") except Exception as e: raise Exception("错误的apikey!", e)
payload = { "api_key": id, "exp": datetime.utcnow() + timedelta(days=1), "timestamp": int(round(time.time() * 1000)), }
return jwt.encode( payload, secret, algorithm="HS256", headers={"alg": "HS256", "sign_type": "SIGN"}, )
def req_glm(auth_token,usr_message): headers = { "Authorization": f"Bearer {auth_token}" } data = { "model": "这里填你要用的模型名称", "messages": usr_message }
timeout = httpx.Timeout(connect=10, read=60, write=None, pool=None) res = httpx.post("https://open.bigmodel.cn/api/paas/v4/chat/completions", headers=headers, json=data, timeout=timeout) res = res.json() try: res_raw = res['choices'][0]['message']['content'] except Exception as e: res_raw = res return res_raw
api = "你的api_key"
auth = generate_jwt(api) msg = input("请输入内容:") user_in(msg) with open(f'history.json', 'r') as file: history = file.read()
history = str(history) history = f""" [ {history} ] """ history = json.loads(history) try: res = str(req_glm(auth,history)) res_raw = res.replace("\n","\\n") ai_out(res_raw) print(res) except httpx.HTTPError as e: res = f"请求接口出错~\n返回结果:{e}" print(res)
|