SpyBara
Go Premium

Documentation 2026-09-20 23:01 UTC to 2026-09-21 23:00 UTC

40 files changed +334 −320. View all changes and history on the product overview
2026
Wed 30 23:57 Tue 29 23:59 Mon 28 23:57 Sun 27 22:59 Sat 26 23:59 Fri 25 23:01 Thu 24 23:59 Wed 23 23:59 Tue 22 23:58 Mon 21 23:00 Sun 20 23:01 Sat 19 23:59 Fri 18 23:59 Thu 17 10:04 Wed 16 19:01 Tue 15 17:00 Mon 14 06:00 Sun 13 05:00 Fri 11 21:00 Tue 8 21:00 Mon 7 22:57 Thu 3 16:59 Wed 2 22:03
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.6"32 model = "grok-4.7"

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.6",81 model="grok-4.7",

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

83 )83 )

84 84 

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.6",38 "model": "grok-4.7",

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.6",53 "model": "grok-4.7",

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.6", use_encrypted_content=True)75chat = client.chat.create(model="grok-4.7", 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.6",89 model="grok-4.7",

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.6",116 model="grok-4.7",

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.6",132 model="grok-4.7",

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.6",152 model: "grok-4.7",

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.6",168 model: "grok-4.7",

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.6",189 "model": "grok-4.7",

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.6", use_encrypted_content=True)236chat = client.chat.create(model="grok-4.7", 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.6",39 model="grok-4.7",

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.6",72 "model": "grok-4.7",

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.6',112 model: 'grok-4.7',

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.6",152 "model": "grok-4.7",

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.6",172 "model": "grok-4.7",

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.6",50 "model": "grok-4.7",

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.6",72 model="grok-4.7",

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.6',95 model: 'grok-4.7',

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.6",31 "model": "grok-4.7",

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.6",46 model="grok-4.7",

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.6",67 model="grok-4.7",

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.6",85 model: "grok-4.7",

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.6",99 "model": "grok-4.7",

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.6",15 "model": "grok-4.7",

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.6",32 model="grok-4.7",

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.6',56 model: 'grok-4.7',

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.6",88 "model": "grok-4.7",

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.6",103 model="grok-4.7",

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.6',123 model: 'grok-4.7',

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.6'),140 model: xai.responses('grok-4.7'),

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.6")166chat = client.chat.create(model="grok-4.7")

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.6",27 "model": "grok-4.7",

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.6",41 "model": "grok-4.7",

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.6",67 model="grok-4.7",

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.6",79 model="grok-4.7",

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.6', messages },106 { model: 'grok-4.7', 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.6', messages },120 { model: 'grok-4.7', 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.6",139 "model": "grok-4.7",

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.6",163 "model": "grok-4.7",

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.6",186 "model": "grok-4.7",

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

8 8 

9> [!NOTE]9> [!NOTE]

10>10>

11> The US endpoint currently serves one model, `grok-4.6`, and none of the image generation, video generation, or voice APIs. Token usage costs 10% more than on the global endpoint. The US guarantee covers API request handling, inference, moderation, and retained request data. It does not cover Files, Collections, server-side tools, or the network path from your systems to SpaceXAI. See [What the guarantee covers](#what-the-guarantee-covers).11> The US endpoint currently serves two models, `grok-4.7` and `grok-4.6`, and none of the image generation, video generation, or voice APIs. Token usage costs 10% more than on the global endpoint. The US guarantee covers API request handling, inference, moderation, and retained request data. It does not cover Files, Collections, server-side tools, or the network path from your systems to SpaceXAI. See [What the guarantee covers](#what-the-guarantee-covers).

12 12 

13## Using the US endpoint13## Using the US endpoint

14 14 


24});24});

25 25 

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

27 model: xai.responses('grok-4.6'),27 model: xai.responses('grok-4.7'),

28 prompt: 'Explain latency versus throughput in two sentences.',28 prompt: 'Explain latency versus throughput in two sentences.',

29});29});

30 30 


42 api_host="us.api.x.ai",42 api_host="us.api.x.ai",

43)43)

44 44 

45chat = client.chat.create(model="grok-4.6")45chat = client.chat.create(model="grok-4.7")

46chat.append(user("Explain latency versus throughput in two sentences."))46chat.append(user("Explain latency versus throughput in two sentences."))

47 47 

48print(chat.sample().content)48print(chat.sample().content)


58)58)

59 59 

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

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

62 input="Explain latency versus throughput in two sentences.",62 input="Explain latency versus throughput in two sentences.",

63)63)

64 64 


74});74});

75 75 

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

77 model: 'grok-4.6',77 model: 'grok-4.7',

78 input: 'Explain latency versus throughput in two sentences.',78 input: 'Explain latency versus throughput in two sentences.',

79});79});

80 80 


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

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

88 -d '{88 -d '{

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

90 "input": "Explain latency versus throughput in two sentences."90 "input": "Explain latency versus throughput in two sentences."

91 }'91 }'

92```92```

93 93 

94### Model availability94### Model availability

95 95 

