关键信息
成本追踪
xAI API 的每个 inference response 都包含该请求实际收取的精确费用,并通过 chat completion、Responses API、图像生成和视频生成 response 的 cost_in_usd_ticks object 中的 usage 字段返回。
费用按请求计算:无论是简单 completion、streaming response,还是使用 server-side tool 的 Agent loop,每次调用都会返回该单独请求的费用。这是应用所有适用折扣(包括 prompt caching 减免)后的实际计费金额,包含全部 token 费用和 server-side tool 调用费用。无需估算,也无需事后查询账单。
工作原理
费用以 tick 表示,其中 1 USD = 10,000,000,000 tick(10^10)。换算为美元:
cost_usd = cost_in_usd_ticks / 10,000,000,000例如,费用为 "cost_in_usd_ticks": 37756000 的 response 成本为 $0.0038;费用为 "cost_in_usd_ticks": 200000000 的图像生成成本为 $0.02。
Tick 用于提供精确度:它可以表示低至几分之一美分的费用,且不存在 floating-point rounding。当你处理数千个请求并需要准确汇总时,这一点非常重要。
从 Response 中读取费用
xAI SDK
xAI SDK 提供 cost_usd convenience property,可自动将 tick 换算为美元。如需 integer precision,也可以通过 response.usage.cost_in_usd_ticks 访问 raw tick:
import os
from xai_sdk import Client
from xai_sdk.chat import user
client = Client(api_key=os.getenv("XAI_API_KEY"))
chat = client.chat.create(
model="grok-4.5",
messages=[user("Say hello")],
)
response = chat.sample()
# Convenience property — ticks converted to dollars.
print(f"Cost: ${response.cost_usd:.6f}")
# Raw ticks for integer-precision accounting.
print(f"Cost (ticks): {response.usage.cost_in_usd_ticks}")Chat Completions 与 Responses API
每个 REST completion 和 response 中的 usage object 都包含 cost_in_usd_ticks:
"usage": {
"input_tokens": 199,
"output_tokens": 1,
"total_tokens": 200,
"cost_in_usd_ticks": 158500
}Streaming
使用 xAI SDK 进行 streaming 时,每个 chunk 都包含持续更新的 cost_in_usd_ticks total;最后一个 chunk 反映该请求的最终费用。组装后的 Response object 会自动包含该值。
使用 OpenAI SDK 或 REST API 时,请在请求中设置 stream_options: { include_usage: true }。费用仅包含在最后一个 chunk 中(其 choices 为空);中间 chunk 不包含 usage data。
import os
from xai_sdk import Client
from xai_sdk.chat import user
client = Client(api_key=os.getenv("XAI_API_KEY"))
chat = client.chat.create(
model="grok-4.5",
messages=[user("Tell me a joke")],
)
for response, chunk in chat.stream():
print(chunk.content, end="", flush=True)
print()
# After the stream completes, cost is on the final response.
print(f"Cost: ${response.cost_usd:.6f}")追踪整个对话的费用
cost_in_usd_ticks 按请求计算,不会跨 turn 累积。在 multi-turn conversation 中,需要自行汇总费用:
import os
from xai_sdk import Client
from xai_sdk.chat import system, user
client = Client(api_key=os.getenv("XAI_API_KEY"))
chat = client.chat.create(
model="grok-4.5",
messages=[system("You are a helpful assistant.")],
)
total_cost_usd = 0.0
while True:
prompt = input("You: ")
if prompt.lower() == "exit":
break
chat.append(user(prompt))
response = chat.sample()
print(f"Grok: {response.content}")
chat.append(response)
total_cost_usd += response.cost_usd or 0.0
print(f" (this turn: ${response.cost_usd or 0:.6f})")
print(f"Total session cost: ${total_cost_usd:.4f}")Server-side Tool
当请求使用 server-side tool(web search、X search、code execution)时,model 可能在返回最终答案前进行多次内部调用。返回的 cost_in_usd_ticks 会以单个值涵盖该请求的全部 token 费用和所有 tool 调用费用,无需单独累加。
import os
from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import web_search, x_search
client = Client(api_key=os.getenv("XAI_API_KEY"))
chat = client.chat.create(
model="grok-4.5",
tools=[web_search(), x_search()],
)
chat.append(user("What are people saying about xAI's latest announcement?"))
response = chat.sample()
print(response.content)
# Shows which server-side tools were invoked and how many times.
print(f"Tools used: {response.server_side_tool_usage}")
# Cost covers all model decodes + every tool call in the agentic loop.
print(f"Cost: ${response.cost_usd:.4f}")图像与视频生成
图像和视频 response 的 cost_in_usd_ticks object 中也包含相同的 usage 字段:
# Image generation
curl https://api.x.ai/v1/images/generations \
-H "Authorization: Bearer $XAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "grok-imagine-image-quality",
"prompt": "A cat on a rocket"
}' | jq '.usage.cost_in_usd_ticks'
# => 200000000 ($0.02)Batch API
Batch result 包含每个请求的费用。可以将其汇总得到 batch 总费用,也可以直接读取 batch object 上的 cost_breakdown。详情请参阅 Batch API。