SpyBara
Go Premium

Documentation 2026-08-11 20:57 UTC to 2026-08-12 23:59 UTC

40 files changed +468 −307. View all changes and history on the product overview
2026
Mon 31 20:58 Tue 25 22:58 Fri 21 18:57 Thu 20 15:58 Wed 19 18:02 Tue 18 04:01 Thu 13 22:00 Wed 12 23:59 Tue 11 20:57 Sat 8 23:00 Fri 7 17:57 Thu 6 20:01 Mon 3 23:00 Sat 1 01:59
Details

29 timeout=3600, # Override default timeout with longer timeout for reasoning models29 timeout=3600, # Override default timeout with longer timeout for reasoning models

30 )30 )

31 31 

32 model = "grok-4.5"32 model = "grok-4.6"

33 requests = [33 requests = [

34 "Tell me a joke",34 "Tell me a joke",

35 "Write a funny haiku",35 "Write a funny haiku",


78 # The 'async with sem' ensures only a limited number of requests run at once78 # The 'async with sem' ensures only a limited number of requests run at once

79 async with sem:79 async with sem:

80 return await client.chat.completions.create(80 return await client.chat.completions.create(

81 model="grok-4.5",81 model="grok-4.6",

82 messages=[{"role": "user", "content": request}]82 messages=[{"role": "user", "content": request}]

83 )83 )

84 84 

Details

7> [!WARNING]7> [!WARNING]

8> Model support8> Model support

9>9>

10> `grok-4.5` is not currently supported for Batch API requests and will be rejected.10> `grok-4.6` and `grok-4.5` are not currently supported for Batch API requests and will be rejected.

11 11 

12## What is the Batch API?12## What is the Batch API?

13 13 

Details

35 -H "Content-Type: application/json" \35 -H "Content-Type: application/json" \

36 -H "Authorization: Bearer $XAI_API_KEY" \36 -H "Authorization: Bearer $XAI_API_KEY" \

37 -d '{37 -d '{

38 "model": "grok-4.5",38 "model": "grok-4.6",

39 "input": [39 "input": [

40 {"role": "system", "content": "You are a concise and knowledgeable science tutor."},40 {"role": "system", "content": "You are a concise and knowledgeable science tutor."},

41 {"role": "user", "content": "What is the Higgs boson and why is it important?"},41 {"role": "user", "content": "What is the Higgs boson and why is it important?"},


50 -H "Content-Type: application/json" \50 -H "Content-Type: application/json" \

51 -H "Authorization: Bearer $XAI_API_KEY" \51 -H "Authorization: Bearer $XAI_API_KEY" \

52 -d '{52 -d '{

53 "model": "grok-4.5",53 "model": "grok-4.6",

54 "input": [54 "input": [

55 {55 {

56 "type": "compaction",56 "type": "compaction",


72# Build up a chat normally — system prompt plus a few user/assistant turns.72# Build up a chat normally — system prompt plus a few user/assistant turns.

73# use_encrypted_content=True is recommended for reasoning models so the model's73# use_encrypted_content=True is recommended for reasoning models so the model's

74# reasoning content from prior turns is preserved through the compaction.74# reasoning content from prior turns is preserved through the compaction.

75chat = client.chat.create(model="grok-4.5", use_encrypted_content=True)75chat = client.chat.create(model="grok-4.6", use_encrypted_content=True)

76chat.append(system("You are a concise and knowledgeable science tutor."))76chat.append(system("You are a concise and knowledgeable science tutor."))

77 77 

78chat.append(user("What is the Higgs boson and why is it important?"))78chat.append(user("What is the Higgs boson and why is it important?"))


86# Step 1 — compact the conversation. Pass the chat's accumulated messages86# Step 1 — compact the conversation. Pass the chat's accumulated messages

87# straight into compact_context.87# straight into compact_context.

88compact = client.chat.compact_context(88compact = client.chat.compact_context(

89 model="grok-4.5",89 model="grok-4.6",

90 messages=chat.messages,90 messages=chat.messages,

91)91)

92print(f"Compaction ID: {compact.id}")92print(f"Compaction ID: {compact.id}")


113 113 

114# Step 1 — compact the long conversation114# Step 1 — compact the long conversation

115compacted = client.responses.compact(115compacted = client.responses.compact(

116 model="grok-4.5",116 model="grok-4.6",

117 input=[117 input=[

118 {"role": "system", "content": "You are a concise and knowledgeable science tutor."},118 {"role": "system", "content": "You are a concise and knowledgeable science tutor."},

119 {"role": "user", "content": "What is the Higgs boson and why is it important?"},119 {"role": "user", "content": "What is the Higgs boson and why is it important?"},


129 129 

130# Step 2 — continue the conversation. Spread compacted.output into the next input.130# Step 2 — continue the conversation. Spread compacted.output into the next input.

131followup = client.responses.create(131followup = client.responses.create(

132 model="grok-4.5",132 model="grok-4.6",

133 input=[133 input=[

134 *compacted.output, # use the compaction item verbatim — do not modify134 *compacted.output, # use the compaction item verbatim — do not modify

135 {"role": "user", "content": "Based on our earlier conversation, what gives particles their mass?"},135 {"role": "user", "content": "Based on our earlier conversation, what gives particles their mass?"},


149 149 

150// Step 1 — compact the long conversation150// Step 1 — compact the long conversation

151const compacted = await client.responses.compact({151const compacted = await client.responses.compact({

152 model: "grok-4.5",152 model: "grok-4.6",

153 input: [153 input: [

154 { role: "system", content: "You are a concise and knowledgeable science tutor." },154 { role: "system", content: "You are a concise and knowledgeable science tutor." },

155 { role: "user", content: "What is the Higgs boson and why is it important?" },155 { role: "user", content: "What is the Higgs boson and why is it important?" },


165 165 

166// Step 2 — continue the conversation. Spread compacted.output into the next input.166// Step 2 — continue the conversation. Spread compacted.output into the next input.

167const followup = await client.responses.create({167const followup = await client.responses.create({

168 model: "grok-4.5",168 model: "grok-4.6",

169 input: [169 input: [

170 ...compacted.output, // use the compaction item verbatim — do not modify170 ...compacted.output, // use the compaction item verbatim — do not modify

171 { role: "user", content: "Based on our earlier conversation, what gives particles their mass?" },171 { role: "user", content: "Based on our earlier conversation, what gives particles their mass?" },


186 "id": "cmp_01HZ9P0V8M2YQK3F7C4G6N5R2A",186 "id": "cmp_01HZ9P0V8M2YQK3F7C4G6N5R2A",

187 "object": "response.compaction",187 "object": "response.compaction",

188 "created_at": 1748895600,188 "created_at": 1748895600,

189 "model": "grok-4.5",189 "model": "grok-4.6",

190 "output": [190 "output": [

191 {191 {

192 "type": "compaction",192 "type": "compaction",


233 233 

234# use_encrypted_content=True preserves the model's reasoning content across234# use_encrypted_content=True preserves the model's reasoning content across

235# turns, recommended when using reasoning models.235# turns, recommended when using reasoning models.

236chat = client.chat.create(model="grok-4.5", use_encrypted_content=True)236chat = client.chat.create(model="grok-4.6", use_encrypted_content=True)

237chat.append(system("You are a helpful assistant. Keep answers brief."))237chat.append(system("You are a helpful assistant. Keep answers brief."))

238 238 

239compact_every = 5239compact_every = 5

Details

36client = Client(api_key=os.getenv('XAI_API_KEY'))36client = Client(api_key=os.getenv('XAI_API_KEY'))

37 37 

38chat = client.chat.create(38chat = client.chat.create(

39 model="grok-4.5",39 model="grok-4.6",

40 messages=[system("You are Zaphod Beeblebrox.")]40 messages=[system("You are Zaphod Beeblebrox.")]

41)41)

42chat.append(user("126/3=?"))42chat.append(user("126/3=?"))


69 {"role": "system", "content": "You are Zaphod Beeblebrox."},69 {"role": "system", "content": "You are Zaphod Beeblebrox."},

70 {"role": "user", "content": "126/3=?"}70 {"role": "user", "content": "126/3=?"}

71 ],71 ],

72 "model": "grok-4.5",72 "model": "grok-4.6",

73 "deferred": True73 "deferred": True

74}74}

75 75 


109 { role: 'system', content: 'You are Zaphod Beeblebrox.' },109 { role: 'system', content: 'You are Zaphod Beeblebrox.' },

110 { role: 'user', content: '126/3=?' }110 { role: 'user', content: '126/3=?' }

111 ],111 ],

112 model: 'grok-4.5',112 model: 'grok-4.6',

113 deferred: true113 deferred: true

114};114};

115 115 


149 {"role": "system", "content": "You are Zaphod Beeblebrox."},149 {"role": "system", "content": "You are Zaphod Beeblebrox."},

150 {"role": "user", "content": "126/3=?"}150 {"role": "user", "content": "126/3=?"}

151 ],151 ],

152 "model": "grok-4.5",152 "model": "grok-4.6",

153 "deferred": true153 "deferred": true

154}')154}')

155 155 


169 "id": "3f4ddfca-b997-3bd4-80d4-8112278a1508",169 "id": "3f4ddfca-b997-3bd4-80d4-8112278a1508",

170 "object": "chat.completion",170 "object": "chat.completion",

171 "created": 1752077400,171 "created": 1752077400,

172 "model": "grok-4.5",172 "model": "grok-4.6",

173 "choices": [173 "choices": [

174 {174 {

175 "index": 0,175 "index": 0,

Details

47 "content": "Hello, world!"47 "content": "Hello, world!"

48 }48 }

49 ],49 ],

50 "model": "grok-4.5",50 "model": "grok-4.6",

51 "stream": false51 "stream": false

52 }'52 }'

53```53```


69)69)

70 70 

71completion = client.chat.completions.create(71completion = client.chat.completions.create(

72 model="grok-4.5",72 model="grok-4.6",

73 messages=[73 messages=[

74 {"role": "user", "content": "Hello, world!"}74 {"role": "user", "content": "Hello, world!"}

75 ]75 ]


92});92});

93 93 

94const completion = await client.chat.completions.create({94const completion = await client.chat.completions.create({

95 model: 'grok-4.5',95 model: 'grok-4.6',

96 messages: [96 messages: [

97 { role: 'user', content: 'Hello, world!' }97 { role: 'user', content: 'Hello, world!' }

98 ],98 ],

Details

28 -H "Authorization: Bearer $XAI_API_KEY" \28 -H "Authorization: Bearer $XAI_API_KEY" \

29 -H "Content-Type: application/json" \29 -H "Content-Type: application/json" \

30 -d '{30 -d '{

31 "model": "grok-4.5",31 "model": "grok-4.6",

32 "input": "Explain the Riemann hypothesis in one paragraph.",32 "input": "Explain the Riemann hypothesis in one paragraph.",

33 "service_tier": "priority"33 "service_tier": "priority"

34 }'34 }'


43client = Client(api_key=os.getenv("XAI_API_KEY"))43client = Client(api_key=os.getenv("XAI_API_KEY"))

44 44 

45chat = client.chat.create(45chat = client.chat.create(

46 model="grok-4.5",46 model="grok-4.6",

47 service_tier="priority",47 service_tier="priority",

48)48)

49chat.append(user("Explain the Riemann hypothesis in one paragraph."))49chat.append(user("Explain the Riemann hypothesis in one paragraph."))


64)64)

65 65 

66response = client.responses.create(66response = client.responses.create(

67 model="grok-4.5",67 model="grok-4.6",

68 input="Explain the Riemann hypothesis in one paragraph.",68 input="Explain the Riemann hypothesis in one paragraph.",

69 service_tier="priority",69 service_tier="priority",

70)70)


82});82});

83 83 

84const response = await client.responses.create({84const response = await client.responses.create({

85 model: "grok-4.5",85 model: "grok-4.6",

86 input: "Explain the Riemann hypothesis in one paragraph.",86 input: "Explain the Riemann hypothesis in one paragraph.",

87 service_tier: "priority",87 service_tier: "priority",

88});88});


96```json customLanguage="json"96```json customLanguage="json"

97{97{

98 "id": "resp_abc123",98 "id": "resp_abc123",

99 "model": "grok-4.5",99 "model": "grok-4.6",

100 "service_tier": "priority",100 "service_tier": "priority",

101 "usage": {101 "usage": {

102 "input_tokens": 42,102 "input_tokens": 42,

Details

12 -H "Authorization: Bearer $XAI_API_KEY" \12 -H "Authorization: Bearer $XAI_API_KEY" \

13 -H "x-grok-conv-id: conv_abc123" \13 -H "x-grok-conv-id: conv_abc123" \

14 -d '{14 -d '{

15 "model": "grok-4.5",15 "model": "grok-4.6",

16 "messages": [16 "messages": [

17 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},17 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},

18 {"role": "user", "content": "What is prompt caching?"}18 {"role": "user", "content": "What is prompt caching?"}


29)29)

30 30 

31response = client.chat.completions.create(31response = client.chat.completions.create(

32 model="grok-4.5",32 model="grok-4.6",

33 messages=[33 messages=[

34 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},34 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},

35 {"role": "user", "content": "What is prompt caching?"},35 {"role": "user", "content": "What is prompt caching?"},


53 53 

54const response = await client.chat.completions.create(54const response = await client.chat.completions.create(

55 {55 {

56 model: 'grok-4.5',56 model: 'grok-4.6',

57 messages: [57 messages: [

58 {58 {

59 role: 'system',59 role: 'system',


85 -H "Content-Type: application/json" \85 -H "Content-Type: application/json" \

86 -H "Authorization: Bearer $XAI_API_KEY" \86 -H "Authorization: Bearer $XAI_API_KEY" \

87 -d '{87 -d '{

88 "model": "grok-4.5",88 "model": "grok-4.6",

89 "input": "What is prompt caching?",89 "input": "What is prompt caching?",

90 "prompt_cache_key": "b79ad29b-b3f9-463c-bca6-041d5058d366"90 "prompt_cache_key": "b79ad29b-b3f9-463c-bca6-041d5058d366"

91 }'91 }'


100)100)

101 101 

102response = client.responses.create(102response = client.responses.create(

103 model="grok-4.5",103 model="grok-4.6",

104 input="What is prompt caching?",104 input="What is prompt caching?",

105 extra_body={105 extra_body={

106 "prompt_cache_key": "b79ad29b-b3f9-463c-bca6-041d5058d366",106 "prompt_cache_key": "b79ad29b-b3f9-463c-bca6-041d5058d366",


120});120});

121 121 

122const response = await client.responses.create({122const response = await client.responses.create({

123 model: 'grok-4.5',123 model: 'grok-4.6',

124 input: 'What is prompt caching?',124 input: 'What is prompt caching?',

125 // @ts-expect-error -- xAI-specific field125 // @ts-expect-error -- xAI-specific field

126 prompt_cache_key: 'b79ad29b-b3f9-463c-bca6-041d5058d366',126 prompt_cache_key: 'b79ad29b-b3f9-463c-bca6-041d5058d366',


137import { generateText } from 'ai';137import { generateText } from 'ai';

138 138 

139const { text, usage } = await generateText({139const { text, usage } = await generateText({

140 model: xai.responses('grok-4.5'),140 model: xai.responses('grok-4.6'),

141 prompt: 'What is prompt caching?',141 prompt: 'What is prompt caching?',

142 providerOptions: {142 providerOptions: {

143 xai: {143 xai: {


163 metadata=(("x-grok-conv-id", "conv_abc123"),),163 metadata=(("x-grok-conv-id", "conv_abc123"),),

164)164)

165 165 

166chat = client.chat.create(model="grok-4.5")166chat = client.chat.create(model="grok-4.6")

167chat.append(system("You are Grok, a helpful and truthful AI assistant built by xAI."))167chat.append(system("You are Grok, a helpful and truthful AI assistant built by xAI."))

168chat.append(user("What is prompt caching?"))168chat.append(user("What is prompt caching?"))

169 169 

Details

24 -H "Authorization: Bearer $XAI_API_KEY" \24 -H "Authorization: Bearer $XAI_API_KEY" \

25 -H "x-grok-conv-id: conv_abc123" \25 -H "x-grok-conv-id: conv_abc123" \

26 -d '{26 -d '{

27 "model": "grok-4.5",27 "model": "grok-4.6",

28 "messages": [28 "messages": [

29 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},29 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},

30 {"role": "user", "content": "What is prompt caching?"},30 {"role": "user", "content": "What is prompt caching?"},


38 -H "Authorization: Bearer $XAI_API_KEY" \38 -H "Authorization: Bearer $XAI_API_KEY" \

39 -H "x-grok-conv-id: conv_abc123" \39 -H "x-grok-conv-id: conv_abc123" \

40 -d '{40 -d '{

41 "model": "grok-4.5",41 "model": "grok-4.6",

42 "messages": [42 "messages": [

43 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},43 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},

44 {"role": "user", "content": "What is prompt caching?"},44 {"role": "user", "content": "What is prompt caching?"},


64 64 

65# Turn 1: Initial request (establishes the cache)65# Turn 1: Initial request (establishes the cache)

66response = client.chat.completions.create(66response = client.chat.completions.create(

67 model="grok-4.5",67 model="grok-4.6",

68 messages=messages,68 messages=messages,

69 extra_headers={"x-grok-conv-id": conversation_id},69 extra_headers={"x-grok-conv-id": conversation_id},

70)70)


76 76 

77# Turn 2: Cache HIT — prefix is unchanged, only new messages appended77# Turn 2: Cache HIT — prefix is unchanged, only new messages appended

78response = client.chat.completions.create(78response = client.chat.completions.create(

79 model="grok-4.5",79 model="grok-4.6",

80 messages=messages,80 messages=messages,

81 extra_headers={"x-grok-conv-id": conversation_id},81 extra_headers={"x-grok-conv-id": conversation_id},

82)82)


103 103 

104// Turn 1: Initial request (establishes the cache)104// Turn 1: Initial request (establishes the cache)

105const turn1 = await client.chat.completions.create(105const turn1 = await client.chat.completions.create(

106 { model: 'grok-4.5', messages },106 { model: 'grok-4.6', messages },

107 { headers: { 'x-grok-conv-id': conversationId } },107 { headers: { 'x-grok-conv-id': conversationId } },

108);108);

109console.log(109console.log(


117 117 

118// Turn 2: Cache HIT — prefix unchanged, new message appended118// Turn 2: Cache HIT — prefix unchanged, new message appended

119const turn2 = await client.chat.completions.create(119const turn2 = await client.chat.completions.create(

120 { model: 'grok-4.5', messages },120 { model: 'grok-4.6', messages },

121 { headers: { 'x-grok-conv-id': conversationId } },121 { headers: { 'x-grok-conv-id': conversationId } },

122);122);

123console.log(123console.log(


136 -H "Authorization: Bearer $XAI_API_KEY" \136 -H "Authorization: Bearer $XAI_API_KEY" \

137 -H "x-grok-conv-id: conv_abc123" \137 -H "x-grok-conv-id: conv_abc123" \

138 -d '{138 -d '{

139 "model": "grok-4.5",139 "model": "grok-4.6",

140 "messages": [140 "messages": [

141 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},141 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},

142 {"role": "user", "content": "What is prompt caching?"},142 {"role": "user", "content": "What is prompt caching?"},


160 -H "Authorization: Bearer $XAI_API_KEY" \160 -H "Authorization: Bearer $XAI_API_KEY" \

161 -H "x-grok-conv-id: conv_abc123" \161 -H "x-grok-conv-id: conv_abc123" \

162 -d '{162 -d '{

163 "model": "grok-4.5",163 "model": "grok-4.6",

164 "messages": [164 "messages": [

165 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},165 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},

166 {"role": "user", "content": "What is prompt caching?"},166 {"role": "user", "content": "What is prompt caching?"},


183 -H "Authorization: Bearer $XAI_API_KEY" \183 -H "Authorization: Bearer $XAI_API_KEY" \

184 -H "x-grok-conv-id: conv_abc123" \184 -H "x-grok-conv-id: conv_abc123" \

185 -d '{185 -d '{

186 "model": "grok-4.5",186 "model": "grok-4.6",

187 "messages": [187 "messages": [

188 {"role": "user", "content": "What is prompt caching?"},188 {"role": "user", "content": "What is prompt caching?"},

189 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},189 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},

Details

44 json.dumps(44 json.dumps(

45 {45 {

46 "type": "response.create",46 "type": "response.create",

47 "model": "grok-4.5",47 "model": "grok-4.6",

48 "store": False,48 "store": False,

49 "input": [49 "input": [

50 {50 {


72 ws.send(72 ws.send(

73 JSON.stringify({73 JSON.stringify({

74 type: "response.create",74 type: "response.create",

75 model: "grok-4.5",75 model: "grok-4.6",

76 store: false,76 store: false,

77 input: [77 input: [

78 {78 {


112 json.dumps(112 json.dumps(

113 {113 {

114 "type": "response.create",114 "type": "response.create",

115 "model": "grok-4.5",115 "model": "grok-4.6",

116 "store": False,116 "store": False,

117 "previous_response_id": "resp_123",117 "previous_response_id": "resp_123",

118 "input": [118 "input": [


137ws.send(137ws.send(

138 JSON.stringify({138 JSON.stringify({

139 type: "response.create",139 type: "response.create",

140 model: "grok-4.5",140 model: "grok-4.6",

141 store: false,141 store: false,

142 previous_response_id: "resp_123",142 previous_response_id: "resp_123",

143 input: [143 input: [

community.md +2 −2

Details

20 20 

21os.environ['XAI_API_KEY'] = ""21os.environ['XAI_API_KEY'] = ""

22response = completion(22response = completion(

23 model="xai/grok-4.5",23 model="xai/grok-4.6",

24 messages=[24 messages=[

25 {25 {

26 "role": "user",26 "role": "user",


50import { generateText } from 'ai';50import { generateText } from 'ai';

51 51 

52const { text } = await generateText({52const { text } = await generateText({

53 model: xai.responses('grok-4.5'),53 model: xai.responses('grok-4.6'),

54 prompt: 'Write a vegetarian lasagna recipe for 4 people.',54 prompt: 'Write a vegetarian lasagna recipe for 4 people.',

55});55});

56```56```

Details

45 45 

46Use the model ID shown in Model Garden. Vertex model names may use a publisher prefix, for example:46Use the model ID shown in Model Garden. Vertex model names may use a publisher prefix, for example:

47 47 

48* `xai/grok-4.5`48* `xai/grok-4.6`

49 49 

50Model availability generally matches the xAI API, subject to Google Cloud regional availability and quotas.50Model availability generally matches the xAI API, subject to Google Cloud regional availability and quotas.

51 51 


71client = OpenAI() # Uses ADC / env vars automatically71client = OpenAI() # Uses ADC / env vars automatically

72 72 

73response = client.responses.create(73response = client.responses.create(

74 model="xai/grok-4.5",74 model="xai/grok-4.6",

75 input="Explain the advantages of using Grok for agentic workflows with parallel tool calling.",75 input="Explain the advantages of using Grok for agentic workflows with parallel tool calling.",

76 max_output_tokens=800,76 max_output_tokens=800,

77)77)


87client = OpenAI()87client = OpenAI()

88 88 

89response = client.chat.completions.create(89response = client.chat.completions.create(

90 model="xai/grok-4.5",90 model="xai/grok-4.6",

91 messages=[91 messages=[

92 {92 {

93 "role": "user",93 "role": "user",

cost-tracking.md +11 −11

Details

32client = Client(api_key=os.getenv("XAI_API_KEY"))32client = Client(api_key=os.getenv("XAI_API_KEY"))

33 33 

34chat = client.chat.create(34chat = client.chat.create(

35 model="grok-4.5",35 model="grok-4.6",

36 messages=[user("Say hello")],36 messages=[user("Say hello")],

37)37)

38response = chat.sample()38response = chat.sample()


62 -H "Authorization: Bearer $XAI_API_KEY" \62 -H "Authorization: Bearer $XAI_API_KEY" \

63 -H "Content-Type: application/json" \63 -H "Content-Type: application/json" \

64 -d '{64 -d '{

65 "model": "grok-4.5",65 "model": "grok-4.6",

66 "input": "Say hello"66 "input": "Say hello"

67 }' | jq '.usage.cost_in_usd_ticks'67 }' | jq '.usage.cost_in_usd_ticks'

68```68```


77)77)

78 78 

79completion = client.chat.completions.create(79completion = client.chat.completions.create(

80 model="grok-4.5",80 model="grok-4.6",

81 messages=[{"role": "user", "content": "Say hello"}],81 messages=[{"role": "user", "content": "Say hello"}],

82)82)

83 83 


96});96});

97 97 

98const completion = await client.chat.completions.create({98const completion = await client.chat.completions.create({

99 model: "grok-4.5",99 model: "grok-4.6",

100 messages: [{ role: "user", content: "Say hello" }],100 messages: [{ role: "user", content: "Say hello" }],

101});101});

102 102 


123client = Client(api_key=os.getenv("XAI_API_KEY"))123client = Client(api_key=os.getenv("XAI_API_KEY"))

124 124 

125chat = client.chat.create(125chat = client.chat.create(

126 model="grok-4.5",126 model="grok-4.6",

127 messages=[user("Tell me a joke")],127 messages=[user("Tell me a joke")],

128)128)

129 129 


145)145)

146 146 

147stream = client.chat.completions.create(147stream = client.chat.completions.create(

148 model="grok-4.5",148 model="grok-4.6",

149 messages=[{"role": "user", "content": "Tell me a joke"}],149 messages=[{"role": "user", "content": "Tell me a joke"}],

150 stream=True,150 stream=True,

151 stream_options={"include_usage": True},151 stream_options={"include_usage": True},


171client = Client(api_key=os.getenv("XAI_API_KEY"))171client = Client(api_key=os.getenv("XAI_API_KEY"))

172 172 

173chat = client.chat.create(173chat = client.chat.create(

174 model="grok-4.5",174 model="grok-4.6",

175 messages=[system("You are a helpful assistant.")],175 messages=[system("You are a helpful assistant.")],

176)176)

177 177 


211 211 

212 messages.append({"role": "user", "content": prompt})212 messages.append({"role": "user", "content": prompt})

213 completion = client.chat.completions.create(213 completion = client.chat.completions.create(

214 model="grok-4.5",214 model="grok-4.6",

215 messages=messages,215 messages=messages,

216 )216 )

217 217 


240client = Client(api_key=os.getenv("XAI_API_KEY"))240client = Client(api_key=os.getenv("XAI_API_KEY"))

241 241 

242chat = client.chat.create(242chat = client.chat.create(

243 model="grok-4.5",243 model="grok-4.6",

244 tools=[web_search(), x_search()],244 tools=[web_search(), x_search()],

245)245)

246chat.append(user("What are people saying about xAI's latest announcement?"))246chat.append(user("What are people saying about xAI's latest announcement?"))


264)264)

265 265 

266response = client.responses.create(266response = client.responses.create(

267 model="grok-4.5",267 model="grok-4.6",

268 input="What are people saying about xAI's latest announcement?",268 input="What are people saying about xAI's latest announcement?",

269 tools=[269 tools=[

270 {"type": "web_search"},270 {"type": "web_search"},


284 -H "Authorization: Bearer $XAI_API_KEY" \284 -H "Authorization: Bearer $XAI_API_KEY" \

285 -H "Content-Type: application/json" \285 -H "Content-Type: application/json" \

286 -d '{286 -d '{

287 "model": "grok-4.5",287 "model": "grok-4.6",

288 "tools": [{"type": "web_search"}, {"type": "x_search"}],288 "tools": [{"type": "web_search"}, {"type": "x_search"}],

289 "input": "What are people saying about xAI'\''s latest announcement?"289 "input": "What are people saying about xAI'\''s latest announcement?"

290 }' | jq '{tools_used: .usage.num_server_side_tools_used, cost_in_usd_ticks: .usage.cost_in_usd_ticks}'290 }' | jq '{tools_used: .usage.num_server_side_tools_used, cost_in_usd_ticks: .usage.cost_in_usd_ticks}'

files.md +3 −3

Details

78)78)

79 79 

80# 2. Chat with files80# 2. Chat with files

81chat = client.chat.create(model="grok-4.5")81chat = client.chat.create(model="grok-4.6")

82chat.append(user(82chat.append(user(

83 "Summarize both documents",83 "Summarize both documents",

84 file(url=file_url),84 file(url=file_url),


117 Authorization: \`Bearer \${process.env.XAI_API_KEY}\`,117 Authorization: \`Bearer \${process.env.XAI_API_KEY}\`,

118 },118 },

119 body: JSON.stringify({119 body: JSON.stringify({

120 model: "grok-4.5",120 model: "grok-4.6",

121 input: [121 input: [

122 {122 {

123 role: "user",123 role: "user",


162 162 

163* **File size**: Maximum 48 MB per file163* **File size**: Maximum 48 MB per file

164* **No batch requests**: File attachments with document search are agentic requests and do not support batch mode (`n > 1`)164* **No batch requests**: File attachments with document search are agentic requests and do not support batch mode (`n > 1`)

165* **Agentic models only**: Requires models that support agentic tool calling (e.g., `grok-4.20`, `grok-4.5`)165* **Agentic models only**: Requires models that support agentic tool calling (e.g., `grok-4.20`, `grok-4.5`, `grok-4.6`)

166* **Supported file formats**:166* **Supported file formats**:

167 * Plain text files (.txt)167 * Plain text files (.txt)

168 * Markdown files (.md)168 * Markdown files (.md)

grok-4-6.md +17 −15 renamed

Details

Previously: grok-4-5.md

1#### Get Started1#### Get Started

2 2 

3# Grok 4.53# Grok 4.6

4 4 

5Grok 4.5 is SpaceXAI's frontier model built for coding, agentic tasks, and knowledge work. It was trained in SpaceXAI's data centers in Memphis with new datasets spanning science, engineering, and math.5Grok 4.6 is SpaceXAI's frontier model built for coding, agentic tasks, and knowledge work.

6 6 

7## Using the API7## Using the API

8 8 

9If you already have an [API key](https://console.x.ai/team/default/api-keys), set the model name to `grok-4.5`:9If you already have an [API key](https://console.x.ai/team/default/api-keys), set the model name to `grok-4.6`:

10 10 

11```python customLanguage="pythonXAI"11```python customLanguage="pythonXAI"

12import os12import os


15 15 

16client = Client(api_key=os.getenv("XAI_API_KEY"))16client = Client(api_key=os.getenv("XAI_API_KEY"))

17 17 

18chat = client.chat.create(model="grok-4.5")18chat = client.chat.create(model="grok-4.6")

19chat.append(user("Find and fix the bug, then explain it: function median(a){a.sort();return a[a.length/2]}"))19chat.append(user("Find and fix the bug, then explain it: function median(a){a.sort();return a[a.length/2]}"))

20 20 

21response = chat.sample()21response = chat.sample()


27import { generateText } from 'ai';27import { generateText } from 'ai';

28 28 

29const { text } = await generateText({29const { text } = await generateText({

30 model: xai.responses('grok-4.5'),30 model: xai.responses('grok-4.6'),

31 prompt:31 prompt:

32 'Find and fix the bug, then explain it: function median(a){a.sort();return a[a.length/2]}',32 'Find and fix the bug, then explain it: function median(a){a.sort();return a[a.length/2]}',

33});33});


44});44});

45 45 

46const response = await client.responses.create({46const response = await client.responses.create({

47 model: 'grok-4.5',47 model: 'grok-4.6',

48 input: [48 input: [

49 {49 {

50 role: 'user',50 role: 'user',


62 -H "Content-Type: application/json" \62 -H "Content-Type: application/json" \

63 -H "Authorization: Bearer $XAI_API_KEY" \63 -H "Authorization: Bearer $XAI_API_KEY" \

64 -d '{64 -d '{

65 "model": "grok-4.5",65 "model": "grok-4.6",

66 "input": "Find and fix the bug, then explain it: function median(a){a.sort();return a[a.length/2]}"66 "input": "Find and fix the bug, then explain it: function median(a){a.sort();return a[a.length/2]}"

67 }'67 }'

68```68```


73 73 

74| Property | Value |74| Property | Value |

75|----------|-------|75|----------|-------|

76| Model name | `grok-4.5` |76| Model name | `grok-4.6` |

77| Context window | 500,000 tokens |

77| Knowledge cutoff | February 1, 2026 |78| Knowledge cutoff | February 1, 2026 |

79| Modalities | Text and image input; text output |

80| Output limit | No text output limit |

78| Input price | $2.00 / 1M tokens |81| Input price | $2.00 / 1M tokens |

79| Output price | $6.00 / 1M tokens |82| Output price | $6.00 / 1M tokens |

80| Reasoning | Low, medium, or high (default high) |83| Reasoning | Low, medium, high (default), or xhigh |

81| APIs | [Responses API](/developers/rest-api-reference/inference/chat#create-new-response), [Chat Completions](/developers/rest-api-reference/inference/chat#chat-completions) |84| APIs | [Responses API](/developers/rest-api-reference/inference/chat#create-new-response), [Chat Completions](/developers/rest-api-reference/inference/chat#chat-completions) |

82| Tools | [Function calling](/developers/tools/function-calling), [web search](/developers/tools/web-search), [X search](/developers/tools/x-search), [code execution](/developers/tools/code-execution) |85| Tools | [Function calling](/developers/tools/function-calling), [web search](/developers/tools/web-search), [X search](/developers/tools/x-search), [code execution](/developers/tools/code-execution) |

83 86 

84Full context window, rate limits, and live pricing for your team are on the [model detail page](/developers/models/grok-4.5) and [Pricing](/developers/pricing).87Rate limits and live pricing for your team are on the [model detail page](/developers/models/grok-4.6) and [Pricing](/developers/pricing).

85 88 

86For benchmark results and cost-versus-score comparisons, see the [announcement](https://x.ai/news/grok-4-5).89For benchmark results and demos, see the [announcement](https://x.ai/news/grok-4-6).

87 90 

88## Important details91## Important details

89 92 


95* **xAI API**: get a key from the [console](https://console.x.ai/)98* **xAI API**: get a key from the [console](https://console.x.ai/)

96* **Grok Build**: the default model of the [coding agent](/build/overview), on the API and CLI99* **Grok Build**: the default model of the [coding agent](/build/overview), on the API and CLI

97* **Cursor**: available on all plans100* **Cursor**: available on all plans

98* **Office add-ins**: default model in the Word, PowerPoint, and Excel add-ins101* **Model gateways**: OpenRouter, Vercel, and Cloudflare

99* **Model gateways**: OpenRouter, Vercel, Cloudflare, Snowflake, and Databricks Mosaic

100 102 

101## Learn more103## Learn more

102 104 

103* [Reasoning](/developers/model-capabilities/text/reasoning#the-reasoning_effort-parameter) - controlling `reasoning_effort`105* [Reasoning](/developers/model-capabilities/text/reasoning#the-reasoning_effort-parameter) - controlling `reasoning_effort`, including `"xhigh"`

104* [Announcement](https://x.ai/news/grok-4-5) - launch post with demos and full benchmark figures106* [Announcement](https://x.ai/news/grok-4-6) - launch post with demos and full benchmark figures

105* [Models](/developers/models) - compare available models and their capabilities107* [Models](/developers/models) - compare available models and their capabilities

106* [Pricing](/developers/pricing) - token pricing for all models108* [Pricing](/developers/pricing) - token pricing for all models

Details

33 33 

34And to specify models the API key has access to:34And to specify models the API key has access to:

35 35 

36* `api-key:model:<model name such as grok-4.5>`36* `api-key:model:<model name such as grok-4.6>`

37 37 

38### Create an API key38### Create an API key

39 39 

Details

133 133 

134| Model | Description |134| Model | Description |

135|-------|-------------|135|-------|-------------|

136| `grok-voice-latest` | Alias for `grok-voice-think-fast-1.0`.Updates to `grok-voice-think-fast-2.0` on August 5, 2026. |136| `grok-voice-latest` | Alias for `grok-voice-think-fast-2.0`. |

137| `grok-voice-think-fast-2.0` | Flagship voice model |137| `grok-voice-think-fast-2.0` | Flagship voice model |

138| `grok-voice-think-fast-1.0` | Previous-generation voice model |138| `grok-voice-think-fast-1.0` | Previous-generation voice model |

139 139 

Details

109| `optimize_streaming_latency` | integer | | Latency optimization level for streaming synthesis. `0` (default): No optimization — best audio quality. `1`: Reduced first-chunk size for lower time-to-first-audio, with minor quality tradeoff at chunk boundaries. `2`: Further reduced first-chunk size for lowest time-to-first-audio, with more noticeable quality tradeoff at chunk boundaries. |109| `optimize_streaming_latency` | integer | | Latency optimization level for streaming synthesis. `0` (default): No optimization — best audio quality. `1`: Reduced first-chunk size for lower time-to-first-audio, with minor quality tradeoff at chunk boundaries. `2`: Further reduced first-chunk size for lowest time-to-first-audio, with more noticeable quality tradeoff at chunk boundaries. |

110| `text_normalization` | boolean | | Enable text normalization before synthesis. When `true`, the model normalizes written-form text (e.g. numbers, abbreviations, symbols) into spoken-form before generating audio. Defaults to `false`. |110| `text_normalization` | boolean | | Enable text normalization before synthesis. When `true`, the model normalizes written-form text (e.g. numbers, abbreviations, symbols) into spoken-form before generating audio. Defaults to `false`. |

111| `with_timestamps` | boolean | | Return character-level timing metadata alongside the audio. When `true`, the response is a JSON envelope containing base64-encoded audio plus per-character start/end times. Adds latency for the post-synthesis alignment pass. Defaults to `false`. See [Character-level timestamps](#character-level-timestamps). |111| `with_timestamps` | boolean | | Return character-level timing metadata alongside the audio. When `true`, the response is a JSON envelope containing base64-encoded audio plus per-character start/end times. Adds latency for the post-synthesis alignment pass. Defaults to `false`. See [Character-level timestamps](#character-level-timestamps). |

112| `replace` | object | | Map of phrases to spoken substitutions applied before synthesis. Values may be respellings (`{"Acme Mobile": "Acme Mobull"}`) or [IPA](#phonetic-pronunciations-with-ipa) phonetics (`{"nginx": "/ˈɛndʒɪn ˈɛks/"}`). See [Pronunciation Replacements](#pronunciation-replacements). |

112 113 

113### Example with all options114### Example with all options

114 115 


674 675 

675This mostly happens with [`text_normalization`](#request-body) enabled, which expands symbols and numbers into words. With normalization on, `$5` is spoken as "five dollars" but is still only two characters: the `$` gets the full span for "five dollars", and the `5` gets an interpolated time inside it. So always step through `graph_chars` in order rather than slicing the input text by index.676This mostly happens with [`text_normalization`](#request-body) enabled, which expands symbols and numbers into words. With normalization on, `$5` is spoken as "five dollars" but is still only two characters: the `$` gets the full span for "five dollars", and the `5` gets an interpolated time inside it. So always step through `graph_chars` in order rather than slicing the input text by index.

676 677 

678## Pronunciation Replacements

679 

680Use `replace` to fix how specific words or phrases are pronounced. Each key is matched in your text and swapped for its replacement value **before** synthesis, so only the audio changes — you keep sending your original text, and you are billed on it.

681 

682This is useful for brand names, acronyms, and domain terms. Mapping `"Acme Mobile"` to `"Acme Mobull"` makes the audio say it correctly while your request body still reads "Acme Mobile".

683 

684```python customLanguage="pythonWithoutSDK"

685response = requests.post(

686 "https://api.x.ai/v1/tts",

687 headers={"Authorization": f"Bearer {XAI_API_KEY}"},

688 json={

689 "text": "Welcome to Acme Mobile.",

690 "voice_id": "eve",

691 "language": "en",

692 "replace": {"Acme Mobile": "Acme Mobull"},

693 },

694)

695```

696 

697```javascript customLanguage="javascriptWithoutSDK"

698const response = await fetch("https://api.x.ai/v1/tts", {

699 method: "POST",

700 headers: {

701 Authorization: `Bearer ${XAI_API_KEY}`,

702 "Content-Type": "application/json"

703 },

704 body: JSON.stringify({

705 text: "Welcome to Acme Mobile.",

706 voice_id: "eve",

707 language: "en",

708 replace: { "Acme Mobile": "Acme Mobull" }

709 })

710});

711```

712 

713Matching behavior:

714 

715* Matching is case-insensitive; the replacement is spoken using the casing you provide.

716* Whole-word boundaries are required, so `Acme, Mobile`, `Acme-Mobile`, and `Acme Mobiles` do **not** match. In scripts written without spaces — Chinese, Japanese, Thai, Lao, Khmer, Burmese — matching is per character, so a one-character key also matches inside a longer word.

717* When multiple keys share a prefix, the longest match wins.

718* Keys match the text exactly as you send it, so write them as they appear in your input.

719 

720#### Map limits

721 

722The map is validated before any audio is generated, so a broken rule fails the request rather than silently dropping an entry:

723 

724| Constraint | Limit | Error (`400`) |

725|---|---|---|

726| Entries per map | 200 | `replace has too many entries` |

727| Key length | 100 characters | `replace key "…" is too long` |

728| Value length | 128 characters | `replace value for "…" is too long` |

729| Key characters | letters, digits, apostrophes, spaces | `replace key "C++" may not contain punctuation or symbols` |

730| Keys non-blank | — | `replace keys must not be blank` |

731| Keys distinct as phrases | compared case- and whitespace-insensitively | `replace keys "ACME" and "Acme" are the same phrase; keep one` |

732| Text after substitution | 60,000 characters | `` `replace` expands the text to … characters `` |

733 

734The last row bounds the **rewritten** text — watch it when a short key maps to a long value across a large body of text. Your 15,000-character input cap and your billing still count what you sent.

735 

736The same `replace` map is available on the [Speech to Speech API](/developers/model-capabilities/audio/speech-to-speech#pronunciation-replacements) and on the [WebSocket endpoint](#session-configuration).

737 

738> [!NOTE]

739>

740> Replacements change the text that is spoken. With `with_timestamps` enabled, `graph_chars` describes the **spoken** text, so it will contain the replacement characters rather than the characters you sent.

741 

742### Phonetic pronunciations with IPA

743 

744The model reads [IPA](https://www.internationalphoneticalphabet.org) directly in `text`:

745 

746```json

747{"text": "Restart /ˈɛndʒɪn ˈɛks/ on the edge nodes."}

748```

749 

750Put it in a `replace` value to keep phonetics out of the text you send — when the text is generated upstream, or when one entry should cover every occurrence in a document or a session.

751 

752Phonetics earn their keep where pronunciation is a convention rather than something derivable from spelling: `nginx` is "engine X", `kubectl` is "kube cuttle", and `SQL` is "sequel" or "S-Q-L" by house style. Left alone the model spells these out, and not the same way twice; an entry makes the reading deterministic.

753 

754```python customLanguage="pythonWithoutSDK"

755response = requests.post(

756 "https://api.x.ai/v1/tts",

757 headers={"Authorization": f"Bearer {XAI_API_KEY}"},

758 json={

759 "text": "nginx is returning errors on the Acme Mobile edge nodes.",

760 "voice_id": "eve",

761 "language": "en",

762 "replace": {

763 "nginx": "/ˈɛndʒɪn ˈɛks/",

764 "Acme Mobile": "Acme Mobull",

765 },

766 },

767)

768```

769 

770```javascript customLanguage="javascriptWithoutSDK"

771const response = await fetch("https://api.x.ai/v1/tts", {

772 method: "POST",

773 headers: {

774 Authorization: `Bearer ${XAI_API_KEY}`,

775 "Content-Type": "application/json"

776 },

777 body: JSON.stringify({

778 text: "nginx is returning errors on the Acme Mobile edge nodes.",

779 voice_id: "eve",

780 language: "en",

781 replace: {

782 nginx: "/ˈɛndʒɪn ˈɛks/",

783 "Acme Mobile": "Acme Mobull"

784 }

785 })

786});

787```

788 

789Phonetic and respelled entries can share one map, as above.

790 

791* Synthesize the word first. Well-known names are usually already right — `IEEE` comes out "I triple E" unprompted — and a redundant entry is upkeep with no benefit.

792* Slashes are convention, not a marker: `/ˈɛndʒɪn ˈɛks/` and `ˈɛndʒɪn ˈɛks` are spoken identically and never read aloud.

793* IPA belongs in the value. Keys stay the ordinary spelling you want to catch.

794* Phonetics are unaffected by [`text_normalization`](#request-body), and work in any supported language.

795 

796> [!WARNING]

797>

798> IPA is interpreted per symbol, so a typo yields a confidently wrong pronunciation rather than an error. Check symbols against the [IPA sound chart](https://www.internationalphoneticalphabet.org/ipa-sounds/) and listen to each new entry once before shipping it.

799 

677## Best Practices800## Best Practices

678 801 

679Tips for getting the highest quality output from the TTS API.802Tips for getting the highest quality output from the TTS API.


890| **Max text length** | 15,000 characters per request | No limit — individual `text.delta` messages capped at 15,000 characters each |1013| **Max text length** | 15,000 characters per request | No limit — individual `text.delta` messages capped at 15,000 characters each |

891| **Request timeout** | 15 minutes | No timeout (connection stays open) |1014| **Request timeout** | 15 minutes | No timeout (connection stays open) |

892| **Concurrent sessions** | — | 50 per team |1015| **Concurrent sessions** | — | 50 per team |

1016| **[`replace`](#map-limits) map** | 200 entries; keys ≤ 100 and values ≤ 128 characters | Same, per `session.update` |

1017| **Text after `replace`** | 60,000 characters | 60,000 characters per utterance |

893 1018 

894For content exceeding 15,000 characters, use the [bidirectional WebSocket endpoint](#streaming-tts-websocket) which has no text length limit.1019For content exceeding 15,000 characters, use the [bidirectional WebSocket endpoint](#streaming-tts-websocket) which has no text length limit.

895 1020 


942| `text.delta` | A chunk of text to synthesize. Individual deltas are capped at **15,000 characters**. |1067| `text.delta` | A chunk of text to synthesize. Individual deltas are capped at **15,000 characters**. |

943| `text.done` | Signals the end of the current utterance. The server will finish generating audio and send `audio.done`. |1068| `text.done` | Signals the end of the current utterance. The server will finish generating audio and send `audio.done`. |

944| `text.clear` | Cancel the current utterance. The server stops generating audio, discards any buffered data, and responds with `audio.clear`. |1069| `text.clear` | Cancel the current utterance. The server stops generating audio, discards any buffered data, and responds with `audio.clear`. |

1070| `session.update` | Set or change the [`replace`](#session-configuration) map for the session. Accepted at any point; it takes effect on the next utterance to begin. |

945 1071 

946### Server → Client Messages1072### Server → Client Messages

947 1073 


959| `audio.delta` | A chunk of base64-encoded audio in the codec specified at connection time. Decode and enqueue for playback. When the connection was opened with `with_timestamps=true`, also carries `audio_timestamps` (`graph_chars` + `graph_times`) and `audio_duration` for the characters in that chunk. See [Character-level timestamps](#character-level-timestamps). |1085| `audio.delta` | A chunk of base64-encoded audio in the codec specified at connection time. Decode and enqueue for playback. When the connection was opened with `with_timestamps=true`, also carries `audio_timestamps` (`graph_chars` + `graph_times`) and `audio_duration` for the characters in that chunk. See [Character-level timestamps](#character-level-timestamps). |

960| `audio.done` | All audio for the current utterance has been sent. Includes a `trace_id` for debugging. |1086| `audio.done` | All audio for the current utterance has been sent. Includes a `trace_id` for debugging. |

961| `audio.clear` | Confirms that the current utterance was cancelled in response to `text.clear`. The connection is ready for the next utterance. |1087| `audio.clear` | Confirms that the current utterance was cancelled in response to `text.clear`. The connection is ready for the next utterance. |

1088| `session.updated` | Acknowledges a `session.update` and echoes the `replace` map now in effect. |

962| `error` | An error occurred. The `message` field contains a human-readable description. |1089| `error` | An error occurred. The `message` field contains a human-readable description. |

963 1090 

1091### Session Configuration

1092 

1093[Pronunciation replacements](#pronunciation-replacements) are configured with a `session.update` message. Send it before the first `text.delta` to have it cover the whole connection:

1094 

1095```json

1096{"type": "session.update", "replace": {"Acme Mobile": "Acme Mobull"}}

1097{"type": "text.delta", "delta": "Welcome to Acme Mobile."}

1098{"type": "text.done"}

1099```

1100 

1101The server replies with `{"type": "session.updated", "replace": {...}}` echoing the map now in effect. Values may be respellings or [IPA](#phonetic-pronunciations-with-ipa), exactly as over HTTP.

1102 

1103The map applies to **every utterance** for the life of the connection, including after `text.clear`. Send another `session.update` at any point to change it; no reconnect needed. Which utterance it reaches is decided by arrival:

1104 

1105> An utterance is spoken with the map that was in effect when its **first text** arrived.

1106 

1107An update landing mid-utterance therefore takes effect on the next one, so a phrase is never matched under two maps.

1108 

1109Matching runs across `text.delta` boundaries, so a phrase split over two messages still matches.

1110 

1111The [same map limits](#map-limits) apply. A map that fails validation is answered with an `error` frame, leaves the map in effect unchanged, and keeps the connection open — but a map that expands a turn past 60,000 characters ends the session, since by then the oversized text has already been accepted.

1112 

964### Multi-Utterance Sessions1113### Multi-Utterance Sessions

965 1114 

966The connection stays open after `audio.done`. You can immediately send another round of `text.delta` → `text.done` messages to synthesize additional text without reconnecting. This is useful for conversational UIs where you generate audio for each assistant response in sequence.1115The connection stays open after `audio.done`. You can immediately send another round of `text.delta` → `text.done` messages to synthesize additional text without reconnecting. This is useful for conversational UIs where you generate audio for each assistant response in sequence.


1290| **Delta size** | Individual `text.delta` messages capped at 15,000 characters |1439| **Delta size** | Individual `text.delta` messages capped at 15,000 characters |

1291| **Concurrent sessions** | 50 per team |1440| **Concurrent sessions** | 50 per team |

1292| **Session permit TTL** | 600 seconds |1441| **Session permit TTL** | 600 seconds |

1442| **[`replace`](#map-limits) expansion** | An utterance whose text exceeds 60,000 characters after substitution ends the session |

1293| **Moderation** | Runs asynchronously on accumulated text after audio is sent (fail-open) |1443| **Moderation** | Runs asynchronously on accumulated text after audio is sent (fail-open) |

1294| **Billing** | Recorded per session based on total input characters |1444| **Billing** | Recorded per session based on total input characters |

1295 1445 

Details

34client = Client(api_key=os.getenv("XAI_API_KEY"))34client = Client(api_key=os.getenv("XAI_API_KEY"))

35 35 

36# Attach a file by public URL (or use file(file_id) for uploaded files)36# Attach a file by public URL (or use file(file_id) for uploaded files)

37chat = client.chat.create(model="grok-4.5")37chat = client.chat.create(model="grok-4.6")

38chat.append(user(38chat.append(user(

39 "What was the total revenue in this report?",39 "What was the total revenue in this report?",

40 file(url="https://docs.x.ai/assets/api-examples/documents/sales-report.txt"),40 file(url="https://docs.x.ai/assets/api-examples/documents/sales-report.txt"),


57 57 

58# Attach a file by public URL (or use file_id for uploaded files)58# Attach a file by public URL (or use file_id for uploaded files)

59response = client.responses.create(59response = client.responses.create(

60 model="grok-4.5",60 model="grok-4.6",

61 input=[61 input=[

62 {62 {

63 "role": "user",63 "role": "user",


86# Attach a file by public URL (or use file_id for uploaded files)86# Attach a file by public URL (or use file_id for uploaded files)

87chat_url = "https://api.x.ai/v1/responses"87chat_url = "https://api.x.ai/v1/responses"

88payload = {88payload = {

89 "model": "grok-4.5",89 "model": "grok-4.6",

90 "input": [90 "input": [

91 {91 {

92 "role": "user",92 "role": "user",


111 111 

112// Attach a file by public URL (or use file_id for uploaded files)112// Attach a file by public URL (or use file_id for uploaded files)

113const response = await client.responses.create({113const response = await client.responses.create({

114 model: "grok-4.5",114 model: "grok-4.6",

115 input: [115 input: [

116 {116 {

117 role: "user",117 role: "user",


133 -H "Authorization: Bearer $XAI_API_KEY" \\133 -H "Authorization: Bearer $XAI_API_KEY" \\

134 -H "Content-Type: application/json" \\134 -H "Content-Type: application/json" \\

135 -d '{135 -d '{

136 "model": "grok-4.5",136 "model": "grok-4.6",

137 "input": [137 "input": [

138 {138 {

139 "role": "user",139 "role": "user",


158client = Client(api_key=os.getenv("XAI_API_KEY"))158client = Client(api_key=os.getenv("XAI_API_KEY"))

159 159 

160# Attach a file by public URL (or use file(file_id) for uploaded files)160# Attach a file by public URL (or use file(file_id) for uploaded files)

161chat = client.chat.create(model="grok-4.5")161chat = client.chat.create(model="grok-4.6")

162chat.append(user(162chat.append(user(

163 "What is the weight of the XR-2000?",163 "What is the weight of the XR-2000?",

164 file(url="https://docs.x.ai/assets/api-examples/documents/product-specs.txt"),164 file(url="https://docs.x.ai/assets/api-examples/documents/product-specs.txt"),


194 194 

195// Attach a file by public URL (or use file_id for uploaded files)195// Attach a file by public URL (or use file_id for uploaded files)

196const stream = await client.responses.create({196const stream = await client.responses.create({

197 model: "grok-4.5",197 model: "grok-4.6",

198 input: [198 input: [

199 {199 {

200 role: "user",200 role: "user",


228client = Client(api_key=os.getenv("XAI_API_KEY"))228client = Client(api_key=os.getenv("XAI_API_KEY"))

229 229 

230# Attach files by public URL (or use file(file_id) for uploaded files)230# Attach files by public URL (or use file(file_id) for uploaded files)

231chat = client.chat.create(model="grok-4.5")231chat = client.chat.create(model="grok-4.6")

232chat.append(232chat.append(

233 user(233 user(

234 "Based on these documents, when did the project start, what is the budget, and how many people are on the team?",234 "Based on these documents, when did the project start, what is the budget, and how many people are on the team?",


254 254 

255// Attach files by public URL (or use file_id for uploaded files)255// Attach files by public URL (or use file_id for uploaded files)

256const response = await client.responses.create({256const response = await client.responses.create({

257 model: "grok-4.5",257 model: "grok-4.6",

258 input: [258 input: [

259 {259 {

260 role: "user",260 role: "user",


289 289 

290# Create a multi-turn conversation with encrypted content290# Create a multi-turn conversation with encrypted content

291chat = client.chat.create(291chat = client.chat.create(

292 model="grok-4.5",292 model="grok-4.6",

293 use_encrypted_content=True, # Enable encrypted content for efficient multi-turn293 use_encrypted_content=True, # Enable encrypted content for efficient multi-turn

294)294)

295 295 


333 333 

334// First turn: Ask about the document334// First turn: Ask about the document

335const response1 = await client.responses.create({335const response1 = await client.responses.create({

336 model: "grok-4.5",336 model: "grok-4.6",

337 input: [337 input: [

338 {338 {

339 role: "user",339 role: "user",


350 350 

351// Second turn: Ask about department (uses previous_response_id for context)351// Second turn: Ask about department (uses previous_response_id for context)

352const response2 = await client.responses.create({352const response2 = await client.responses.create({

353 model: "grok-4.5",353 model: "grok-4.6",

354 previous_response_id: response1.id,354 previous_response_id: response1.id,

355 input: [355 input: [

356 { role: "user", content: "What department does this employee work in?" },356 { role: "user", content: "What department does this employee work in?" },


362 362 

363// Third turn: Ask about skills363// Third turn: Ask about skills

364const response3 = await client.responses.create({364const response3 = await client.responses.create({

365 model: "grok-4.5",365 model: "grok-4.6",

366 previous_response_id: response2.id,366 previous_response_id: response2.id,

367 input: [367 input: [

368 { role: "user", content: "What skills does this employee have?" },368 { role: "user", content: "What skills does this employee have?" },


385client = Client(api_key=os.getenv("XAI_API_KEY"))385client = Client(api_key=os.getenv("XAI_API_KEY"))

386 386 

387# Attach files by public URL (or use file(file_id) for uploaded files)387# Attach files by public URL (or use file(file_id) for uploaded files)

388chat = client.chat.create(model="grok-4.5")388chat = client.chat.create(model="grok-4.6")

389chat.append(389chat.append(

390 user(390 user(

391 "Based on the attached care guide, do you have any advice about the pictured cat?",391 "Based on the attached care guide, do you have any advice about the pictured cat?",


409 409 

410// Attach files by public URL (or use file_id for uploaded files)410// Attach files by public URL (or use file_id for uploaded files)

411const response = await client.responses.create({411const response = await client.responses.create({

412 model: "grok-4.5",412 model: "grok-4.6",

413 input: [413 input: [

414 {414 {

415 role: "user",415 role: "user",


446 446 

447# Attach a file by public URL (or use file(file_id) for uploaded files)447# Attach a file by public URL (or use file(file_id) for uploaded files)

448chat = client.chat.create(448chat = client.chat.create(

449 model="grok-4.5",449 model="grok-4.6",

450 tools=[code_execution()], # Enable code execution450 tools=[code_execution()], # Enable code execution

451)451)

452 452 


487 487 

488// Attach a file by public URL (or use file_id for uploaded files)488// Attach a file by public URL (or use file_id for uploaded files)

489const stream = await client.responses.create({489const stream = await client.responses.create({

490 model: "grok-4.5",490 model: "grok-4.6",

491 input: [491 input: [

492 {492 {

493 role: "user",493 role: "user",


538 538 

539### Model Compatibility539### Model Compatibility

540 540 

541* **Recommended model**: `grok-4.5` for best document understanding541* **Recommended model**: `grok-4.6` for best document understanding

542* **Agentic requirement**: File attachments require [agentic-capable](/developers/tools/overview) models that support server-side tools.542* **Agentic requirement**: File attachments require [agentic-capable](/developers/tools/overview) models that support server-side tools.

543 543 

544## Next Steps544## Next Steps

Details

58)58)

59 59 

60image_url = "https://science.nasa.gov/wp-content/uploads/2023/09/web-first-images-release.png"60image_url = "https://science.nasa.gov/wp-content/uploads/2023/09/web-first-images-release.png"

61chat = client.chat.create(model="grok-4.5")61chat = client.chat.create(model="grok-4.6")

62chat.append(62chat.append(

63 user(63 user(

64 "What's in this image?",64 "What's in this image?",


89)89)

90 90 

91response = client.responses.create(91response = client.responses.create(

92 model="grok-4.5",92 model="grok-4.6",

93 input=[93 input=[

94 {94 {

95 "role": "user",95 "role": "user",


128 "https://science.nasa.gov/wp-content/uploads/2023/09/web-first-images-release.png";128 "https://science.nasa.gov/wp-content/uploads/2023/09/web-first-images-release.png";

129 129 

130const response = await client.responses.create({130const response = await client.responses.create({

131 model: "grok-4.5",131 model: "grok-4.6",

132 input: [132 input: [

133 {133 {

134 role: "user",134 role: "user",


158import { generateText } from 'ai';158import { generateText } from 'ai';

159 159 

160const { text, response } = await generateText({160const { text, response } = await generateText({

161 model: xai.responses('grok-4.5'),161 model: xai.responses('grok-4.6'),

162 messages: [162 messages: [

163 {163 {

164 role: 'user',164 role: 'user',


188 -H "Authorization: Bearer $XAI_API_KEY" \188 -H "Authorization: Bearer $XAI_API_KEY" \

189 -m 3600 \189 -m 3600 \

190 -d '{190 -d '{

191 "model": "grok-4.5",191 "model": "grok-4.6",

192 "input": [192 "input": [

193 {193 {

194 "role": "user",194 "role": "user",

Details

33 timeout=3600, # Override default timeout with longer timeout for reasoning models33 timeout=3600, # Override default timeout with longer timeout for reasoning models

34)34)

35 35 

36chat = client.chat.create(model="grok-4.5")36chat = client.chat.create(model="grok-4.6")

37chat.append(system("You are a PhD-level mathematician."))37chat.append(system("You are a PhD-level mathematician."))

38chat.append(user("What is 2 + 2?"))38chat.append(user("What is 2 + 2?"))

39 39 


53)53)

54 54 

55completion = client.chat.completions.create(55completion = client.chat.completions.create(

56 model="grok-4.5",56 model="grok-4.6",

57 messages=[57 messages=[

58 {"role": "system", "content": "You are a PhD-level mathematician."},58 {"role": "system", "content": "You are a PhD-level mathematician."},

59 {"role": "user", "content": "What is 2 + 2?"},59 {"role": "user", "content": "What is 2 + 2?"},


73});73});

74 74 

75const completion = await client.chat.completions.create({75const completion = await client.chat.completions.create({

76 model: "grok-4.5",76 model: "grok-4.6",

77 messages: [77 messages: [

78 {78 {

79 role: "system",79 role: "system",


94import { generateText } from 'ai';94import { generateText } from 'ai';

95 95 

96const result = await generateText({96const result = await generateText({

97 model: xai('grok-4.5'),97 model: xai('grok-4.6'),

98 system:98 system:

99 "You are Grok, a helpful and maximally truthful AI built by xAI.",99 "You are Grok, a helpful and maximally truthful AI built by xAI.",

100 prompt: 'Explain how neural networks learn in two sentences.',100 prompt: 'Explain how neural networks learn in two sentences.',


119 "content": "Explain how neural networks learn in two sentences."119 "content": "Explain how neural networks learn in two sentences."

120 }120 }

121 ],121 ],

122 "model": "grok-4.5",122 "model": "grok-4.6",

123 "stream": false123 "stream": false

124}'124}'

125```125```


169 "id": "0daf962f-a275-4a3c-839a-047854645532",169 "id": "0daf962f-a275-4a3c-839a-047854645532",

170 "object": "chat.completion",170 "object": "chat.completion",

171 "created": 1739301120,171 "created": 1739301120,

172 "model": "grok-4.5",172 "model": "grok-4.6",

173 "choices": [173 "choices": [

174 {174 {

175 "index": 0,175 "index": 0,

Details

34 timeout=3600,34 timeout=3600,

35)35)

36 36 

37chat = client.chat.create(model="grok-4.5")37chat = client.chat.create(model="grok-4.6")

38chat.append(system("You are Grok, an AI agent built to answer helpful questions."))38chat.append(system("You are Grok, an AI agent built to answer helpful questions."))

39chat.append(user("How big is the universe?"))39chat.append(user("How big is the universe?"))

40response = chat.sample()40response = chat.sample()


58)58)

59 59 

60response = client.responses.create(60response = client.responses.create(

61 model="grok-4.5",61 model="grok-4.6",

62 input=[62 input=[

63 {"role": "system", "content": "You are Grok, an AI agent built to answer helpful questions."},63 {"role": "system", "content": "You are Grok, an AI agent built to answer helpful questions."},

64 {"role": "user", "content": "How big is the universe?"},64 {"role": "user", "content": "How big is the universe?"},


82});82});

83 83 

84const response = await client.responses.create({84const response = await client.responses.create({

85 model: "grok-4.5",85 model: "grok-4.6",

86 input: [86 input: [

87 {87 {

88 role: "system",88 role: "system",


106import { generateText } from 'ai';106import { generateText } from 'ai';

107 107 

108const { text, response } = await generateText({108const { text, response } = await generateText({

109 model: xai.responses('grok-4.5'),109 model: xai.responses('grok-4.6'),

110 system: "You are Grok, an AI agent built to answer helpful questions.",110 system: "You are Grok, an AI agent built to answer helpful questions.",

111 prompt: "How big is the universe?",111 prompt: "How big is the universe?",

112});112});


123 -H "Authorization: Bearer $XAI_API_KEY" \123 -H "Authorization: Bearer $XAI_API_KEY" \

124 -m 3600 \124 -m 3600 \

125 -d '{125 -d '{

126 "model": "grok-4.5",126 "model": "grok-4.6",

127 "input": [127 "input": [

128 {128 {

129 "role": "system",129 "role": "system",


152 timeout=3600,152 timeout=3600,

153)153)

154 154 

155chat = client.chat.create(model="grok-4.5", store_messages=False)155chat = client.chat.create(model="grok-4.6", store_messages=False)

156chat.append(system("You are Grok, an AI agent built to answer helpful questions."))156chat.append(system("You are Grok, an AI agent built to answer helpful questions."))

157chat.append(user("How big is the universe?"))157chat.append(user("How big is the universe?"))

158response = chat.sample()158response = chat.sample()


172)172)

173 173 

174response = client.responses.create(174response = client.responses.create(

175 model="grok-4.5",175 model="grok-4.6",

176 input=[176 input=[

177 {"role": "system", "content": "You are Grok, an AI agent built to answer helpful questions."},177 {"role": "system", "content": "You are Grok, an AI agent built to answer helpful questions."},

178 {"role": "user", "content": "How big is the universe?"},178 {"role": "user", "content": "How big is the universe?"},


193});193});

194 194 

195const response = await client.responses.create({195const response = await client.responses.create({

196 model: "grok-4.5",196 model: "grok-4.6",

197 input: [197 input: [

198 {198 {

199 role: "system",199 role: "system",


216 -H "Authorization: Bearer $XAI_API_KEY" \216 -H "Authorization: Bearer $XAI_API_KEY" \

217 -m 3600 \217 -m 3600 \

218 -d '{218 -d '{

219 "model": "grok-4.5",219 "model": "grok-4.6",

220 "input": [220 "input": [

221 {221 {

222 "role": "system",222 "role": "system",


242Modify the steps to create a chat client (xAI SDK) or change the request body as following:242Modify the steps to create a chat client (xAI SDK) or change the request body as following:

243 243 

244```python customLanguage="pythonXAI"244```python customLanguage="pythonXAI"

245chat = client.chat.create(model="grok-4.5",245chat = client.chat.create(model="grok-4.6",

246 use_encrypted_content=True)246 use_encrypted_content=True)

247```247```

248 248 

249```python customLanguage="pythonOpenAISDK"249```python customLanguage="pythonOpenAISDK"

250response = client.responses.create(250response = client.responses.create(

251 model="grok-4.5",251 model="grok-4.6",

252 input=[252 input=[

253 {"role": "system", "content": "You are Grok, an AI agent built to answer helpful questions."},253 {"role": "system", "content": "You are Grok, an AI agent built to answer helpful questions."},

254 {"role": "user", "content": "How big is the universe?"},254 {"role": "user", "content": "How big is the universe?"},


259 259 

260```javascript customLanguage="javascriptWithoutSDK"260```javascript customLanguage="javascriptWithoutSDK"

261const response = await client.responses.create({261const response = await client.responses.create({

262 model: "grok-4.5",262 model: "grok-4.6",

263 input: [263 input: [

264 {"role": "system", "content": "You are Grok, an AI agent built to answer helpful questions."},264 {"role": "system", "content": "You are Grok, an AI agent built to answer helpful questions."},

265 {"role": "user", "content": "How big is the universe?"},265 {"role": "user", "content": "How big is the universe?"},


276// Encrypted reasoning content is included automatically by the AI SDK276// Encrypted reasoning content is included automatically by the AI SDK

277// as long as `store: false` is not set. No extra configuration is needed.277// as long as `store: false` is not set. No extra configuration is needed.

278const { text, reasoning } = await generateText({278const { text, reasoning } = await generateText({

279 model: xai.responses('grok-4.5'),279 model: xai.responses('grok-4.6'),

280 system: "You are Grok, an AI agent built to answer helpful questions.",280 system: "You are Grok, an AI agent built to answer helpful questions.",

281 prompt: "How big is the universe?",281 prompt: "How big is the universe?",

282});282});


291 -H "Authorization: Bearer $XAI_API_KEY" \291 -H "Authorization: Bearer $XAI_API_KEY" \

292 -m 3600 \292 -m 3600 \

293 -d '{293 -d '{

294 "model": "grok-4.5",294 "model": "grok-4.6",

295 "input": [295 "input": [

296 {296 {

297 "role": "system",297 "role": "system",


325 timeout=3600,325 timeout=3600,

326)326)

327 327 

328chat = client.chat.create(model="grok-4.5", store_messages=True)328chat = client.chat.create(model="grok-4.6", store_messages=True)

329chat.append(system("You are Grok, an AI agent built to answer helpful questions."))329chat.append(system("You are Grok, an AI agent built to answer helpful questions."))

330chat.append(user("How big is the universe?"))330chat.append(user("How big is the universe?"))

331response = chat.sample()331response = chat.sample()


339# New steps339# New steps

340 340 

341chat = client.chat.create(341chat = client.chat.create(

342 model="grok-4.5",342 model="grok-4.6",

343 previous_response_id=response.id,343 previous_response_id=response.id,

344 store_messages=True,344 store_messages=True,

345)345)


366)366)

367 367 

368response = client.responses.create(368response = client.responses.create(

369 model="grok-4.5",369 model="grok-4.6",

370 input=[370 input=[

371 {"role": "system", "content": "You are Grok, an AI agent built to answer helpful questions."},371 {"role": "system", "content": "You are Grok, an AI agent built to answer helpful questions."},

372 {"role": "user", "content": "How big is the universe?"},372 {"role": "user", "content": "How big is the universe?"},


382# New steps382# New steps

383 383 

384second_response = client.responses.create(384second_response = client.responses.create(

385 model="grok-4.5",385 model="grok-4.6",

386 previous_response_id=response.id,386 previous_response_id=response.id,

387 input=[387 input=[

388 {"role": "user", "content": "How do stars form?"},388 {"role": "user", "content": "How do stars form?"},


407});407});

408 408 

409const response = await client.responses.create({409const response = await client.responses.create({

410 model: "grok-4.5",410 model: "grok-4.6",

411 input: [411 input: [

412 {412 {

413 role: "system",413 role: "system",


426console.log(response.id);426console.log(response.id);

427 427 

428const secondResponse = await client.responses.create({428const secondResponse = await client.responses.create({

429 model: "grok-4.5",429 model: "grok-4.6",

430 previous_response_id: response.id,430 previous_response_id: response.id,

431 input: [431 input: [

432 {"role": "user", "content": "How do stars form?"},432 {"role": "user", "content": "How do stars form?"},


445 445 

446// First request446// First request

447const result = await generateText({447const result = await generateText({

448 model: xai.responses('grok-4.5'),448 model: xai.responses('grok-4.6'),

449 system: "You are Grok, an AI agent built to answer helpful questions.",449 system: "You are Grok, an AI agent built to answer helpful questions.",

450 prompt: "How big is the universe?",450 prompt: "How big is the universe?",

451});451});


457 457 

458// Continue the conversation using previousResponseId458// Continue the conversation using previousResponseId

459const { text: secondResponse } = await generateText({459const { text: secondResponse } = await generateText({

460 model: xai.responses('grok-4.5'),460 model: xai.responses('grok-4.6'),

461 prompt: "How do stars form?",461 prompt: "How do stars form?",

462 providerOptions: {462 providerOptions: {

463 xai: {463 xai: {


475 -H "Authorization: Bearer $XAI_API_KEY" \475 -H "Authorization: Bearer $XAI_API_KEY" \

476 -m 3600 \476 -m 3600 \

477 -d '{477 -d '{

478 "model": "grok-4.5",478 "model": "grok-4.6",

479 "previous_response_id": "The previous response ID",479 "previous_response_id": "The previous response ID",

480 "input": [480 "input": [

481 {481 {


505 timeout=3600,505 timeout=3600,

506)506)

507 507 

508chat = client.chat.create(model="grok-4.5", store_messages=True, use_encrypted_content=True)508chat = client.chat.create(model="grok-4.6", store_messages=True, use_encrypted_content=True)

509chat.append(system("You are Grok, an AI agent built to answer helpful questions."))509chat.append(system("You are Grok, an AI agent built to answer helpful questions."))

510chat.append(user("How big is the universe?"))510chat.append(user("How big is the universe?"))

511response = chat.sample()511response = chat.sample()


543)543)

544 544 

545response = client.responses.create(545response = client.responses.create(

546 model="grok-4.5",546 model="grok-4.6",

547 input=[547 input=[

548 {"role": "system", "content": "You are Grok, an AI agent built to answer helpful questions."},548 {"role": "system", "content": "You are Grok, an AI agent built to answer helpful questions."},

549 {"role": "user", "content": "How big is the universe?"},549 {"role": "user", "content": "How big is the universe?"},


560# New steps560# New steps

561 561 

562second_response = client.responses.create(562second_response = client.responses.create(

563 model="grok-4.5",563 model="grok-4.6",

564 input=[564 input=[

565 *response.output, # Use response.output instead of the stored response565 *response.output, # Use response.output instead of the stored response

566 {"role": "user", "content": "How do stars form?"},566 {"role": "user", "content": "How do stars form?"},


585});585});

586 586 

587const response = await client.responses.create({587const response = await client.responses.create({

588 model: "grok-4.5",588 model: "grok-4.6",

589 input: [589 input: [

590 {590 {

591 role: "system",591 role: "system",


605console.log(response.id);605console.log(response.id);

606 606 

607const secondResponse = await client.responses.create({607const secondResponse = await client.responses.create({

608 model: "grok-4.5",608 model: "grok-4.6",

609 input: [609 input: [

610 ...response.output, // Use response.output instead of the stored response610 ...response.output, // Use response.output instead of the stored response

611 {"role": "user", "content": "How do stars form?"},611 {"role": "user", "content": "How do stars form?"},


625// First request. Encrypted reasoning content is included automatically625// First request. Encrypted reasoning content is included automatically

626// by the AI SDK as long as `store: false` is not set.626// by the AI SDK as long as `store: false` is not set.

627const result = await generateText({627const result = await generateText({

628 model: xai.responses('grok-4.5'),628 model: xai.responses('grok-4.6'),

629 system: "You are Grok, an AI agent built to answer helpful questions.",629 system: "You are Grok, an AI agent built to answer helpful questions.",

630 prompt: "How big is the universe?",630 prompt: "How big is the universe?",

631});631});


635// Continue the conversation using previousResponseId635// Continue the conversation using previousResponseId

636// The encrypted content is automatically included when using previousResponseId636// The encrypted content is automatically included when using previousResponseId

637const { text: secondResponse } = await generateText({637const { text: secondResponse } = await generateText({

638 model: xai.responses('grok-4.5'),638 model: xai.responses('grok-4.6'),

639 prompt: "How do stars form?",639 prompt: "How do stars form?",

640 providerOptions: {640 providerOptions: {

641 xai: {641 xai: {


653 -H "Authorization: Bearer $XAI_API_KEY" \653 -H "Authorization: Bearer $XAI_API_KEY" \

654 -m 3600 \654 -m 3600 \

655 -d '{655 -d '{

656 "model": "grok-4.5",656 "model": "grok-4.6",

657 "input": [657 "input": [

658 {658 {

659 "role": "system",659 "role": "system",

Details

18 18 

19## The `reasoning_effort` parameter19## The `reasoning_effort` parameter

20 20 

21`grok-4.5` supports the `reasoning_effort` parameter, which controls how much effort the model spends thinking before responding.21`grok-4.6` and `grok-4.5` support the `reasoning_effort` parameter, which controls how much effort the model spends thinking before responding.

22 22 

23If not specified, `reasoning_effort` defaults to `"high"`. Reasoning cannot be disabled.23If not specified, `reasoning_effort` defaults to `"high"`. Reasoning cannot be disabled.

24 24 


31| `"low"` | Uses some reasoning tokens, but still fast | Latency-sensitive agentic use and simple tool calling. |31| `"low"` | Uses some reasoning tokens, but still fast | Latency-sensitive agentic use and simple tool calling. |

32| `"medium"` | More thinking for less-latency sensitive applications | Complex data analysis and long-context reasoning. |32| `"medium"` | More thinking for less-latency sensitive applications | Complex data analysis and long-context reasoning. |

33| `"high"` (default) | Uses more reasoning tokens for deeper thinking | Very challenging problems, complex math, multi-step logic, competition-level tasks |33| `"high"` (default) | Uses more reasoning tokens for deeper thinking | Very challenging problems, complex math, multi-step logic, competition-level tasks |

34| `"xhigh"` | Maximum reasoning depth, with correspondingly higher latency | The hardest problems, where answer quality matters more than response time |

35 

36> [!TIP]

37>

38> `"xhigh"` is available on `grok-4.6` and later. On models that do not support it, such as `grok-4.5`, requests with `"xhigh"` are treated as `"high"`.

34 39 

35### Setting reasoning effort40### Setting reasoning effort

36 41 

37The following example sets `reasoning_effort` to `"high"` for a challenging math proof. You can substitute `"low"` or `"medium"` as needed.42The following example sets `reasoning_effort` to `"high"` for a challenging math proof. You can substitute `"low"`, `"medium"`, or (on supported models) `"xhigh"` as needed.

38 43 

39```python customLanguage="pythonXAI" highlightedLines="13"44```python customLanguage="pythonXAI" highlightedLines="13"

40import os45import os


48)53)

49 54 

50chat = client.chat.create(55chat = client.chat.create(

51 model="grok-4.5",56 model="grok-4.6",

52 reasoning_effort="high",57 reasoning_effort="high",

53 messages=[system("You are a highly intelligent AI assistant.")],58 messages=[system("You are a highly intelligent AI assistant.")],

54)59)


72)77)

73 78 

74response = client.responses.create(79response = client.responses.create(

75 model="grok-4.5",80 model="grok-4.6",

76 reasoning={"effort": "high"},81 reasoning={"effort": "high"},

77 input=[82 input=[

78 {"role": "system", "content": "You are a highly intelligent AI assistant."},83 {"role": "system", "content": "You are a highly intelligent AI assistant."},


92import { generateText } from 'ai';97import { generateText } from 'ai';

93 98 

94const result = await generateText({99const result = await generateText({

95 model: xai.responses('grok-4.5'),100 model: xai.responses('grok-4.6'),

96 system: 'You are a highly intelligent AI assistant.',101 system: 'You are a highly intelligent AI assistant.',

97 prompt: 'Find all prime numbers p such that p^2 + 2 is also prime. Prove your answer.',102 prompt: 'Find all prime numbers p such that p^2 + 2 is also prime. Prove your answer.',

98 providerOptions: {103 providerOptions: {


109 -H "Authorization: Bearer $XAI_API_KEY" \114 -H "Authorization: Bearer $XAI_API_KEY" \

110 -m 3600 \115 -m 3600 \

111 -d '{116 -d '{

112 "model": "grok-4.5",117 "model": "grok-4.6",

113 "reasoning": {"effort": "high"},118 "reasoning": {"effort": "high"},

114 "input": [119 "input": [

115 {120 {


132 137 

133| Model | `reasoning` parameter | Behavior |138| Model | `reasoning` parameter | Behavior |

134|---|---|---|139|---|---|---|

140| `grok-4.6` | `reasoning.effort`: `"low"` / `"medium"` / `"high"` (default) / `"xhigh"` | Controls reasoning depth (cannot be disabled) |

135| `grok-4.5` | `reasoning.effort`: `"low"` / `"medium"` / `"high"` (default) | Controls reasoning depth (cannot be disabled) |141| `grok-4.5` | `reasoning.effort`: `"low"` / `"medium"` / `"high"` (default) | Controls reasoning depth (cannot be disabled) |

136| `grok-4.20-multi-agent` | `reasoning.effort`: `"low"` / `"medium"` / `"high"` / `"xhigh"` | Controls agent count (4 or 16) |142| `grok-4.20-multi-agent` | `reasoning.effort`: `"low"` / `"medium"` / `"high"` / `"xhigh"` | Controls agent count (4 or 16) |

137 143 

138## Summarized Reasoning Content144## Summarized Reasoning Content

139 145 

140For `grok-4.5`, we expose summarizations of the model's internal reasoning. Here's an example of how to stream the reasoning summary deltas alongside the final response:146For `grok-4.6`, we expose summarizations of the model's internal reasoning. Here's an example of how to stream the reasoning summary deltas alongside the final response:

141 147 

142```python customLanguage="pythonXAI"148```python customLanguage="pythonXAI"

143import os149import os


151)157)

152 158 

153chat = client.chat.create(159chat = client.chat.create(

154 model="grok-4.5",160 model="grok-4.6",

155 messages=[system("You are a highly intelligent AI assistant.")],161 messages=[system("You are a highly intelligent AI assistant.")],

156)162)

157chat.append(user("A projectile is launched at 30 m/s at 37° above horizontal from a 45 m cliff. Find its speed on impact. (g=10 m/s²)"))163chat.append(user("A projectile is launched at 30 m/s at 37° above horizontal from a 45 m cliff. Find its speed on impact. (g=10 m/s²)"))


178)184)

179 185 

180stream = client.responses.create(186stream = client.responses.create(

181 model="grok-4.5",187 model="grok-4.6",

182 input=[188 input=[

183 {"role": "system", "content": "You are a highly intelligent AI assistant."},189 {"role": "system", "content": "You are a highly intelligent AI assistant."},

184 {"role": "user", "content": "A projectile is launched at 30 m/s at 37° above horizontal from a 45 m cliff. Find its speed on impact. (g=10 m/s²)"},190 {"role": "user", "content": "A projectile is launched at 30 m/s at 37° above horizontal from a 45 m cliff. Find its speed on impact. (g=10 m/s²)"},


197import { streamText } from 'ai';203import { streamText } from 'ai';

198 204 

199const result = streamText({205const result = streamText({

200 model: xai.responses('grok-4.5'),206 model: xai.responses('grok-4.6'),

201 system: 'You are a highly intelligent AI assistant.',207 system: 'You are a highly intelligent AI assistant.',

202 prompt: 'A projectile is launched at 30 m/s at 37° above horizontal from a 45 m cliff. Find its speed on impact. (g=10 m/s²)'208 prompt: 'A projectile is launched at 30 m/s at 37° above horizontal from a 45 m cliff. Find its speed on impact. (g=10 m/s²)'

203});209});


227 "content": "A ball is thrown upward at 25 m/s from the top of a 60 m building. Find the maximum height above the ground. (g=10 m/s²)"233 "content": "A ball is thrown upward at 25 m/s from the top of a 60 m building. Find the maximum height above the ground. (g=10 m/s²)"

228 }234 }

229 ],235 ],

230 "model": "grok-4.5",236 "model": "grok-4.6",

231 "stream": true237 "stream": true

232}'238}'

233```239```

Details

26 timeout=3600, # Override default timeout with longer timeout for reasoning models26 timeout=3600, # Override default timeout with longer timeout for reasoning models

27)27)

28 28 

29chat = client.chat.create(model="grok-4.5")29chat = client.chat.create(model="grok-4.6")

30chat.append(30chat.append(

31 system("You are Grok, a helpful and maximally truthful AI built by xAI."),31 system("You are Grok, a helpful and maximally truthful AI built by xAI."),

32)32)


53)53)

54 54 

55stream = client.chat.completions.create(55stream = client.chat.completions.create(

56 model="grok-4.5",56 model="grok-4.6",

57 messages=[57 messages=[

58 {"role": "system", "content": "You are Grok, a helpful and maximally truthful AI built by xAI."},58 {"role": "system", "content": "You are Grok, a helpful and maximally truthful AI built by xAI."},

59 {"role": "user", "content": "Explain how neural networks learn in two sentences."},59 {"role": "user", "content": "Explain how neural networks learn in two sentences."},


74});74});

75 75 

76const stream = await openai.chat.completions.create({76const stream = await openai.chat.completions.create({

77 model: "grok-4.5",77 model: "grok-4.6",

78 messages: [78 messages: [

79 { role: "system", content: "You are Grok, a helpful and maximally truthful AI built by xAI." },79 { role: "system", content: "You are Grok, a helpful and maximally truthful AI built by xAI." },

80 {80 {


95import { streamText } from 'ai';95import { streamText } from 'ai';

96 96 

97const result = streamText({97const result = streamText({

98 model: xai.responses('grok-4.5'),98 model: xai.responses('grok-4.6'),

99 system:99 system:

100 "You are Grok, a helpful and maximally truthful AI built by xAI.",100 "You are Grok, a helpful and maximally truthful AI built by xAI.",

101 prompt: 'Explain how neural networks learn in two sentences.',101 prompt: 'Explain how neural networks learn in two sentences.',


122 "content": "Explain how neural networks learn in two sentences."122 "content": "Explain how neural networks learn in two sentences."

123 }123 }

124 ],124 ],

125 "model": "grok-4.5",125 "model": "grok-4.6",

126 "stream": true126 "stream": true

127}'127}'

128```128```


132```json132```json

133data: {133data: {

134 "id":"<completion_id>","object":"chat.completion.chunk","created":<creation_time>,134 "id":"<completion_id>","object":"chat.completion.chunk","created":<creation_time>,

135 "model":"grok-4.5",135 "model":"grok-4.6",

136 "choices":[{"index":0,"delta":{"content":"Ah","role":"assistant"}}],136 "choices":[{"index":0,"delta":{"content":"Ah","role":"assistant"}}],

137 "usage":{"prompt_tokens":41,"completion_tokens":1,"total_tokens":42,137 "usage":{"prompt_tokens":41,"completion_tokens":1,"total_tokens":42,

138 "prompt_tokens_details":{"text_tokens":41,"audio_tokens":0,"image_tokens":0,"cached_tokens":0}},138 "prompt_tokens_details":{"text_tokens":41,"audio_tokens":0,"image_tokens":0,"cached_tokens":0}},


141 141 

142data: {142data: {

143 "id":"<completion_id>","object":"chat.completion.chunk","created":<creation_time>,143 "id":"<completion_id>","object":"chat.completion.chunk","created":<creation_time>,

144 "model":"grok-4.5",144 "model":"grok-4.6",

145 "choices":[{"index":0,"delta":{"content":",","role":"assistant"}}],145 "choices":[{"index":0,"delta":{"content":",","role":"assistant"}}],

146 "usage":{"prompt_tokens":41,"completion_tokens":2,"total_tokens":43,146 "usage":{"prompt_tokens":41,"completion_tokens":2,"total_tokens":43,

147 "prompt_tokens_details":{"text_tokens":41,"audio_tokens":0,"image_tokens":0,"cached_tokens":0}},147 "prompt_tokens_details":{"text_tokens":41,"audio_tokens":0,"image_tokens":0,"cached_tokens":0}},

Details

264 currency: Currency = Field(description="Currency of the invoice")264 currency: Currency = Field(description="Currency of the invoice")

265 265 

266client = Client(api_key=os.getenv("XAI_API_KEY"))266client = Client(api_key=os.getenv("XAI_API_KEY"))

267chat = client.chat.create(model="grok-4.5")267chat = client.chat.create(model="grok-4.6")

268 268 

269chat.append(system("Given a raw invoice, carefully analyze the text and extract the invoice data into JSON format."))269chat.append(system("Given a raw invoice, carefully analyze the text and extract the invoice data into JSON format."))

270chat.append(270chat.append(


338)338)

339 339 

340completion = client.beta.chat.completions.parse(340completion = client.beta.chat.completions.parse(

341 model="grok-4.5",341 model="grok-4.6",

342 messages=[342 messages=[

343 {"role": "system", "content": "Given a raw invoice, carefully analyze the text and extract the invoice data into JSON format."},343 {"role": "system", "content": "Given a raw invoice, carefully analyze the text and extract the invoice data into JSON format."},

344 {"role": "user", "content": """344 {"role": "user", "content": """


395});395});

396 396 

397const completion = await client.chat.completions.parse({397const completion = await client.chat.completions.parse({

398 model: "grok-4.5",398 model: "grok-4.6",

399 messages: [399 messages: [

400 { role: "system", content: "Given a raw invoice, carefully analyze the text and extract the invoice data into JSON format." },400 { role: "system", content: "Given a raw invoice, carefully analyze the text and extract the invoice data into JSON format." },

401 { role: "user", content: \`401 { role: "user", content: \`


449});449});

450 450 

451const result = await generateText({451const result = await generateText({

452 model: xai.responses('grok-4.5'),452 model: xai.responses('grok-4.6'),

453 output: Output.object({ schema: InvoiceSchema }),453 output: Output.object({ schema: InvoiceSchema }),

454 system:454 system:

455 'Given a raw invoice, carefully analyze the text and extract the invoice data into JSON format.',455 'Given a raw invoice, carefully analyze the text and extract the invoice data into JSON format.',


542 542 

543client = Client(api_key=os.getenv("XAI_API_KEY"))543client = Client(api_key=os.getenv("XAI_API_KEY"))

544chat = client.chat.create(544chat = client.chat.create(

545 model="grok-4.5",545 model="grok-4.6",

546 tools=[web_search()],546 tools=[web_search()],

547)547)

548 548 


569)569)

570 570 

571response = client.responses.parse(571response = client.responses.parse(

572 model="grok-4.5",572 model="grok-4.6",

573 input="Find the latest machine-checked proof of the four color theorem.",573 input="Find the latest machine-checked proof of the four color theorem.",

574 tools=[574 tools=[

575 {"type": "web_search"}575 {"type": "web_search"}


600const format = zodResponseFormat(ProofInfoSchema, "proof_info");600const format = zodResponseFormat(ProofInfoSchema, "proof_info");

601 601 

602const response = await client.responses.create({602const response = await client.responses.create({

603 model: "grok-4.5",603 model: "grok-4.6",

604 input: "Find the latest machine-checked proof of the four color theorem.",604 input: "Find the latest machine-checked proof of the four color theorem.",

605 tools: [605 tools: [

606 { type: "web_search" }606 { type: "web_search" }


684 684 

685client = Client(api_key=os.getenv("XAI_API_KEY"))685client = Client(api_key=os.getenv("XAI_API_KEY"))

686chat = client.chat.create(686chat = client.chat.create(

687 model="grok-4.5",687 model="grok-4.6",

688 tools=[collatz_tool],688 tools=[collatz_tool],

689)689)

690 690 


755# Handle tool calls until we get a final response755# Handle tool calls until we get a final response

756while True:756while True:

757 completion = client.chat.completions.create(757 completion = client.chat.completions.create(

758 model="grok-4.5",758 model="grok-4.6",

759 messages=messages,759 messages=messages,

760 tools=tools,760 tools=tools,

761 )761 )


777 777 

778# Final call with structured output778# Final call with structured output

779completion = client.beta.chat.completions.parse(779completion = client.beta.chat.completions.parse(

780 model="grok-4.5",780 model="grok-4.6",

781 messages=messages,781 messages=messages,

782 response_format=CollatzResult,782 response_format=CollatzResult,

783)783)


830// Handle tool calls until we get a final response830// Handle tool calls until we get a final response

831while (true) {831while (true) {

832 const completion = await client.chat.completions.create({832 const completion = await client.chat.completions.create({

833 model: "grok-4.5",833 model: "grok-4.6",

834 messages,834 messages,

835 tools,835 tools,

836 });836 });


855 855 

856// Final call with structured output856// Final call with structured output

857const completion = await client.chat.completions.create({857const completion = await client.chat.completions.create({

858 model: "grok-4.5",858 model: "grok-4.6",

859 messages,859 messages,

860 response_format: {860 response_format: {

861 type: "json_schema",861 type: "json_schema",


947 947 

948# Pass the Pydantic model to response_format instead of using parse()948# Pass the Pydantic model to response_format instead of using parse()

949chat = client.chat.create(949chat = client.chat.create(

950 model="grok-4.5",950 model="grok-4.6",

951 response_format=Invoice, # Pass the Pydantic model here951 response_format=Invoice, # Pass the Pydantic model here

952)952)

953 953 


1000client = Client(api_key=os.getenv("XAI_API_KEY"))1000client = Client(api_key=os.getenv("XAI_API_KEY"))

1001 1001 

1002chat = client.chat.create(1002chat = client.chat.create(

1003 model="grok-4.5",1003 model="grok-4.6",

1004 response_format=Summary, # Pass the Pydantic model here1004 response_format=Summary, # Pass the Pydantic model here

1005)1005)

1006 1006 

quickstart.md +6 −6

Details

44 44 

45## Step 4: Make your first request45## Step 4: Make your first request

46 46 

47Send a coding prompt to [Grok Build](/build/overview) (`grok-4.5`) and get a response. The same model powers agentic coding in Grok Build and is available on the API in early access:47Send a coding prompt to [Grok Build](/build/overview) (`grok-4.6`) and get a response. The same model powers agentic coding in Grok Build and is available on the API in early access:

48 48 

49```bash49```bash

50curl https://api.x.ai/v1/responses \50curl https://api.x.ai/v1/responses \

51 -H "Authorization: Bearer $XAI_API_KEY" \51 -H "Authorization: Bearer $XAI_API_KEY" \

52 -H "Content-Type: application/json" \52 -H "Content-Type: application/json" \

53 -d '{53 -d '{

54 "model": "grok-4.5",54 "model": "grok-4.6",

55 "input": "Fix this function and explain the bug: function median(a){a.sort();return a[a.length/2]}"55 "input": "Fix this function and explain the bug: function median(a){a.sort();return a[a.length/2]}"

56 }'56 }'

57```57```


63 63 

64client = Client(api_key=os.getenv("XAI_API_KEY"))64client = Client(api_key=os.getenv("XAI_API_KEY"))

65 65 

66chat = client.chat.create(model="grok-4.5")66chat = client.chat.create(model="grok-4.6")

67chat.append(user("Fix this function and explain the bug: function median(a){a.sort();return a[a.length/2]}"))67chat.append(user("Fix this function and explain the bug: function median(a){a.sort();return a[a.length/2]}"))

68 68 

69print(chat.sample().content)69print(chat.sample().content)


78)78)

79 79 

80response = client.responses.create(80response = client.responses.create(

81 model="grok-4.5",81 model="grok-4.6",

82 input="Fix this function and explain the bug: function median(a){a.sort();return a[a.length/2]}",82 input="Fix this function and explain the bug: function median(a){a.sort();return a[a.length/2]}",

83)83)

84 84 


90import { generateText } from 'ai';90import { generateText } from 'ai';

91 91 

92const { text } = await generateText({92const { text } = await generateText({

93 model: xai.responses('grok-4.5'),93 model: xai.responses('grok-4.6'),

94 prompt: 'Fix this function and explain the bug: function median(a){a.sort();return a[a.length/2]}',94 prompt: 'Fix this function and explain the bug: function median(a){a.sort();return a[a.length/2]}',

95});95});

96 96 


106});106});

107 107 

108const response = await client.responses.create({108const response = await client.responses.create({

109 model: 'grok-4.5',109 model: 'grok-4.6',

110 input: 'Fix this function and explain the bug: function median(a){a.sort();return a[a.length/2]}',110 input: 'Fix this function and explain the bug: function median(a){a.sort();return a[a.length/2]}',

111});111});

112 112 

rate-limits.md +7 −6

Details

33 33 

34| Model | RPS | TPM |34| Model | RPS | TPM |

35| --- | --- | --- |35| --- | --- | --- |

36| grok-4.6 | T0: 150, T1: 172, T2: 208, T3: 312, T4: 500 | T0: 50M, T1: 53M, T2: 60M, T3: 74M, T4: 100M |

36| grok-4.5 | T0: 150, T1: 172, T2: 208, T3: 312, T4: 500 | T0: 50M, T1: 53M, T2: 60M, T3: 74M, T4: 100M |37| grok-4.5 | T0: 150, T1: 172, T2: 208, T3: 312, T4: 500 | T0: 50M, T1: 53M, T2: 60M, T3: 74M, T4: 100M |

37| grok-4.3 | T0: 37, T1: 50, T2: 75, T3: 125, T4: 208 | T0: 10M, T1: 15M, T2: 25M, T3: 45M, T4: 85M |38| grok-4.3 | T0: 37, T1: 50, T2: 75, T3: 125, T4: 208 | T0: 10M, T1: 15M, T2: 25M, T3: 45M, T4: 85M |

38| grok-4.20-0309-reasoning | T0: 37, T1: 50, T2: 75, T3: 125, T4: 208 | T0: 10M, T1: 15M, T2: 25M, T3: 45M, T4: 85M |39| grok-4.20-0309-reasoning | T0: 37, T1: 50, T2: 75, T3: 125, T4: 208 | T0: 10M, T1: 15M, T2: 25M, T3: 45M, T4: 85M |

39| grok-4.20-0309-non-reasoning | T0: 37, T1: 50, T2: 75, T3: 125, T4: 208 | T0: 10M, T1: 15M, T2: 25M, T3: 45M, T4: 85M |40| grok-4.20-0309-non-reasoning | T0: 37, T1: 50, T2: 75, T3: 125, T4: 208 | T0: 10M, T1: 15M, T2: 25M, T3: 45M, T4: 85M |

40| grok-build-0.1 | T0: 37, T1: 50, T2: 75, T3: 125, T4: 208 | T0: 10M, T1: 15M, T2: 25M, T3: 45M, T4: 85M |41| grok-build-0.1 | T0: 37, T1: 50, T2: 75, T3: 125, T4: 208 | T0: 10M, T1: 15M, T2: 25M, T3: 45M, T4: 85M |

41| grok-4.20-multi-agent-0309 | T0: 9, T1: 12, T2: 18, T3: 31, T4: 56 | T0: 2.5M, T1: 3.7M, T2: 6.2M, T3: 11M, T4: 21M |42| grok-4.20-multi-agent-0309 | T0: 9, T1: 12, T2: 18, T3: 31, T4: 56 | T0: 2.5M, T1: 3.7M, T2: 6.2M, T3: 11M, T4: 21M |

42| grok-imagine-image | 5 | — |43| grok-imagine-image | T0: 6, T1: 12, T2: 25, T3: 50, T4: 100 | — |

44| grok-imagine-image-2.0 | T0: 6, T1: 12, T2: 25, T3: 50, T4: 100 | — |

43| grok-imagine-image-quality | 5 | — |45| grok-imagine-image-quality | 5 | — |

44| grok-imagine-image-2.0 | 5 | — |46| grok-imagine-video-1.5 | T0: 10, T1: 20, T2: 39, T3: 79, T4: 158 | — |

45| grok-imagine-video-1.5 | 10 | — |47| grok-imagine-video | T0: 10, T1: 20, T2: 39, T3: 79, T4: 158 | — |

46| grok-imagine-video | 10 | — |

47 48 

48### What counts toward TPM49### What counts toward TPM

49 50 


71 for attempt in range(max_retries):72 for attempt in range(max_retries):

72 try:73 try:

73 return client.chat.completions.create(74 return client.chat.completions.create(

74 model="grok-4.5",75 model="grok-4.6",

75 messages=messages,76 messages=messages,

76 )77 )

77 except RateLimitError:78 except RateLimitError:


90client = Client(api_key=os.getenv("XAI_API_KEY"))91client = Client(api_key=os.getenv("XAI_API_KEY"))

91 92 

92def request_with_backoff(prompt, max_retries=5):93def request_with_backoff(prompt, max_retries=5):

93 chat = client.chat.create(model="grok-4.5")94 chat = client.chat.create(model="grok-4.6")

94 chat.append(user(prompt))95 chat.append(user(prompt))

95 for attempt in range(max_retries):96 for attempt in range(max_retries):

96 try:97 try:

Details

453 -H "Content-Type: application/json" \453 -H "Content-Type: application/json" \

454 -H "Authorization: Bearer $XAI_API_KEY" \454 -H "Authorization: Bearer $XAI_API_KEY" \

455 -d '{455 -d '{

456 "model": "grok-4.5",456 "model": "grok-4.6",

457 "input": "What is the meaning of life?"457 "input": "What is the meaning of life?"

458 }'458 }'

459```459```


463import { generateText } from "ai";463import { generateText } from "ai";

464 464 

465const result = await generateText({465const result = await generateText({

466 model: xai.responses("grok-4.5"),466 model: xai.responses("grok-4.6"),

467 prompt: "What is the meaning of life?",467 prompt: "What is the meaning of life?",

468});468});

469 469 


481)481)

482 482 

483response = client.responses.create(483response = client.responses.create(

484 model="grok-4.5",484 model="grok-4.6",

485 input="What is the meaning of life?",485 input="What is the meaning of life?",

486)486)

487 487 


497});497});

498 498 

499const response = await client.responses.create({499const response = await client.responses.create({

500 model: "grok-4.5",500 model: "grok-4.6",

501 input: "What is the meaning of life?",501 input: "What is the meaning of life?",

502});502});

503 503 


611 -H "Content-Type: application/json" \611 -H "Content-Type: application/json" \

612 -H "Authorization: Bearer $XAI_API_KEY" \612 -H "Authorization: Bearer $XAI_API_KEY" \

613 -d '{613 -d '{

614 "model": "grok-4.5",614 "model": "grok-4.6",

615 "input": [615 "input": [

616 {"role": "system", "content": "You are a concise and knowledgeable science tutor."},616 {"role": "system", "content": "You are a concise and knowledgeable science tutor."},

617 {"role": "user", "content": "What is the Higgs boson and why is it important?"},617 {"role": "user", "content": "What is the Higgs boson and why is it important?"},


633)633)

634 634 

635compacted = client.responses.compact(635compacted = client.responses.compact(

636 model="grok-4.5",636 model="grok-4.6",

637 input=[637 input=[

638 {"role": "system", "content": "You are a concise and knowledgeable science tutor."},638 {"role": "system", "content": "You are a concise and knowledgeable science tutor."},

639 {"role": "user", "content": "What is the Higgs boson and why is it important?"},639 {"role": "user", "content": "What is the Higgs boson and why is it important?"},


669});669});

670 670 

671const compacted = await client.responses.compact({671const compacted = await client.responses.compact({

672 model: "grok-4.5",672 model: "grok-4.6",

673 input: [673 input: [

674 { role: "system", content: "You are a concise and knowledgeable science tutor." },674 { role: "system", content: "You are a concise and knowledgeable science tutor." },

675 { role: "user", content: "What is the Higgs boson and why is it important?" },675 { role: "user", content: "What is the Higgs boson and why is it important?" },

Details

415 415 

416* `speed` (number) — Speech speed multiplier. \`1.0\` is normal speed. Values below \`1.0\` slow down speech, values above \`1.0\` speed it up. Defaults to \`1.0\` when omitted.416* `speed` (number) — Speech speed multiplier. \`1.0\` is normal speed. Values below \`1.0\` slow down speech, values above \`1.0\` speed it up. Defaults to \`1.0\` when omitted.

417 417 

418* `replace` (object) — Map of phrases to spoken substitutions applied before synthesis, e.g. \`\{"Acme Mobile": "Acme Mobull"}\`. Fixes pronunciation without changing the text you send or the characters you are billed for. A value may be a respelling or IPA phonetics written between forward slashes, e.g. \`\{"nginx": "/ˈɛndʒɪn ˈɛks/"}\` to have it spoken as "engine X"; the slashes are a readability convention and are never spoken. Matching is case-insensitive and requires whole-word boundaries; the longest match wins. Keys may contain only letters, digits, apostrophes and spaces. Up to 200 entries, keys up to 100 characters and values up to 128 characters.

419 

418### Response Body420### Response Body

419 421 

420* `audio` (string, required) — Base64-encoded audio bytes in the requested codec.422* `audio` (string, required) — Base64-encoded audio bytes in the requested codec.

Details

86 ),86 ),

87 ]87 ]

88 88 

89 model = "grok-4.5"89 model = "grok-4.6"

90 ```90 ```

91 91 

922. Perform the tool loop with conversation continuation:922. Perform the tool loop with conversation continuation:


217 # In a real app, this would query your database217 # In a real app, this would query your database

218 return f"The weather in {city} is sunny."218 return f"The weather in {city} is sunny."

219 219 

220 model = "grok-4.5"220 model = "grok-4.6"

221 tools = [221 tools = [

222 {222 {

223 "type": "function",223 "type": "function",


382client = Client(api_key=os.getenv("XAI_API_KEY"))382client = Client(api_key=os.getenv("XAI_API_KEY"))

383# First turn.383# First turn.

384chat = client.chat.create(384chat = client.chat.create(

385 model="grok-4.5", # reasoning model385 model="grok-4.6", # reasoning model

386 tools=[web_search(), x_search()],386 tools=[web_search(), x_search()],

387 store_messages=True,387 store_messages=True,

388)388)


394 394 

395# Second turn.395# Second turn.

396chat = client.chat.create(396chat = client.chat.create(

397 model="grok-4.5", # reasoning model397 model="grok-4.6", # reasoning model

398 tools=[web_search(), x_search()],398 tools=[web_search(), x_search()],

399 # pass the response id of the first turn to continue the conversation399 # pass the response id of the first turn to continue the conversation

400 previous_response_id=response.id,400 previous_response_id=response.id,


427client = Client(api_key=os.getenv("XAI_API_KEY"))427client = Client(api_key=os.getenv("XAI_API_KEY"))

428# First turn.428# First turn.

429chat = client.chat.create(429chat = client.chat.create(

430 model="grok-4.5", # reasoning model430 model="grok-4.6", # reasoning model

431 tools=[web_search(), x_search()],431 tools=[web_search(), x_search()],

432 use_encrypted_content=True,432 use_encrypted_content=True,

433)433)


512 512 

513client = Client(api_key=os.getenv("XAI_API_KEY"))513client = Client(api_key=os.getenv("XAI_API_KEY"))

514chat = client.chat.create(514chat = client.chat.create(

515 model="grok-4.5", # reasoning model515 model="grok-4.6", # reasoning model

516 tools=[516 tools=[

517 web_search(),517 web_search(),

518 x_search(),518 x_search(),


555)555)

556 556 

557response = client.responses.create(557response = client.responses.create(

558 model="grok-4.5",558 model="grok-4.6",

559 input=[559 input=[

560 {560 {

561 "role": "user",561 "role": "user",


585 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"585 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"

586}586}

587payload = {587payload = {

588 "model": "grok-4.5",588 "model": "grok-4.6",

589 "input": [589 "input": [

590 {590 {

591 "role": "user",591 "role": "user",


610 -H "Content-Type: application/json" \\610 -H "Content-Type: application/json" \\

611 -H "Authorization: Bearer $XAI_API_KEY" \\611 -H "Authorization: Bearer $XAI_API_KEY" \\

612 -d '{612 -d '{

613 "model": "grok-4.5",613 "model": "grok-4.6",

614 "input": [614 "input": [

615 {615 {

616 "role": "user",616 "role": "user",


641 641 

642client = Client(api_key=os.getenv("XAI_API_KEY"))642client = Client(api_key=os.getenv("XAI_API_KEY"))

643chat = client.chat.create(643chat = client.chat.create(

644 model="grok-4.5", # reasoning model644 model="grok-4.6", # reasoning model

645 # research_tools645 # research_tools

646 tools=[646 tools=[

647 web_search(),647 web_search(),


666)666)

667 667 

668response = client.responses.create(668response = client.responses.create(

669 model="grok-4.5",669 model="grok-4.6",

670 input=[670 input=[

671 {671 {

672 "role": "user",672 "role": "user",


697 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"697 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"

698}698}

699payload = {699payload = {

700 "model": "grok-4.5",700 "model": "grok-4.6",

701 "input": [701 "input": [

702 {702 {

703 "role": "user",703 "role": "user",


723 -H "Content-Type: application/json" \\723 -H "Content-Type: application/json" \\

724 -H "Authorization: Bearer $XAI_API_KEY" \\724 -H "Authorization: Bearer $XAI_API_KEY" \\

725 -d '{725 -d '{

726 "model": "grok-4.5",726 "model": "grok-4.6",

727 "input": [727 "input": [

728 {728 {

729 "role": "user",729 "role": "user",


757# Create the client and define the server-side tools to use757# Create the client and define the server-side tools to use

758client = Client(api_key=os.getenv("XAI_API_KEY"))758client = Client(api_key=os.getenv("XAI_API_KEY"))

759chat = client.chat.create(759chat = client.chat.create(

760 model="grok-4.5", # reasoning model760 model="grok-4.6", # reasoning model

761 tools=[web_search(), x_search()],761 tools=[web_search(), x_search()],

762 include=["verbose_streaming"],762 include=["verbose_streaming"],

763)763)

tools/citations.md +10 −10

Details

59 -H "Content-Type: application/json" \59 -H "Content-Type: application/json" \

60 -H "Authorization: Bearer $XAI_API_KEY" \60 -H "Authorization: Bearer $XAI_API_KEY" \

61 -d '{61 -d '{

62 "model": "grok-4.5",62 "model": "grok-4.6",

63 "input": [63 "input": [

64 {"role": "user", "content": "What is xAI?"}64 {"role": "user", "content": "What is xAI?"}

65 ],65 ],


76 76 

77client = Client(api_key=os.getenv("XAI_API_KEY"))77client = Client(api_key=os.getenv("XAI_API_KEY"))

78chat = client.chat.create(78chat = client.chat.create(

79 model="grok-4.5",79 model="grok-4.6",

80 tools=[80 tools=[

81 web_search(),81 web_search(),

82 x_search(),82 x_search(),


101)101)

102 102 

103response = client.responses.create(103response = client.responses.create(

104 model="grok-4.5",104 model="grok-4.6",

105 input=[105 input=[

106 {"role": "user", "content": "What is xAI?"}106 {"role": "user", "content": "What is xAI?"}

107 ],107 ],


123import { generateText } from 'ai';123import { generateText } from 'ai';

124 124 

125const { text, sources } = await generateText({125const { text, sources } = await generateText({

126 model: xai.responses('grok-4.5'),126 model: xai.responses('grok-4.6'),

127 prompt: 'What is xAI?',127 prompt: 'What is xAI?',

128 tools: {128 tools: {

129 web_search: xai.tools.webSearch(), // inline citations are enabled by default129 web_search: xai.tools.webSearch(), // inline citations are enabled by default


146});146});

147 147 

148const response = await client.responses.create({148const response = await client.responses.create({

149 model: 'grok-4.5',149 model: 'grok-4.6',

150 input: [150 input: [

151 { role: 'user', content: 'What is xAI?' }151 { role: 'user', content: 'What is xAI?' }

152 ],152 ],


177)177)

178 178 

179response = client.responses.create(179response = client.responses.create(

180 model="grok-4.5",180 model="grok-4.6",

181 input=[181 input=[

182 {"role": "user", "content": "What is xAI?"}182 {"role": "user", "content": "What is xAI?"}

183 ],183 ],


206 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}",206 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}",

207 },207 },

208 json={208 json={

209 "model": "grok-4.5",209 "model": "grok-4.6",

210 "include": ["no_inline_citations"],210 "include": ["no_inline_citations"],

211 "input": [211 "input": [

212 {"role": "user", "content": "What is xAI?"}212 {"role": "user", "content": "What is xAI?"}


228 -H "Content-Type: application/json" \228 -H "Content-Type: application/json" \

229 -H "Authorization: Bearer $XAI_API_KEY" \229 -H "Authorization: Bearer $XAI_API_KEY" \

230 -d '{230 -d '{

231 "model": "grok-4.5",231 "model": "grok-4.6",

232 "include": ["no_inline_citations"],232 "include": ["no_inline_citations"],

233 "input": [233 "input": [

234 {"role": "user", "content": "What is xAI?"}234 {"role": "user", "content": "What is xAI?"}


284 "completed_at": 1781829888,284 "completed_at": 1781829888,

285 "id": "5808284d-ae14-9981-9289-73515f67ebda",285 "id": "5808284d-ae14-9981-9289-73515f67ebda",

286 "max_output_tokens": null,286 "max_output_tokens": null,

287 "model": "grok-4.5",287 "model": "grok-4.6",

288 "object": "response",288 "object": "response",

289 "output": [289 "output": [

290 ...290 ...


384import { streamText } from 'ai';384import { streamText } from 'ai';

385 385 

386const { fullStream } = streamText({386const { fullStream } = streamText({

387 model: xai.responses('grok-4.5'),387 model: xai.responses('grok-4.6'),

388 prompt: 'What is xAI?',388 prompt: 'What is xAI?',

389 tools: {389 tools: {

390 web_search: xai.tools.webSearch(),390 web_search: xai.tools.webSearch(),

Details

48 48 

49client = Client(api_key=os.getenv("XAI_API_KEY"))49client = Client(api_key=os.getenv("XAI_API_KEY"))

50chat = client.chat.create(50chat = client.chat.create(

51 model="grok-4.5", # reasoning model51 model="grok-4.6", # reasoning model

52 tools=[code_execution()],52 tools=[code_execution()],

53 include=["verbose_streaming"],53 include=["verbose_streaming"],

54)54)


89)89)

90 90 

91response = client.responses.create(91response = client.responses.create(

92 model="grok-4.5",92 model="grok-4.6",

93 input=[93 input=[

94 {94 {

95 "role": "user",95 "role": "user",


116 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"116 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"

117}117}

118payload = {118payload = {

119 "model": "grok-4.5",119 "model": "grok-4.6",

120 "input": [120 "input": [

121 {121 {

122 "role": "user",122 "role": "user",


138 -H "Content-Type: application/json" \\138 -H "Content-Type: application/json" \\

139 -H "Authorization: Bearer $XAI_API_KEY" \\139 -H "Authorization: Bearer $XAI_API_KEY" \\

140 -d '{140 -d '{

141 "model": "grok-4.5",141 "model": "grok-4.6",

142 "input": [142 "input": [

143 {143 {

144 "role": "user",144 "role": "user",


158import { generateText } from 'ai';158import { generateText } from 'ai';

159 159 

160const { text } = await generateText({160const { text } = await generateText({

161 model: xai.responses('grok-4.5'),161 model: xai.responses('grok-4.6'),

162 prompt: 'Calculate the compound interest for $10,000 at 5% annually for 10 years',162 prompt: 'Calculate the compound interest for $10,000 at 5% annually for 10 years',

163 tools: {163 tools: {

164 code_execution: xai.tools.codeExecution(),164 code_execution: xai.tools.codeExecution(),


180 180 

181# Multi-turn conversation with data analysis181# Multi-turn conversation with data analysis

182chat = client.chat.create(182chat = client.chat.create(

183 model="grok-4.5", # reasoning model183 model="grok-4.6", # reasoning model

184 tools=[code_execution()],184 tools=[code_execution()],

185 include=["verbose_streaming"],185 include=["verbose_streaming"],

186)186)


250 250 

251// Step 1: Load and analyze data251// Step 1: Load and analyze data

252const step1 = await generateText({252const step1 = await generateText({

253 model: xai.responses('grok-4.5'),253 model: xai.responses('grok-4.6'),

254 prompt: \`I have sales data for Q1-Q4: [120000, 135000, 98000, 156000].254 prompt: \`I have sales data for Q1-Q4: [120000, 135000, 98000, 156000].

255Please analyze this data and create a visualization showing:255Please analyze this data and create a visualization showing:

2561. Quarterly trends2561. Quarterly trends


266 266 

267// Step 2: Follow-up analysis using previousResponseId267// Step 2: Follow-up analysis using previousResponseId

268const step2 = await generateText({268const step2 = await generateText({

269 model: xai.responses('grok-4.5'),269 model: xai.responses('grok-4.6'),

270 prompt: 'Now predict Q1 next year using linear regression',270 prompt: 'Now predict Q1 next year using linear regression',

271 tools: {271 tools: {

272 code_execution: xai.tools.codeExecution(),272 code_execution: xai.tools.codeExecution(),


312### 3. **Use Appropriate Model Settings**312### 3. **Use Appropriate Model Settings**

313 313 

314* **Temperature**: Use lower values (0.0-0.3) for mathematical calculations314* **Temperature**: Use lower values (0.0-0.3) for mathematical calculations

315* **Model**: Use reasoning models like `grok-4.5` for better code generation315* **Model**: Use reasoning models like `grok-4.6` for better code generation

316 316 

317## Common Use Cases317## Common Use Cases

318 318 

Details

21 -H "Content-Type: application/json" \21 -H "Content-Type: application/json" \

22 -H "Authorization: Bearer $XAI_API_KEY" \22 -H "Authorization: Bearer $XAI_API_KEY" \

23 -d '{23 -d '{

24 "model": "grok-4.5",24 "model": "grok-4.6",

25 "input": [25 "input": [

26 {"role": "user", "content": "What is the temperature in San Francisco?"}26 {"role": "user", "content": "What is the temperature in San Francisco?"}

27 ],27 ],


69]69]

70 70 

71chat = client.chat.create(71chat = client.chat.create(

72 model="grok-4.5",72 model="grok-4.6",

73 tools=tools,73 tools=tools,

74)74)

75chat.append(user("What is the temperature in San Francisco?"))75chat.append(user("What is the temperature in San Francisco?"))


116]116]

117 117 

118response = client.responses.create(118response = client.responses.create(

119 model="grok-4.5",119 model="grok-4.6",

120 input=[{"role": "user", "content": "What is the temperature in San Francisco?"}],120 input=[{"role": "user", "content": "What is the temperature in San Francisco?"}],

121 tools=tools,121 tools=tools,

122)122)


128 result = {"location": args["location"], "temperature": 59, "unit": args.get("unit", "fahrenheit")}128 result = {"location": args["location"], "temperature": 59, "unit": args.get("unit", "fahrenheit")}

129 129 

130 response = client.responses.create(130 response = client.responses.create(

131 model="grok-4.5",131 model="grok-4.6",

132 input=[{"type": "function_call_output", "call_id": item.call_id, "output": json.dumps(result)}],132 input=[{"type": "function_call_output", "call_id": item.call_id, "output": json.dumps(result)}],

133 tools=tools,133 tools=tools,

134 previous_response_id=response.id,134 previous_response_id=response.id,


145import { z } from 'zod';145import { z } from 'zod';

146 146 

147const result = streamText({147const result = streamText({

148 model: xai.responses('grok-4.5'),148 model: xai.responses('grok-4.6'),

149 tools: {149 tools: {

150 getTemperature: tool({150 getTemperature: tool({

151 description: 'Get current temperature for a location',151 description: 'Get current temperature for a location',


289 output = json.dumps(tools_map[name](**args))289 output = json.dumps(tools_map[name](**args))

290 290 

291 response = client.responses.create(291 response = client.responses.create(

292 model="grok-4.5",292 model="grok-4.6",

293 input=[{"type": "function_call_output", "call_id": item.call_id, "output": output}],293 input=[{"type": "function_call_output", "call_id": item.call_id, "output": output}],

294 tools=tools,294 tools=tools,

295 previous_response_id=response.id,295 previous_response_id=response.id,


325]325]

326 326 

327chat = client.chat.create(327chat = client.chat.create(

328 model="grok-4.5",328 model="grok-4.6",

329 tools=tools,329 tools=tools,

330)330)

331```331```


447import { z } from 'zod';447import { z } from 'zod';

448 448 

449const result = streamText({449const result = streamText({

450 model: xai.responses('grok-4.5'),450 model: xai.responses('grok-4.6'),

451 tools: {451 tools: {

452 getCurrentTemperature: tool({452 getCurrentTemperature: tool({

453 description: 'Get current temperature for a location',453 description: 'Get current temperature for a location',

Details

23 -H "Content-Type: application/json" \23 -H "Content-Type: application/json" \

24 -H "Authorization: Bearer $XAI_API_KEY" \24 -H "Authorization: Bearer $XAI_API_KEY" \

25 -d '{25 -d '{

26 "model": "grok-4.5",26 "model": "grok-4.6",

27 "input": "Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",27 "input": "Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",

28 "tools": [28 "tools": [

29 {29 {


46)46)

47 47 

48response = client.responses.create(48response = client.responses.create(

49 model="grok-4.5",49 model="grok-4.6",

50 input="Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",50 input="Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",

51 tools=[{"type": "image_generation"}],51 tools=[{"type": "image_generation"}],

52)52)


74 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}",74 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}",

75}75}

76payload = {76payload = {

77 "model": "grok-4.5",77 "model": "grok-4.6",

78 "input": "Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",78 "input": "Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",

79 "tools": [{"type": "image_generation"}],79 "tools": [{"type": "image_generation"}],

80}80}


97});97});

98 98 

99const response = await client.responses.create({99const response = await client.responses.create({

100 model: "grok-4.5",100 model: "grok-4.6",

101 input:101 input:

102 "Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",102 "Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",

103 tools: [{ type: "image_generation" }],103 tools: [{ type: "image_generation" }],


145 -H "Content-Type: application/json" \145 -H "Content-Type: application/json" \

146 -H "Authorization: Bearer $XAI_API_KEY" \146 -H "Authorization: Bearer $XAI_API_KEY" \

147 -d '{147 -d '{

148 "model": "grok-4.5",148 "model": "grok-4.6",

149 "input": "Generate an image of a hot air balloon over the desert",149 "input": "Generate an image of a hot air balloon over the desert",

150 "tools": [150 "tools": [

151 {151 {


158 158 

159```python customLanguage="pythonOpenAISDK"159```python customLanguage="pythonOpenAISDK"

160response = client.responses.create(160response = client.responses.create(

161 model="grok-4.5",161 model="grok-4.6",

162 input="Generate an image of a hot air balloon over the desert",162 input="Generate an image of a hot air balloon over the desert",

163 tools=[{"type": "image_generation", "action": "generate"}],163 tools=[{"type": "image_generation", "action": "generate"}],

164)164)


173 -H "Content-Type: application/json" \173 -H "Content-Type: application/json" \

174 -H "Authorization: Bearer $XAI_API_KEY" \174 -H "Authorization: Bearer $XAI_API_KEY" \

175 -d '{175 -d '{

176 "model": "grok-4.5",176 "model": "grok-4.6",

177 "input": [177 "input": [

178 {178 {

179 "role": "user",179 "role": "user",


210)210)

211 211 

212response = client.responses.create(212response = client.responses.create(

213 model="grok-4.5",213 model="grok-4.6",

214 input=[214 input=[

215 {215 {

216 "role": "user",216 "role": "user",


256)256)

257 257 

258response = client.responses.create(258response = client.responses.create(

259 model="grok-4.5",259 model="grok-4.6",

260 input="Generate an image of a lighthouse on a rocky coast",260 input="Generate an image of a lighthouse on a rocky coast",

261 tools=[{"type": "image_generation"}],261 tools=[{"type": "image_generation"}],

262)262)


273 273 

274# Follow up: edit the image from the previous turn274# Follow up: edit the image from the previous turn

275followup = client.responses.create(275followup = client.responses.create(

276 model="grok-4.5",276 model="grok-4.6",

277 previous_response_id=response.id,277 previous_response_id=response.id,

278 input="Make it night time with a full moon",278 input="Make it night time with a full moon",

279 tools=[{"type": "image_generation"}],279 tools=[{"type": "image_generation"}],


301 -H "Content-Type: application/json" \301 -H "Content-Type: application/json" \

302 -H "Authorization: Bearer $XAI_API_KEY" \302 -H "Authorization: Bearer $XAI_API_KEY" \

303 -d '{303 -d '{

304 "model": "grok-4.5",304 "model": "grok-4.6",

305 "input": "Find out which team won the most recent FIFA World Cup, then generate an image of a celebratory poster for that team, in a vintage travel-poster style.",305 "input": "Find out which team won the most recent FIFA World Cup, then generate an image of a celebratory poster for that team, in a vintage travel-poster style.",

306 "tools": [306 "tools": [

307 {307 {


327)327)

328 328 

329response = client.responses.create(329response = client.responses.create(

330 model="grok-4.5",330 model="grok-4.6",

331 input=(331 input=(

332 "Find out which team won the most recent FIFA World Cup, then generate an "332 "Find out which team won the most recent FIFA World Cup, then generate an "

333 "image of a celebratory poster for that team, in a vintage travel-poster style."333 "image of a celebratory poster for that team, in a vintage travel-poster style."


369)369)

370 370 

371stream = client.responses.create(371stream = client.responses.create(

372 model="grok-4.5",372 model="grok-4.6",

373 input="Generate an image of an origami fox in a paper forest",373 input="Generate an image of an origami fox in a paper forest",

374 tools=[{"type": "image_generation"}],374 tools=[{"type": "image_generation"}],

375 stream=True,375 stream=True,


397});397});

398 398 

399const stream = await client.responses.create({399const stream = await client.responses.create({

400 model: "grok-4.5",400 model: "grok-4.6",

401 input: "Generate an image of an origami fox in a paper forest",401 input: "Generate an image of an origami fox in a paper forest",

402 tools: [{ type: "image_generation" }],402 tools: [{ type: "image_generation" }],

403 stream: true,403 stream: true,

Details

38 -H "Content-Type: application/json" \38 -H "Content-Type: application/json" \

39 -H "Authorization: Bearer $XAI_API_KEY" \39 -H "Authorization: Bearer $XAI_API_KEY" \

40 -d '{40 -d '{

41 "model": "grok-4.5",41 "model": "grok-4.6",

42 "stream": true,42 "stream": true,

43 "input": [43 "input": [

44 {44 {


63 63 

64client = Client(api_key=os.getenv("XAI_API_KEY"))64client = Client(api_key=os.getenv("XAI_API_KEY"))

65chat = client.chat.create(65chat = client.chat.create(

66 model="grok-4.5",66 model="grok-4.6",

67 tools=[67 tools=[

68 web_search(),68 web_search(),

69 x_search(),69 x_search(),


90)90)

91 91 

92response = client.responses.create(92response = client.responses.create(

93 model="grok-4.5",93 model="grok-4.6",

94 input=[94 input=[

95 {"role": "user", "content": "What are the latest updates from xAI?"}95 {"role": "user", "content": "What are the latest updates from xAI?"}

96 ],96 ],


112import { streamText } from 'ai';112import { streamText } from 'ai';

113 113 

114const { fullStream } = streamText({114const { fullStream } = streamText({

115 model: xai.responses('grok-4.5'),115 model: xai.responses('grok-4.6'),

116 prompt: 'What are the latest updates from xAI?',116 prompt: 'What are the latest updates from xAI?',

117 tools: {117 tools: {

118 web_search: xai.tools.webSearch(),118 web_search: xai.tools.webSearch(),


139});139});

140 140 

141const stream = await client.responses.create({141const stream = await client.responses.create({

142 model: "grok-4.5",142 model: "grok-4.6",

143 input: [143 input: [

144 { role: "user", content: "What are the latest updates from xAI?" }144 { role: "user", content: "What are the latest updates from xAI?" }

145 ],145 ],

Details

36 36 

37client = Client(api_key=os.getenv("XAI_API_KEY"))37client = Client(api_key=os.getenv("XAI_API_KEY"))

38chat = client.chat.create(38chat = client.chat.create(

39 model="grok-4.5",39 model="grok-4.6",

40 tools=[40 tools=[

41 mcp(server_url="https://mcp.deepwiki.com/mcp"),41 mcp(server_url="https://mcp.deepwiki.com/mcp"),

42 ],42 ],


76)76)

77 77 

78response = client.responses.create(78response = client.responses.create(

79 model="grok-4.5",79 model="grok-4.6",

80 input=[80 input=[

81 {81 {

82 "role": "user",82 "role": "user",


105 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"105 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"

106}106}

107payload = {107payload = {

108 "model": "grok-4.5",108 "model": "grok-4.6",

109 "input": [109 "input": [

110 {110 {

111 "role": "user",111 "role": "user",


129 -H "Content-Type: application/json" \\129 -H "Content-Type: application/json" \\

130 -H "Authorization: Bearer $XAI_API_KEY" \\130 -H "Authorization: Bearer $XAI_API_KEY" \\

131 -d '{131 -d '{

132 "model": "grok-4.5",132 "model": "grok-4.6",

133 "input": [133 "input": [

134 {134 {

135 "role": "user",135 "role": "user",


173 173 

174```pythonXAI174```pythonXAI

175chat = client.chat.create(175chat = client.chat.create(

176 model="grok-4.5",176 model="grok-4.6",

177 tools=[177 tools=[

178 mcp(server_url="https://mcp.deepwiki.com/mcp", server_label="deepwiki"),178 mcp(server_url="https://mcp.deepwiki.com/mcp", server_label="deepwiki"),

179 mcp(server_url="https://your-custom-tools.com/mcp", server_label="custom"),179 mcp(server_url="https://your-custom-tools.com/mcp", server_label="custom"),

Details

23 23 

24client = Client(api_key=os.getenv("XAI_API_KEY"))24client = Client(api_key=os.getenv("XAI_API_KEY"))

25chat = client.chat.create(25chat = client.chat.create(

26 model="grok-4.5",26 model="grok-4.6",

27 tools=[27 tools=[

28 web_search(),28 web_search(),

29 x_search(),29 x_search(),


55import { streamText } from 'ai';55import { streamText } from 'ai';

56 56 

57const { fullStream } = streamText({57const { fullStream } = streamText({

58 model: xai.responses('grok-4.5'),58 model: xai.responses('grok-4.6'),

59 prompt: 'What are the latest updates from xAI?',59 prompt: 'What are the latest updates from xAI?',

60 tools: {60 tools: {

61 web_search: xai.tools.webSearch(),61 web_search: xai.tools.webSearch(),


88 88 

89client = Client(api_key=os.getenv("XAI_API_KEY"))89client = Client(api_key=os.getenv("XAI_API_KEY"))

90chat = client.chat.create(90chat = client.chat.create(

91 model="grok-4.5",91 model="grok-4.6",

92 tools=[92 tools=[

93 web_search(),93 web_search(),

94 x_search(),94 x_search(),


118 118 

119// Synchronous request - waits for complete response119// Synchronous request - waits for complete response

120const { text, sources } = await generateText({120const { text, sources } = await generateText({

121 model: xai.responses('grok-4.5'),121 model: xai.responses('grok-4.6'),

122 prompt: 'What is the latest update from xAI?',122 prompt: 'What is the latest update from xAI?',

123 tools: {123 tools: {

124 web_search: xai.tools.webSearch(),124 web_search: xai.tools.webSearch(),


149 149 

150client = Client(api_key=os.getenv("XAI_API_KEY"))150client = Client(api_key=os.getenv("XAI_API_KEY"))

151chat = client.chat.create(151chat = client.chat.create(

152 model="grok-4.5",152 model="grok-4.6",

153 store_messages=True, # Enable Responses API153 store_messages=True, # Enable Responses API

154 tools=[154 tools=[

155 web_search(),155 web_search(),


178)178)

179 179 

180response = client.responses.create(180response = client.responses.create(

181 model="grok-4.5",181 model="grok-4.6",

182 input=[182 input=[

183 {183 {

184 "role": "user",184 "role": "user",


203 -H "Content-Type: application/json" \\203 -H "Content-Type: application/json" \\

204 -H "Authorization: Bearer $XAI_API_KEY" \\204 -H "Authorization: Bearer $XAI_API_KEY" \\

205 -d '{205 -d '{

206 "model": "grok-4.5",206 "model": "grok-4.6",

207 "input": [207 "input": [

208 {208 {

209 "role": "user",209 "role": "user",


244 244 

245client = Client(api_key=os.getenv("XAI_API_KEY"))245client = Client(api_key=os.getenv("XAI_API_KEY"))

246chat = client.chat.create(246chat = client.chat.create(

247 model="grok-4.5",247 model="grok-4.6",

248 tools=[248 tools=[

249 code_execution(),249 code_execution(),

250 ],250 ],

Details

122 122 

123client = Client(api_key=os.getenv("XAI_API_KEY"))123client = Client(api_key=os.getenv("XAI_API_KEY"))

124chat = client.chat.create(124chat = client.chat.create(

125 model="grok-4.5",125 model="grok-4.6",

126 tools=[126 tools=[

127 web_search(),127 web_search(),

128 x_search(),128 x_search(),