-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathdeferred_chat.py
More file actions
62 lines (47 loc) · 1.82 KB
/
deferred_chat.py
File metadata and controls
62 lines (47 loc) · 1.82 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
import asyncio
from datetime import timedelta
from typing import Sequence
from absl import app, flags
from xai_sdk import AsyncClient
from xai_sdk.chat import user
TIMEOUT = flags.DEFINE_integer("timeout", 5, "Timeout for the deferred chat request.")
INTERVAL = flags.DEFINE_integer("interval", 2000, "Interval for the deferred chat request.")
# see https://docs.x.ai/docs/guides/deferred-chat-completions#deferred-chat-completions
async def deferred_chat(client: AsyncClient):
"""Sample a response from a model using polling."""
chat = client.chat.create(model="grok-4.20-non-reasoning")
chat.append(user("Hello"))
try:
response = await 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)
async def batch_deferred_chat(client: AsyncClient):
"""Sample multiple responses from a model using polling."""
chat = client.chat.create(model="grok-4.20-non-reasoning")
chat.append(user("Hello"))
try:
responses = await chat.defer_batch(
n=10, 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)
async def main(argv: Sequence[str]) -> None:
if len(argv) > 1:
raise app.UsageError("Unexpected command line arguments.")
client = AsyncClient()
await deferred_chat(client)
if __name__ == "__main__":
app.run(lambda argv: asyncio.run(main(argv)))