新集成应使用
POST /v1/responses。这篇客户端发送简单 input,并从output_text/ output 列表抽取文本(mock 形状已对齐教学需要)。
先看清成品
- mock 返回
[responses] …。- 1 项 pytest 通过。
合规提醒:Grok 可结合网页与 X 平台实时信息,实时内容未必准确,重要结论须核对可靠来源。API 密钥在 console.x.ai 管理,勿提交公开仓库。遵守 xAI 使用政策;勿用于骚扰、欺诈或未授权自动化。价格与套餐以官网为准。
运行说明:无正式
XAI_API_KEY。A/B 用 mock;对官方api.x.ai无效密钥实测 HTTP 400(Incorrect API key)。C 校验 search_parameters。Chat Completions 在文档中标为 legacy,新集成优先 Responses。2026-10-23(Asia/Shanghai)pytest 通过。
做完之后你会得到什么?
| 成果 | 说明 |
|---|---|
grok_responses.py |
Responses 客户端 |
mock_xai.py |
假服务 |
test_105b.py |
测试 |
需要准备哪些环境?
| 项目 | 说明 |
|---|---|
| Python | 3.10+ |
| 环境变量 | XAI_API_KEY |
关键事实
| 事实 | 来源 |
|---|---|
| Responses 是推荐的新集成面 | 官方文档导向 |
| 响应结构可能含 output 数组;本客户端做了简易抽取 | 实践 |
| 正式字段以 API Reference 为准,mock 仅教学 | 重要 |
文件结构
105-grok-B-src/
├── grok_responses.py
├── mock_xai.py
└── test_105b.py
第 1 步:客户端
#!/usr/bin/env python3
"""xAI Responses API client (recommended for new Grok integrations)."""
from __future__ import annotations
import argparse, json, os, sys, urllib.error, urllib.request
def create_response(base, key, model, text):
payload = {
"model": model,
"input": [{"role": "user", "content": text}],
}
req = urllib.request.Request(
f"{base.rstrip('/')}/v1/responses",
data=json.dumps(payload).encode(),
headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=120) as resp:
return json.loads(resp.read().decode())
except urllib.error.HTTPError as e:
raise SystemExit(f"HTTP {e.code}: {e.read().decode(errors='replace')}") from e
def extract_text(r: dict) -> str:
if r.get("output_text"):
return r["output_text"]
for item in r.get("output") or []:
for c in item.get("content") or []:
if c.get("type") in ("output_text", "text") and c.get("text"):
return c["text"]
return json.dumps(r, ensure_ascii=False)
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("message", nargs="?", default="Explain neural nets in two sentences.")
ap.add_argument("--base", default=os.environ.get("XAI_BASE_URL", "https://api.x.ai"))
ap.add_argument("--key", default=os.environ.get("XAI_API_KEY", ""))
ap.add_argument("--model", default=os.environ.get("XAI_MODEL", "grok-4"))
args = ap.parse_args(argv)
if not args.key:
print("设置 XAI_API_KEY", file=sys.stderr); return 2
r = create_response(args.base, args.key, args.model, args.message)
print(extract_text(r))
return 0
if __name__ == "__main__":
raise SystemExit(main())
第 2 步:测试
import subprocess, sys, time
from pathlib import Path
HERE = Path(__file__).resolve().parent
def test_responses():
port = 19151
proc = subprocess.Popen([sys.executable, str(HERE/"mock_xai.py"), "--port", str(port)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
time.sleep(0.3)
r = subprocess.run([sys.executable, str(HERE/"grok_responses.py"), "ping", "--base", f"http://127.0.0.1:{port}", "--key", "xai-test-key"], capture_output=True, text=True, check=True)
assert "ping" in r.stdout and "responses" in r.stdout
finally:
proc.terminate(); proc.wait(timeout=5)
第 3 步:运行
$ pytest responses
. [100%]
1 passed in 0.36s
怎么检查结果?
- 输出含 responses 标记(mock)。
- 正式环境打印模型文本。
调试示例
抽取不到文本。 打印完整 JSON 对照 API Reference;字段名随版本可能调整,抽一层适配器比改业务代码便宜。
常见问题
| 现象 | 原因 | 处理 |
|---|---|---|
| 与 chat 并存 | 可以 | 新功能优先 responses |
| 工具/搜索 | 见 Live Search | 先校验参数 C 篇 |
| 超时 | 加长 timeout | 或异步方案 |
模板规则
- 新代码默认 Responses。
- 适配器隔离字段变化。
- 密钥轮换可审计。
项目资源
| 用途 | 地址 |
|---|---|
| Docs 首页(官方) | https://docs.x.ai/ |
| API Reference(官方) | https://docs.x.ai/docs/api-reference |
| xAI 官网 | https://x.ai/ |
Responses 跑通,再叠加搜索与工具。