-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathdeferred_chat.py
More file actions
63 lines (48 loc) · 1.83 KB
/
deferred_chat.py
File metadata and controls
63 lines (48 loc) · 1.83 KB
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
from datetime import timedelta
from typing import Sequence
from absl import app, flags
from xai_sdk import Client
from xai_sdk.chat import user
TIMEOUT = flags.DEFINE_integer("timeout", 5, "Timeout in minutes for the deferred chat request.")
INTERVAL = flags.DEFINE_integer("interval", 100, "Interval in milliseconds for the deferred chat request.")
N = flags.DEFINE_integer("n", 1, "Number of responses to generate.")
# see https://docs.x.ai/docs/guides/deferred-chat-completions#deferred-chat-completions
def deferred_chat(client: Client):
"""Sample a response from a model using polling."""
chat = client.chat.create(model="grok-3")
chat.append(user("Hello"))
try:
response = chat.defer(timeout=timedelta(minutes=TIMEOUT.value), interval=timedelta(milliseconds=INTERVAL.value))
print(response.content)
except RuntimeError as e:
# request expired
print(e)
except ValueError as e:
# unknown deferred status
print(e)
def batch_deferred_chat(client: Client):
"""Sample multiple responses from a model using polling."""
chat = client.chat.create(model="grok-3")
chat.append(user("Hello"))
try:
responses = chat.defer_batch(
n=N.value, timeout=timedelta(minutes=TIMEOUT.value), interval=timedelta(milliseconds=INTERVAL.value)
)
for response in responses:
print(response.content)
except RuntimeError as e:
# request expired
print(e)
except ValueError as e:
# unknown deferred status
print(e)
def main(argv: Sequence[str]) -> None:
if len(argv) > 1:
raise app.UsageError("Unexpected command line arguments.")
client = Client()
if N.value > 1:
batch_deferred_chat(client)
else:
deferred_chat(client)
if __name__ == "__main__":
app.run(main)