1+ import time
2+ from zai import ZaiClient
3+
4+ # Async chat completions example: create task and poll result
5+ # Prerequisite: set ZAI_API_KEY in your environment.
6+
7+
8+ def create_async_task ():
9+ """Create an async chat completion task and return its id."""
10+ client = ZaiClient ()
11+ response = client .chat .asyncCompletions .create (
12+ model = 'glm-4.6' ,
13+ messages = [
14+ {
15+ "role" : "user" ,
16+ "content" : "Please write a short fairy tale about keeping a kind heart that encourages learning and imagination."
17+ }
18+ ]
19+ )
20+ print ("Task created:" , response )
21+ return response .id
22+
23+
24+ def poll_result (task_id , interval_sec : int = 2 , max_attempts : int = 40 ):
25+ """Poll the async task result until it succeeds or fails."""
26+ client = ZaiClient ()
27+ attempt = 0
28+ status = ""
29+ while attempt < max_attempts :
30+ result = client .chat .asyncCompletions .retrieve_completion_result (id = task_id )
31+ print ("Polling result:" , result )
32+ status = getattr (result , "task_status" , "" ) or ""
33+ # Handle different enum cases and capitalizations
34+ if status in ("SUCCESS" , "FAIL" ):
35+ if status in ("SUCCESS" ):
36+ try :
37+ content = result .choices [0 ].message .content
38+ except Exception :
39+ content = None
40+ if content :
41+ print ("Final content:" )
42+ print (content )
43+ else :
44+ print ("Task failed, status:" , status )
45+ break
46+ time .sleep (interval_sec )
47+ attempt += 1
48+ else :
49+ print ("Polling timed out, final status:" , status )
50+
51+
52+ def main ():
53+ """Run the async task creation and polling demo."""
54+ task_id = create_async_task ()
55+ poll_result (task_id )
56+
57+
58+ if __name__ == "__main__" :
59+ main ()
0 commit comments