96`grok-4.6` is currently the only model available on the US endpoint; the [models page in the console](https://console.x.ai/team/default/models?cluster=us-central-1\&utm_source=docs\&utm_medium=referral\&utm_campaign=developers-advanced-api-usage-regions\&utm_content=models) and `GET https://us.api.x.ai/v1/models` always show the current list. Requesting a model that is not on that list, including `grok-latest`, fails with `404 Not Found`:96`grok-4.7` and `grok-4.6` are currently the only models available on the US endpoint; the [models page in the console](https://console.x.ai/team/default/models?cluster=us-central-1\&utm_source=docs\&utm_medium=referral\&utm_campaign=developers-advanced-api-usage-regions\&utm_content=models) and `GET https://us.api.x.ai/v1/models` always show the current list. Requesting a model that is not on that list, including `grok-latest`, fails with `404 Not Found`:

97 97 

98```json customLanguage="json"98```json customLanguage="json"

99{99{

Details

44 json.dumps(44 json.dumps(

45 {45 {

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

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

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.6",75 model: "grok-4.7",

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.6",115 "model": "grok-4.7",

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.6",140 model: "grok-4.7",

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.6",23 model="xai/grok-4.7",

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.6'),53 model: xai.responses('grok-4.7'),

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.6`48* `xai/grok-4.7`

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.6",74 model="xai/grok-4.7",

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.6",90 model="xai/grok-4.7",

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.6",35 model="grok-4.7",

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.6",65 "model": "grok-4.7",

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.6",80 model="grok-4.7",

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.6",99 model: "grok-4.7",

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.6",126 model="grok-4.7",

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.6",148 model="grok-4.7",

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.6",174 model="grok-4.7",

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.6",214 model="grok-4.7",

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.6",243 model="grok-4.7",

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.6",267 model="grok-4.7",

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.6",287 "model": "grok-4.7",

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}'

faq/security.md +1 −1

Details

73 73 

74## Can I keep my data in the United States?74## Can I keep my data in the United States?

75 75 

76The default endpoint, `https://api.x.ai`, does not guarantee a processing region. To keep API request handling, model inference, moderation, and retained request data in the United States, use the US regional endpoint, `https://us.api.x.ai/v1`. It currently serves only `grok-4.6`, with no image generation, video generation, or voice APIs, and its token prices are 10% higher than global rates. Files, Collections, server-side tools, and the network path from your systems to the endpoint are outside the guarantee. See [Regional Endpoints](/developers/advanced-api-usage/regions) for details.76The default endpoint, `https://api.x.ai`, does not guarantee a processing region. To keep API request handling, model inference, moderation, and retained request data in the United States, use the US regional endpoint, `https://us.api.x.ai/v1`. It currently serves only `grok-4.7` and `grok-4.6`, with no image generation, video generation, or voice APIs, and its token prices are 10% higher than global rates. Files, Collections, server-side tools, and the network path from your systems to the endpoint are outside the guarantee. See [Regional Endpoints](/developers/advanced-api-usage/regions) for details.

77 77 

78## Is the xAI API HIPAA compliant?78## Is the xAI API HIPAA compliant?

79 79 

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.6")81chat = client.chat.create(model="grok-4.7")

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.6",120 model: "grok-4.7",

121 input: [121 input: [

122 {122 {

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


162 162 

163* **File size**: Maximum 512 MB per file163* **File size**: Maximum 512 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`, `grok-4.6`)165* **Agentic models only**: Requires models that support agentic tool calling (e.g., `grok-4.20`, `grok-4.5`, `grok-4.6`, `grok-4.7`)

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-7.md +19 −16 renamed

Details

Previously: grok-4-6.md

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

2 2 

3# Grok 4.63# Grok 4.7

4 4 

5Grok 4.6 is SpaceXAI's frontier model built for coding, agentic tasks, and knowledge work.5Grok 4.7 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?utm_source=docs\&utm_medium=referral\&utm_campaign=developers-grok-4-6\&utm_content=api-keys), set the model name to `grok-4.6`:9If you already have an [API key](https://console.x.ai/team/default/api-keys?utm_source=docs\&utm_medium=referral\&utm_campaign=developers-grok-4-7\&utm_content=api-keys), set the model name to `grok-4.7`:

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.6")18chat = client.chat.create(model="grok-4.7")

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.6'),30 model: xai.responses('grok-4.7'),

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.6',47 model: 'grok-4.7',

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.6",65 "model": "grok-4.7",

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.6` |76| Model name | `grok-4.7` |

77| Context window | 500,000 tokens |77| Context window | 500,000 tokens |

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

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

80| Output limit | No text output limit |80| Output limit | No text output limit |

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


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

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) |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) |

86 86 

87Rate limits and live pricing for your team are on the [model detail page](/developers/models/grok-4.6) and [Pricing](/developers/pricing).87Rate limits and live pricing for your team are on the [model detail page](/developers/models/grok-4.7) and [Pricing](/developers/pricing).

88 

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

90 88 

91## Important details89## Important details

92 90 

93* **We highly recommend setting a [`prompt_cache_key`](/developers/advanced-api-usage/prompt-caching/maximizing-cache-hits)** (Responses API; `x-grok-conv-id` header on Chat Completions). It routes a conversation's requests to the same server, making cache hits reliable; without it you often pay full input price on a cache-cold server. See [What Breaks Caching](/developers/advanced-api-usage/prompt-caching/multi-turn) for common mistakes.91* **We highly recommend setting a [`prompt_cache_key`](/developers/advanced-api-usage/prompt-caching/maximizing-cache-hits)** (Responses API; `x-grok-conv-id` header on Chat Completions). It routes a conversation's requests to the same server, making cache hits reliable; without it you often pay full input price on a cache-cold server. See [What Breaks Caching](/developers/advanced-api-usage/prompt-caching/multi-turn) for common mistakes.

94* **Long agent loops** additionally benefit from [context compaction](/developers/advanced-api-usage/context-compaction); for tool-heavy workloads see [function calling](/developers/tools/function-calling).92* **Long agent loops** additionally benefit from [context compaction](/developers/advanced-api-usage/context-compaction); for tool-heavy workloads see [function calling](/developers/tools/function-calling).

93* **Encrypted reasoning is always returned on the Responses API.** `POST /v1/responses` responses from `grok-4.7` include `reasoning.encrypted_content` even when `include` does not list it, so multi-turn conversations keep the model's reasoning without extra configuration. Pass the reasoning items back unchanged in the next request's `input`; see [Encrypted reasoning content](/developers/model-capabilities/text/reasoning#encrypted-reasoning-content). Chat Completions is unchanged.

94 

95## Fast variant

96 

97Grok 4.7 Fast is the same model served on faster infrastructure, billed at twice the standard token rates. It is available only in Cursor and [Grok Build](/build/overview), and it is not included in Grok Build's free tier. It is not available on the public xAI API. Rates are on the [Pricing](/developers/pricing#grok-47-fast-pricing-cursor-and-grok-build-only) page.

95 98 

96## Where it runs99## Where it runs

97 100 

98* **xAI API**: get a key from the [console](https://console.x.ai/?utm_source=docs\&utm_medium=referral\&utm_campaign=developers-grok-4-6\&utm_content=console-home)101* **xAI API**: get a key from the [console](https://console.x.ai/?utm_source=docs\&utm_medium=referral\&utm_campaign=developers-grok-4-7\&utm_content=console-home)

99* **US regional endpoint**: currently the only model served at `https://us.api.x.ai/v1`, which keeps inference in the United States, with token usage priced at a 10% premium; see [Regional Endpoints](/developers/advanced-api-usage/regions)102* **US regional endpoint**: also served at `https://us.api.x.ai/v1`, which keeps inference in the United States, with token usage priced at a 10% premium; see [Regional Endpoints](/developers/advanced-api-usage/regions)

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

101* **Cursor**: available on all plans104* **Cursor**: available on all plans

102* **Model gateways**: OpenRouter, Vercel, and Cloudflare105* **Model gateways**: OpenRouter, Vercel, and Cloudflare

103 106 

104## Learn more107## Learn more

105 108 

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

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

108* [Models](/developers/models) - compare available models and their capabilities111* [Models](/developers/models) - compare available models and their capabilities

109* [Pricing](/developers/pricing) - token pricing for all models112* [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.6>`36* `api-key:model:<model name such as grok-4.7>`

37 37 

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

39 39 

Details

129 129 

130## Voices130## Voices

131 131 

132Each voice has a distinct personality. Listen to samples and choose the best fit for your use case (`eve` is the default):132Each voice has a distinct personality. All voices can speak every supported language. Listen to samples and choose the best fit for your use case (`eve` is the default):

133 133 

134Voice IDs are **case-insensitive** - `eve`, `Eve`, and `EVE` all work. [Preview all voices in the playground →](https://console.x.ai/team/default/voice/text-to-speech?campaign=voice-docs-tts\&utm_source=docs\&utm_medium=referral\&utm_campaign=developers-model-capabilities-audio-text-to-speech\&utm_content=text-to-speech)134Voice IDs are **case-insensitive** - `eve`, `Eve`, and `EVE` all work. [Preview all voices in the playground →](https://console.x.ai/team/default/voice/text-to-speech?campaign=voice-docs-tts\&utm_source=docs\&utm_medium=referral\&utm_campaign=developers-model-capabilities-audio-text-to-speech\&utm_content=text-to-speech)

135 135 


236 236 

237## Supported Languages237## Supported Languages

238 238 

239The TTS API supports 20 languages via BCP-47 language codes. Use `auto` for automatic language detection, or specify a language code explicitly for consistent results.239The TTS API supports 20 languages via BCP-47 language codes. Use `auto` for automatic language detection, or specify a language code explicitly for consistent results. Voice and language are independent: any built-in voice can speak any supported language.

240 240 

241Language code validation is **case-insensitive** — `en`, `EN`, and `En` all work.241Language code validation is **case-insensitive** — `en`, `EN`, and `En` all work.

242 242 

Details

267 267 

268## Voices268## Voices

269 269 

270When using the Speech to Speech API or Text to Speech, you can choose from the full set of built-in voices. Each has its own personality and tone, so pick the one that best fits your application (`eve` is the default):270When using the Speech to Speech API or Text to Speech, you can choose from the full set of built-in voices. Each has its own personality and tone, and all of them can speak every supported language. Pick the one that best fits your application (`eve` is the default):

271 271 

272### Enterprise Compliance & Security272### Enterprise Compliance & Security

273 273 

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.6")37chat = client.chat.create(model="grok-4.7")

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.6",60 model="grok-4.7",

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.6",89 "model": "grok-4.7",

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.6",114 model: "grok-4.7",

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.6",136 "model": "grok-4.7",

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.6")161chat = client.chat.create(model="grok-4.7")

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.6",197 model: "grok-4.7",

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.6")231chat = client.chat.create(model="grok-4.7")

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.6",257 model: "grok-4.7",

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.6",292 model="grok-4.7",

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.6",336 model: "grok-4.7",

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.6",353 model: "grok-4.7",

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.6",365 model: "grok-4.7",

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.6")388chat = client.chat.create(model="grok-4.7")

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.6",412 model: "grok-4.7",

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.6",449 model="grok-4.7",

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.6",490 model: "grok-4.7",

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.6` for best document understanding541* **Recommended model**: `grok-4.7` 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.6")61chat = client.chat.create(model="grok-4.7")

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.6",92 model="grok-4.7",

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.6",131 model: "grok-4.7",

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.6'),161 model: xai.responses('grok-4.7'),

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.6",191 "model": "grok-4.7",

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.6")36chat = client.chat.create(model="grok-4.7")

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.6",56 model="grok-4.7",

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.6",76 model: "grok-4.7",

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.6'),97 model: xai('grok-4.7'),

98 system:98 system:

99 "You are Grok, a helpful and useful AI built by xAI.",99 "You are Grok, a helpful and useful 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.6",122 "model": "grok-4.7",

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.6",172 "model": "grok-4.7",

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.6")37chat = client.chat.create(model="grok-4.7")

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.6",61 model="grok-4.7",

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.6",85 model: "grok-4.7",

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.6'),109 model: xai.responses('grok-4.7'),

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.6",126 "model": "grok-4.7",

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.6", store_messages=False)155chat = client.chat.create(model="grok-4.7", 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.6",175 model="grok-4.7",

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.6",196 model: "grok-4.7",

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.6",219 "model": "grok-4.7",

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

221 {221 {

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


239>239>

240> Make sure to use a reasoning model when working with encrypted thinking content.240> Make sure to use a reasoning model when working with encrypted thinking content.

241 241 

242> [!NOTE]

243>

244> `grok-4.7` always returns `reasoning.encrypted_content` on the Responses API, whether or not `include` lists it. See [Encrypted reasoning content](/developers/model-capabilities/text/reasoning#encrypted-reasoning-content).

245 

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

243 247 

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

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

246 use_encrypted_content=True)250 use_encrypted_content=True)

247```251```

248 252 

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

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

251 model="grok-4.6",255 model="grok-4.7",

252 input=[256 input=[

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

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


259 263 

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

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

262 model: "grok-4.6",266 model: "grok-4.7",

263 input: [267 input: [

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

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


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

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

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

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

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

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

282});286});


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

292 -m 3600 \296 -m 3600 \

293 -d '{297 -d '{

294 "model": "grok-4.6",298 "model": "grok-4.7",

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

296 {300 {

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


325 timeout=3600,329 timeout=3600,

326)330)

327 331 

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

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

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

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


339# New steps343# New steps

340 344 

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

342 model="grok-4.6",346 model="grok-4.7",

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

344 store_messages=True,348 store_messages=True,

345)349)


366)370)

367 371 

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

369 model="grok-4.6",373 model="grok-4.7",

370 input=[374 input=[

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

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


382# New steps386# New steps

383 387 

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

385 model="grok-4.6",389 model="grok-4.7",

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

387 input=[391 input=[

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


407});411});

408 412 

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

410 model: "grok-4.6",414 model: "grok-4.7",

411 input: [415 input: [

412 {416 {

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


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

427 431 

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

429 model: "grok-4.6",433 model: "grok-4.7",

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

431 input: [435 input: [

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


445 449 

446// First request450// First request

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

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

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

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

451});455});


457 461 

458// Continue the conversation using previousResponseId462// Continue the conversation using previousResponseId

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

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

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

462 providerOptions: {466 providerOptions: {

463 xai: {467 xai: {


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

476 -m 3600 \480 -m 3600 \

477 -d '{481 -d '{

478 "model": "grok-4.6",482 "model": "grok-4.7",

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

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

481 {485 {


505 timeout=3600,509 timeout=3600,

506)510)

507 511 

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

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

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

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


543)547)

544 548 

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

546 model="grok-4.6",550 model="grok-4.7",

547 input=[551 input=[

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

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


560# New steps564# New steps

561 565 

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

563 model="grok-4.6",567 model="grok-4.7",

564 input=[568 input=[

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

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


585});589});

586 590 

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

588 model: "grok-4.6",592 model: "grok-4.7",

589 input: [593 input: [

590 {594 {

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


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

606 610 

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

608 model: "grok-4.6",612 model: "grok-4.7",

609 input: [613 input: [

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

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


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

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

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

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

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

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

631});635});


635// Continue the conversation using previousResponseId639// Continue the conversation using previousResponseId

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

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

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

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

640 providerOptions: {644 providerOptions: {

641 xai: {645 xai: {


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

654 -m 3600 \658 -m 3600 \

655 -d '{659 -d '{

656 "model": "grok-4.6",660 "model": "grok-4.7",

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

658 {662 {

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

Details

12 12 

13The reasoning content is encrypted by us and can be returned if you pass `include: ["reasoning.encrypted_content"]` to the Responses API. You can send the encrypted content back to provide more context to a previous conversation. See [Adding encrypted thinking content](/developers/model-capabilities/text/generate-text#adding-encrypted-thinking-content) for more details on how to use the content.13The reasoning content is encrypted by us and can be returned if you pass `include: ["reasoning.encrypted_content"]` to the Responses API. You can send the encrypted content back to provide more context to a previous conversation. See [Adding encrypted thinking content](/developers/model-capabilities/text/generate-text#adding-encrypted-thinking-content) for more details on how to use the content.

14 14 

15> [!NOTE]

16> Always returned for grok-4.7

17>

18> On the Responses API, `grok-4.7` returns `reasoning.encrypted_content` on every response, whether or not `include` lists it, together with the encrypted outputs of any server-side tools. Reasoning items in the output carry an `encrypted_content` field; pass them back unchanged in the next request's `input` so the model keeps its reasoning across turns even when you manage conversation history yourself. Unlike an explicit `include`, this default does not stop xAI from storing the thinking trace server-side for rehydration, so clients that ignore the field keep working as before; whether the response itself is stored for `previous_response_id` is governed by `store`, not by this setting. Chat Completions is unaffected; it has no field for the ciphertext.

19 

15> [!TIP]20> [!TIP]

16>21>

17> When using the Vercel AI SDK, encrypted reasoning content is automatically included under the hood as long as `store: false` is not specified. No additional configuration is needed.22> When using the Vercel AI SDK, encrypted reasoning content is automatically included under the hood as long as `store: false` is not specified. No additional configuration is needed.

18 23 

19## The `reasoning_effort` parameter24## The `reasoning_effort` parameter

20 25 

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

22 27 

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

24 29 


53)58)

54 59 

55chat = client.chat.create(60chat = client.chat.create(

56 model="grok-4.6",61 model="grok-4.7",

57 reasoning_effort="high",62 reasoning_effort="high",

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

59)64)


77)82)

78 83 

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

80 model="grok-4.6",85 model="grok-4.7",

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

82 input=[87 input=[

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


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

98 103 

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

100 model: xai.responses('grok-4.6'),105 model: xai.responses('grok-4.7'),

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

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

103 providerOptions: {108 providerOptions: {


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

115 -m 3600 \120 -m 3600 \

116 -d '{121 -d '{

117 "model": "grok-4.6",122 "model": "grok-4.7",

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

119 "input": [124 "input": [

120 {125 {


137 142 

138| Model | `reasoning` parameter | Behavior |143| Model | `reasoning` parameter | Behavior |

139|---|---|---|144|---|---|---|

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

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

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

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

143 149 

144## Summarized Reasoning Content150## Summarized Reasoning Content

145 151 

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:152For `grok-4.7`, 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:

147 153 

148```python customLanguage="pythonXAI"154```python customLanguage="pythonXAI"

149import os155import os


157)163)

158 164 

159chat = client.chat.create(165chat = client.chat.create(

160 model="grok-4.6",166 model="grok-4.7",

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

162)168)

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²)"))169chat.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²)"))


184)190)

185 191 

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

187 model="grok-4.6",193 model="grok-4.7",

188 input=[194 input=[

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

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²)"},196 {"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²)"},


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

204 210 

205const result = streamText({211const result = streamText({

206 model: xai.responses('grok-4.6'),212 model: xai.responses('grok-4.7'),

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

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²)'214 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²)'

209});215});


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²)"239 "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²)"

234 }240 }

235 ],241 ],

236 "model": "grok-4.6",242 "model": "grok-4.7",

237 "stream": true243 "stream": true

238}'244}'

239```245```

Details

26 timeout=3600,26 timeout=3600,

27)27)

28 28 

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

30chat.append(30chat.append(

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

32)32)


53)53)

54 54 

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

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

57 messages=[57 messages=[

58 {"role": "system", "content": "You are Grok, a helpful and useful AI built by xAI."},58 {"role": "system", "content": "You are Grok, a helpful and useful 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."},


75});75});

76 76 

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

78 model: "grok-4.6",78 model: "grok-4.7",

79 messages: [79 messages: [

80 { role: "system", content: "You are Grok, a helpful and useful AI built by xAI." },80 { role: "system", content: "You are Grok, a helpful and useful AI built by xAI." },

81 {81 {


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

100 100 

101const result = streamText({101const result = streamText({

102 model: xai.responses('grok-4.6'),102 model: xai.responses('grok-4.7'),

103 system:103 system:

104 "You are Grok, a helpful and useful AI built by xAI.",104 "You are Grok, a helpful and useful AI built by xAI.",

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


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

127 }127 }

128 ],128 ],

129 "model": "grok-4.6",129 "model": "grok-4.7",

130 "stream": true130 "stream": true

131}'131}'

132```132```


136```json136```json

137data: {137data: {

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

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

140 "choices":[{"index":0,"delta":{"reasoning_content":"The","role":"assistant"}}],140 "choices":[{"index":0,"delta":{"reasoning_content":"The","role":"assistant"}}],

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

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


145 145 

146data: {146data: {

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

148 "model":"grok-4.6",148 "model":"grok-4.7",

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

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

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


154 154 

155data: {155data: {

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

157 "model":"grok-4.6",157 "model":"grok-4.7",

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

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

160 "prompt_tokens_details":{"text_tokens":41,"audio_tokens":0,"image_tokens":0,"cached_tokens":0}},160 "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.6")267chat = client.chat.create(model="grok-4.7")

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.6",341 model="grok-4.7",

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.6",398 model: "grok-4.7",

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.6'),452 model: xai.responses('grok-4.7'),

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.6",545 model="grok-4.7",

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.6",572 model="grok-4.7",

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.6",603 model: "grok-4.7",

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.6",687 model="grok-4.7",

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.6",758 model="grok-4.7",

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.6",780 model="grok-4.7",

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.6",833 model: "grok-4.7",

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.6",858 model: "grok-4.7",

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.6",950 model="grok-4.7",

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.6",1003 model="grok-4.7",

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.6`) 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.7`) 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.6",54 "model": "grok-4.7",

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.6")66chat = client.chat.create(model="grok-4.7")

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.6",81 model="grok-4.7",

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.6'),93 model: xai.responses('grok-4.7'),

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.6',109 model: 'grok-4.7',

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 +4 −3

Details

33 33 

34| Model | RPS | TPM |34| Model | RPS | TPM |

35| --- | --- | --- |35| --- | --- | --- |

36| grok-4.7 | T0: 150, T1: 172, T2: 208, T3: 312, T4: 500 | T0: 50M, T1: 53M, T2: 60M, T3: 74M, T4: 100M |

36| grok-4.6 | T0: 150, T1: 172, T2: 208, T3: 312, T4: 500 | T0: 50M, T1: 53M, T2: 60M, T3: 74M, T4: 100M |37| grok-4.6 | 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 |38| grok-4.5 | T0: 150, T1: 172, T2: 208, T3: 312, T4: 500 | T0: 50M, T1: 53M, T2: 60M, T3: 74M, T4: 100M |

38| grok-4.3 | T0: 37, T1: 50, T2: 75, T3: 125, T4: 208 | T0: 10M, T1: 15M, T2: 25M, T3: 45M, T4: 85M |39| grok-4.3 | 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 |41| 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 |

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 |42| grok-build-0.1 | T0: 37, T1: 50, T2: 75, T3: 125, T4: 208 | T0: 10M, T1: 15M, T2: 25M, T3: 45M, T4: 85M |

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 |43| 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 |

44| grok-imagine-image-quality | T0: 6, T1: 12, T2: 25, T3: 50, T4: 100 | — |

43| grok-imagine-image-2.0 | T0: 6, T1: 12, T2: 25, T3: 50, T4: 100 | — |45| grok-imagine-image-2.0 | T0: 6, T1: 12, T2: 25, T3: 50, T4: 100 | — |

44| grok-imagine-image | T0: 6, T1: 12, T2: 25, T3: 50, T4: 100 | — |46| grok-imagine-image | T0: 6, T1: 12, T2: 25, T3: 50, T4: 100 | — |

45| grok-imagine-image-quality | T0: 6, T1: 12, T2: 25, T3: 50, T4: 100 | — |

46| grok-imagine-video | T0: 10, T1: 20, T2: 39, T3: 79, T4: 158 | — |47| grok-imagine-video | T0: 10, T1: 20, T2: 39, T3: 79, T4: 158 | — |

47| grok-imagine-video-1.5 | T0: 10, T1: 20, T2: 39, T3: 79, T4: 158 | — |48| grok-imagine-video-1.5 | T0: 10, T1: 20, T2: 39, T3: 79, T4: 158 | — |

48 49 


80 for attempt in range(max_retries):81 for attempt in range(max_retries):

81 try:82 try:

82 return client.chat.completions.create(83 return client.chat.completions.create(

83 model="grok-4.6",84 model="grok-4.7",

84 messages=messages,85 messages=messages,

85 )86 )

86 except RateLimitError:87 except RateLimitError:


99client = Client(api_key=os.getenv("XAI_API_KEY"))100client = Client(api_key=os.getenv("XAI_API_KEY"))

100 101 

101def request_with_backoff(prompt, max_retries=5):102def request_with_backoff(prompt, max_retries=5):

102 chat = client.chat.create(model="grok-4.6")103 chat = client.chat.create(model="grok-4.7")

103 chat.append(user(prompt))104 chat.append(user(prompt))

104 for attempt in range(max_retries):105 for attempt in range(max_retries):

105 try:106 try:

Details

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

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

247 -d '{247 -d '{

248 "model": "grok-4.6",248 "model": "grok-4.7",

249 "input": "What is the meaning of life?"249 "input": "What is the meaning of life?"

250 }'250 }'

251```251```


255import { generateText } from "ai";255import { generateText } from "ai";

256 256 

257const result = await generateText({257const result = await generateText({

258 model: xai.responses("grok-4.6"),258 model: xai.responses("grok-4.7"),

259 prompt: "What is the meaning of life?",259 prompt: "What is the meaning of life?",

260});260});

261 261 


273)273)

274 274 

275response = client.responses.create(275response = client.responses.create(

276 model="grok-4.6",276 model="grok-4.7",

277 input="What is the meaning of life?",277 input="What is the meaning of life?",

278)278)

279 279 


289});289});

290 290 

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

292 model: "grok-4.6",292 model: "grok-4.7",

293 input: "What is the meaning of life?",293 input: "What is the meaning of life?",

294});294});

295 295 


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

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

651 -d '{651 -d '{

652 "model": "grok-4.6",652 "model": "grok-4.7",

653 "input": [653 "input": [

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

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


671)671)

672 672 

673compacted = client.responses.compact(673compacted = client.responses.compact(

674 model="grok-4.6",674 model="grok-4.7",

675 input=[675 input=[

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

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


707});707});

708 708 

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

710 model: "grok-4.6",710 model: "grok-4.7",

711 input: [711 input: [

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

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

Details

86 ),86 ),

87 ]87 ]

88 88 

89 model = "grok-4.6"89 model = "grok-4.7"

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.6"220 model = "grok-4.7"

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.6", # reasoning model385 model="grok-4.7", # 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.6", # reasoning model397 model="grok-4.7", # 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.6", # reasoning model430 model="grok-4.7", # 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.6", # reasoning model515 model="grok-4.7", # 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.6",558 model="grok-4.7",

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.6",588 "model": "grok-4.7",

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.6",613 "model": "grok-4.7",

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.6", # reasoning model644 model="grok-4.7", # 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.6",669 model="grok-4.7",

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.6",700 "model": "grok-4.7",

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.6",726 "model": "grok-4.7",

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.6", # reasoning model760 model="grok-4.7", # 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.6",62 "model": "grok-4.7",

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.6",79 model="grok-4.7",

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.6",104 model="grok-4.7",

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.6'),126 model: xai.responses('grok-4.7'),

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.6',149 model: 'grok-4.7',

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.6",180 model="grok-4.7",

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.6",209 "model": "grok-4.7",

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.6",231 "model": "grok-4.7",

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.6",287 "model": "grok-4.7",

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.6'),387 model: xai.responses('grok-4.7'),

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.6", # reasoning model51 model="grok-4.7", # 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.6",92 model="grok-4.7",

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.6",119 "model": "grok-4.7",

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.6",141 "model": "grok-4.7",

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.6'),161 model: xai.responses('grok-4.7'),

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.6", # reasoning model183 model="grok-4.7", # 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.6'),253 model: xai.responses('grok-4.7'),

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.6'),269 model: xai.responses('grok-4.7'),

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.6` for better code generation315* **Model**: Use reasoning models like `grok-4.7` 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.6",24 "model": "grok-4.7",

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.6",72 model="grok-4.7",

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.6",119 model="grok-4.7",

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.6",131 model="grok-4.7",

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.6'),148 model: xai.responses('grok-4.7'),

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.6",292 model="grok-4.7",

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.6",328 model="grok-4.7",

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.6'),450 model: xai.responses('grok-4.7'),

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

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

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

26 -d '{26 -d '{

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

28 "input": "Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",28 "input": "Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",

29 "tools": [29 "tools": [

30 {30 {


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

46 46 

47chat = client.chat.create(47chat = client.chat.create(

48 model="grok-4.6",48 model="grok-4.7",

49 tools=[image_generation()],49 tools=[image_generation()],

50)50)

51chat.append(user("Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print"))51chat.append(user("Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print"))


68)68)

69 69 

70response = client.responses.create(70response = client.responses.create(

71 model="grok-4.6",71 model="grok-4.7",

72 input="Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",72 input="Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",

73 tools=[{"type": "image_generation"}],73 tools=[{"type": "image_generation"}],

74)74)


96 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}",96 "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}",

97}97}

98payload = {98payload = {

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

100 "input": "Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",100 "input": "Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",

101 "tools": [{"type": "image_generation"}],101 "tools": [{"type": "image_generation"}],

102}102}


119});119});

120 120 

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

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

123 input:123 input:

124 "Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",124 "Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",

125 tools: [{ type: "image_generation" }],125 tools: [{ type: "image_generation" }],


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

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

169 -d '{169 -d '{

170 "model": "grok-4.6",170 "model": "grok-4.7",

171 "input": "Generate an image of a hot air balloon over the desert",171 "input": "Generate an image of a hot air balloon over the desert",

172 "tools": [172 "tools": [

173 {173 {


180 180 

181```python customLanguage="pythonXAI"181```python customLanguage="pythonXAI"

182chat = client.chat.create(182chat = client.chat.create(

183 model="grok-4.6",183 model="grok-4.7",

184 tools=[image_generation(action="generate")],184 tools=[image_generation(action="generate")],

185)185)

186chat.append(user("Generate an image of a hot air balloon over the desert"))186chat.append(user("Generate an image of a hot air balloon over the desert"))


189 189 

190```python customLanguage="pythonOpenAISDK"190```python customLanguage="pythonOpenAISDK"

191response = client.responses.create(191response = client.responses.create(

192 model="grok-4.6",192 model="grok-4.7",

193 input="Generate an image of a hot air balloon over the desert",193 input="Generate an image of a hot air balloon over the desert",

194 tools=[{"type": "image_generation", "action": "generate"}],194 tools=[{"type": "image_generation", "action": "generate"}],

195)195)


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

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

206 -d '{206 -d '{

207 "model": "grok-4.6",207 "model": "grok-4.7",

208 "input": [208 "input": [

209 {209 {

210 "role": "user",210 "role": "user",


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

240 240 

241chat = client.chat.create(241chat = client.chat.create(

242 model="grok-4.6",242 model="grok-4.7",

243 tools=[image_generation(action="edit")],243 tools=[image_generation(action="edit")],

244)244)

245chat.append(245chat.append(


266)266)

267 267 

268response = client.responses.create(268response = client.responses.create(

269 model="grok-4.6",269 model="grok-4.7",

270 input=[270 input=[

271 {271 {

272 "role": "user",272 "role": "user",


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

311 311 

312chat = client.chat.create(312chat = client.chat.create(

313 model="grok-4.6",313 model="grok-4.7",

314 tools=[image_generation()],314 tools=[image_generation()],

315)315)

316 316 


340)340)

341 341 

342response = client.responses.create(342response = client.responses.create(

343 model="grok-4.6",343 model="grok-4.7",

344 input="Generate an image of a lighthouse on a rocky coast",344 input="Generate an image of a lighthouse on a rocky coast",

345 tools=[{"type": "image_generation"}],345 tools=[{"type": "image_generation"}],

346)346)


357 357 

358# Follow up: edit the image from the previous turn358# Follow up: edit the image from the previous turn

359followup = client.responses.create(359followup = client.responses.create(

360 model="grok-4.6",360 model="grok-4.7",

361 previous_response_id=response.id,361 previous_response_id=response.id,

362 input="Make it night time with a full moon",362 input="Make it night time with a full moon",

363 tools=[{"type": "image_generation"}],363 tools=[{"type": "image_generation"}],


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

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

387 -d '{387 -d '{

388 "model": "grok-4.6",388 "model": "grok-4.7",

389 "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.",389 "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.",

390 "tools": [390 "tools": [

391 {391 {


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

410 410 

411chat = client.chat.create(411chat = client.chat.create(

412 model="grok-4.6",412 model="grok-4.7",

413 tools=[web_search(), image_generation()],413 tools=[web_search(), image_generation()],

414)414)

415chat.append(415chat.append(


440)440)

441 441 

442response = client.responses.create(442response = client.responses.create(

443 model="grok-4.6",443 model="grok-4.7",

444 input=(444 input=(

445 "Find out which team won the most recent FIFA World Cup, then generate an "445 "Find out which team won the most recent FIFA World Cup, then generate an "

446 "image of a celebratory poster for that team, in a vintage travel-poster style."446 "image of a celebratory poster for that team, in a vintage travel-poster style."


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

483 483 

484chat = client.chat.create(484chat = client.chat.create(

485 model="grok-4.6",485 model="grok-4.7",

486 tools=[image_generation()],486 tools=[image_generation()],

487 include=["verbose_streaming"],487 include=["verbose_streaming"],

488)488)


512)512)

513 513 

514stream = client.responses.create(514stream = client.responses.create(

515 model="grok-4.6",515 model="grok-4.7",

516 input="Generate an image of an origami fox in a paper forest",516 input="Generate an image of an origami fox in a paper forest",

517 tools=[{"type": "image_generation"}],517 tools=[{"type": "image_generation"}],

518 stream=True,518 stream=True,


540});540});

541 541 

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

543 model: "grok-4.6",543 model: "grok-4.7",

544 input: "Generate an image of an origami fox in a paper forest",544 input: "Generate an image of an origami fox in a paper forest",

545 tools: [{ type: "image_generation" }],545 tools: [{ type: "image_generation" }],

546 stream: true,546 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.6",41 "model": "grok-4.7",

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.6",66 model="grok-4.7",

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.6",93 model="grok-4.7",

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.6'),115 model: xai.responses('grok-4.7'),

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.6",142 model: "grok-4.7",

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.6",39 model="grok-4.7",

40 tools=[40 tools=[

41 mcp(server_url="https://mcp.deepwiki.com/mcp", server_label="deepwiki"),41 mcp(server_url="https://mcp.deepwiki.com/mcp", server_label="deepwiki"),

42 ],42 ],


76)76)

77 77 

78response = client.responses.create(78response = client.responses.create(

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

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.6",108 "model": "grok-4.7",

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.6",132 "model": "grok-4.7",

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.6",176 model="grok-4.7",

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.6",26 model="grok-4.7",

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.6'),58 model: xai.responses('grok-4.7'),

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.6",91 model="grok-4.7",

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.6'),121 model: xai.responses('grok-4.7'),

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.6",152 model="grok-4.7",

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.6",181 model="grok-4.7",

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.6",206 "model": "grok-4.7",

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.6",247 model="grok-4.7",

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.6",125 model="grok-4.7",

126 tools=[126 tools=[

127 web_search(),127 web_search(),

128 x_search(),128 x_search(),