-
Notifications
You must be signed in to change notification settings - Fork 0
/
zhipu.py
77 lines (71 loc) · 2.78 KB
/
zhipu.py
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
import asyncio
try:
from .config import zhipu_Config
from .base_chat import aichat
from hoshino import aiorequests
except ImportError:
import sys, os
_current_dir = os.path.dirname(__file__)
if _current_dir not in sys.path:
sys.path.insert(0, _current_dir)
from config import zhipu_Config
from base_chat import aichat
import aiorequests
class Zhipu(aichat):
config: zhipu_Config
def __init__(self):
self.config = zhipu_Config()
self.headers = {
'Authorization': f'Bearer {self.config.api_key}',
'Content-Type': 'application/json'
}
async def asend(self, msg, gid, uid):
url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
self.data = {
'model': self.config.model,
'messages': [
{
'role': 'user',
'content': msg
},
],
'max_tokens': self.config.max_tokens,
'temperature': self.config.temperature,
'top_p': self.config.top_p,
'user_id': str(uid),
}
if self.config.system:
self.data['messages'].insert(0, {'role':'system','content': f'{self.config.system}'})
if not self.config.use_web_search:
self.data['tools']= [{'type':'web_search','web_search':{'enable': False}}]
resp = await aiorequests.post(f'{url}', headers=self.headers, json=self.data)
resp_j = await resp.json()
print(resp_j)
if "error" in resp_j.keys():
# 发生错误
# 智谱的错误信息是汉语,就不画蛇添足了,直接返回。https://open.bigmodel.cn/dev/api#error-code-v3
error_code = resp_j['error']['code']
error_message = resp_j['error']['message']
self.response = f"发生错误:\ncode: {error_code}\n{error_message}"
return resp_j
self.response = resp_j['choices'][0]['message']['content']
self.usage = resp_j['usage']
self.completion_tokens = int(resp_j['usage']['completion_tokens'])
self.prompt_tokens = int(resp_j['usage']['prompt_tokens'])
self.total_tokens = int(resp_j['usage']['total_tokens'])
await self.token_cost_record(gid, uid, self.total_tokens, 'zhipu')
return resp_j
if __name__ == '__main__':
async def task1():
print("Task 1 is running")
zhipu = Zhipu()
await zhipu.asend('介绍一下东海帝王', 112233445566, 1)
print(zhipu.get_response())
print(zhipu.get_usage())
print("Task 1 completed")
async def main():
# tasks = [task1(), task2()]
tasks = [task1()]
await asyncio.gather(*tasks)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())