grok-4.7
最后更新:2026-11-14
POSThttps://www.sagelib.com/chat/completions
grok-4.7 模型的聊天生成接口,OpenAI兼容,支持多轮上下文、流式输出、工具调用、结构化输出等。
接口鉴权方式请参考:API接入与鉴权
请求参数
请求头
| 参数名称 | 描述 |
|---|---|
*Authorization string |
认证令牌 |
*Content-Type string |
内容类型 |
Body 参数
| 参数名称 | 描述 |
|---|---|
*model string |
可选值:grok-4.7 要使用的模型 ID,置于请求体顶层 |
*messages array |
对话消息数组;role 支持 system / user / assistant / tool / developer,content 可为纯字符串或内容块数组 |
stream boolean |
默认值:false 可选值:true、false 是否以 SSE 流式返回;true 时按 chunk 增量返回 delta |
stream_options object |
可选值:include_usage: true (required sub-field) 流式附加选项,仅在 stream=true 时有效;include_usage=true 时在最后一个 chunk 附加 usage 统计 |
temperature number |
默认值:1 可选值:0 - 2 采样温度,值越高输出越随机 |
top_p number |
默认值:1 可选值:(0, 1] 核采样,按累积概率质量截断候选词集合;取值须大于 0 |
max_tokens integer |
可选值:1 - 450000 单次生成的最大 token 数,含可见输出 token 与推理 token |
seed integer |
可选值:>= 1 随机种子(Beta 特性);相同 seed 与参数下尽力保证输出确定性 |
user string |
终端用户唯一标识,用于 xAI 侧滥用监测与审计 |
service_tier string |
默认值:default 可选值:default / priority 请求处理层级;priority 为更高调度优先级(更高 token 单价) |
reasoning_effort string |
默认值:high 可选值:low / medium / high / xhigh 推理强度,xhigh 为最大推理深度;grok-4.7 为推理模型,推理不可关闭,无 none 档位 |
tools array |
可供模型调用的工具列表,JSON Schema 函数定义 |
tool_choice string |
默认值:auto 可选值:none / auto / required, or an object forcing a specific tool 工具选择策略;required=必须调用至少一个工具 |
parallel_tool_calls boolean |
默认值:true 可选值:true、false 是否允许模型在单次响应中并行发起多个工具调用 |
response_format object |
可选值:type:text / type:json_object / type:json_schema 输出格式约束对象;json_schema 按给定 JSON Schema 严格约束输出结构 |
store_messages boolean |
默认值:false 可选值:true、false 是否在 xAI 后端持久化本次生成的响应 |
use_encrypted_content boolean |
默认值:false 可选值:true、false 是否返回加密的推理内容;启用后响应携带加密推理轨迹 |
max_turns integer |
模型可自动执行的 agentic 轮次上限 |
请求示例
curl -v 'https://www.sagelib.com/chat/completions' \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{
"model": "grok-4.7",
"messages": [
{
"role": "user",
"content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
]
}'
import json
import requests
# Configure base variables
base_url = "https://www.sagelib.com" # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***" # Replace with your Bearer token
url = f"https://www.sagelib.com/chat/completions"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
data = {
"model": "grok-4.7",
"messages": [
{
"role": "user",
"content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
]
}
# Send the POST request
response = requests.post(url, headers=headers, json=data)
# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class LlmStreamClient {
public static void main(String[] args) {
String baseUrl = "https://www.sagelib.com";
String apiKey = "***";
String url = "https://www.sagelib.com/chat/completions";
String jsonRequestBody = """
{
"model": "grok-4.7",
"messages": [
{
"role": "user",
"content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
]
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
.build();
try {
HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith("data:")) {
String data = line.substring(5).trim();
if ("[DONE]".equals(data)) break;
System.out.println("Received stream chunk: " + data);
}
}
}
} catch (Exception e) { e.printStackTrace(); }
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func main() {
baseUrl := "https://www.sagelib.com"
apiKey := "***"
url := "https://www.sagelib.com/chat/completions"
jsonRequestBody := `
{
"model": "grok-4.7",
"messages": [
{
"role": "user",
"content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
}
]
}
`
req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
if err != nil { fmt.Println("Failed to create request:", err); return }
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil { fmt.Println("Request failed:", err); return }
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var prettyBody map[string]interface{}
if err := json.Unmarshal(body, &prettyBody); err == nil {
pretty, _ := json.MarshalIndent(prettyBody, "", " ")
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(pretty))
} else {
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(body))
}
}
curl -v 'https://www.sagelib.com/chat/completions' \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{
"messages": [
{
"content": "How is the weather in Beijing today? Please use a tool to query.",
"role": "user"
}
],
"model": "grok-4.7",
"tool_choice": "required",
"tools": [
{
"function": {
"description": "Get weather information for a specified city",
"name": "get_weather",
"parameters": {
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
],
"type": "object"
}
},
"type": "function"
}
]
}'
import json
import requests
# Configure base variables
base_url = "https://www.sagelib.com" # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***" # Replace with your Bearer token
url = f"https://www.sagelib.com/chat/completions"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
data = {
"messages": [
{
"content": "How is the weather in Beijing today? Please use a tool to query.",
"role": "user"
}
],
"model": "grok-4.7",
"tool_choice": "required",
"tools": [
{
"function": {
"description": "Get weather information for a specified city",
"name": "get_weather",
"parameters": {
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
],
"type": "object"
}
},
"type": "function"
}
]
}
# Send the POST request
response = requests.post(url, headers=headers, json=data)
# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class LlmStreamClient {
public static void main(String[] args) {
String baseUrl = "https://www.sagelib.com";
String apiKey = "***";
String url = "https://www.sagelib.com/chat/completions";
String jsonRequestBody = """
{
"messages": [
{
"content": "How is the weather in Beijing today? Please use a tool to query.",
"role": "user"
}
],
"model": "grok-4.7",
"tool_choice": "required",
"tools": [
{
"function": {
"description": "Get weather information for a specified city",
"name": "get_weather",
"parameters": {
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
],
"type": "object"
}
},
"type": "function"
}
]
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
.build();
try {
HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith("data:")) {
String data = line.substring(5).trim();
if ("[DONE]".equals(data)) break;
System.out.println("Received stream chunk: " + data);
}
}
}
} catch (Exception e) { e.printStackTrace(); }
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func main() {
baseUrl := "https://www.sagelib.com"
apiKey := "***"
url := "https://www.sagelib.com/chat/completions"
jsonRequestBody := `
{
"messages": [
{
"content": "How is the weather in Beijing today? Please use a tool to query.",
"role": "user"
}
],
"model": "grok-4.7",
"tool_choice": "required",
"tools": [
{
"function": {
"description": "Get weather information for a specified city",
"name": "get_weather",
"parameters": {
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
],
"type": "object"
}
},
"type": "function"
}
]
}
`
req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
if err != nil { fmt.Println("Failed to create request:", err); return }
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil { fmt.Println("Request failed:", err); return }
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var prettyBody map[string]interface{}
if err := json.Unmarshal(body, &prettyBody); err == nil {
pretty, _ := json.MarshalIndent(prettyBody, "", " ")
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(pretty))
} else {
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(body))
}
}
curl -v 'https://www.sagelib.com/chat/completions' \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{
"model": "grok-4.7",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Describe the content of this image, including the subject, scene, tone, and style."
},
{
"type": "image_url",
"image_url": {
"url": "${image_url}"
}
}
]
}
]
}'
import json
import requests
# Configure base variables
base_url = "https://www.sagelib.com" # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***" # Replace with your Bearer token
url = f"https://www.sagelib.com/chat/completions"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
data = {
"model": "grok-4.7",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Describe the content of this image, including the subject, scene, tone, and style."
},
{
"type": "image_url",
"image_url": {
"url": "${image_url}"
}
}
]
}
]
}
# Send the POST request
response = requests.post(url, headers=headers, json=data)
# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class LlmStreamClient {
public static void main(String[] args) {
String baseUrl = "https://www.sagelib.com";
String apiKey = "***";
String url = "https://www.sagelib.com/chat/completions";
String jsonRequestBody = """
{
"model": "grok-4.7",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Describe the content of this image, including the subject, scene, tone, and style."
},
{
"type": "image_url",
"image_url": {
"url": "${image_url}"
}
}
]
}
]
}
""";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
.build();
try {
HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith("data:")) {
String data = line.substring(5).trim();
if ("[DONE]".equals(data)) break;
System.out.println("Received stream chunk: " + data);
}
}
}
} catch (Exception e) { e.printStackTrace(); }
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func main() {
baseUrl := "https://www.sagelib.com"
apiKey := "***"
url := "https://www.sagelib.com/chat/completions"
jsonRequestBody := `
{
"model": "grok-4.7",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Describe the content of this image, including the subject, scene, tone, and style."
},
{
"type": "image_url",
"image_url": {
"url": "${image_url}"
}
}
]
}
]
}
`
req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
if err != nil { fmt.Println("Failed to create request:", err); return }
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil { fmt.Println("Request failed:", err); return }
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var prettyBody map[string]interface{}
if err := json.Unmarshal(body, &prettyBody); err == nil {
pretty, _ := json.MarshalIndent(prettyBody, "", " ")
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(pretty))
} else {
fmt.Println("Status Code:", resp.StatusCode)
fmt.Println(string(body))
}
}
响应参数
Body 参数
| 参数名称 | 描述 |
|---|---|
id string |
响应唯一标识 |
object string |
固定为 chat.completion |
created integer |
Unix 时间戳 |
model string |
实际使用的模型名 |
choices array |
候选回复列表 |
index integer |
候选序号 |
message object |
回复消息对象 |
role string |
固定为 assistant |
content string |
可见文本输出 |
reasoning_content string |
推理过程文本(xAI 特有字段,非标准 OpenAI 字段) |
tool_calls array |
工具调用结果,含 id / type / function.name / function.arguments |
finish_reason string |
stop(正常结束)/ tool_calls(触发工具调用)/ length(达到上限) |
service_tier string |
实际使用的服务层级 |
usage object |
Token 使用统计 |
prompt_tokens integer |
输入 token 数 |
completion_tokens integer |
输出 token 数(含推理 token) |
total_tokens integer |
总 token 数 |
completion_tokens_details object |
输出 token 细分 |
reasoning_tokens integer |
推理 token 数 |
prompt_tokens_details object |
输入 token 细分 |
cached_tokens integer |
命中缓存的输入 token 数 |