1
+ import json
2
+ import sys
3
+ from http import HTTPStatus
4
+
5
+ from dashscope import Assistants , Messages , Runs , Threads
6
+
7
+
8
+ def create_assistant ():
9
+ # create assistant with information
10
+ assistant = Assistants .create (
11
+ model = 'qwen-max' , # 此处以qwen-max为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
12
+ name = 'smart helper' ,
13
+ description = 'A tool helper.' ,
14
+ instructions = 'You are a helpful assistant.' , # noqa E501
15
+ )
16
+
17
+ return assistant
18
+
19
+
20
+ def verify_status_code (res ):
21
+ if res .status_code != HTTPStatus .OK :
22
+ print ('Failed: ' )
23
+ print (res )
24
+ sys .exit (res .status_code )
25
+
26
+
27
+ if __name__ == '__main__' :
28
+ # create assistant
29
+ assistant = create_assistant ()
30
+ print ('create assistant:\n %s\n ' % assistant )
31
+ verify_status_code (assistant )
32
+
33
+ # create thread.
34
+ thread = Threads .create (
35
+ messages = [{
36
+ 'role' : 'user' ,
37
+ 'content' : '如何做出美味的牛肉炖土豆?'
38
+ }])
39
+ print ('create thread:\n %s\n ' % thread )
40
+ verify_status_code (thread )
41
+
42
+ # create run
43
+ run = Runs .create (thread .id , assistant_id = assistant .id )
44
+
45
+ print (run )
46
+ print ('create run:\n %s\n ' % run )
47
+
48
+ verify_status_code (run )
49
+ # wait for run completed or requires_action
50
+ run_status = Runs .wait (run .id , thread_id = thread .id )
51
+ print (run_status )
52
+ print ('run status:\n %s\n ' % run_status )
53
+ if run_status .usage :
54
+ print ('run usage: total=%s, input=%s, output=%s, prompt=%s, completion=%s\n ' %
55
+ (run_status .usage .get ('total_tokens' ), run_status .usage .get ('input_tokens' ), run_status .usage .get ('output_tokens' ),
56
+ run_status .usage .get ('prompt_tokens' ), run_status .usage .get ('completion_tokens' )))
57
+ # print('run usage: total=%d, input=%d, output=%d, prompt=%d, completion=%d\n' %
58
+ # (run_status.usage.total_tokens, run_status.usage.input_tokens, run_status.usage.output_tokens,
59
+ # run_status.usage.prompt_tokens, run_status.usage.completion_tokens))
60
+
61
+ # get the thread messages.
62
+ msgs = Messages .list (thread .id )
63
+ print (msgs )
64
+ print ('thread messages:\n %s\n ' % msgs )
65
+ print (json .dumps (msgs , ensure_ascii = False , default = lambda o : o .__dict__ , sort_keys = True , indent = 4 ))
0 commit comments