AI 工具

xAI Grok Live Search:search_parameters 本地校验

实时搜索相关请求常带 searchparameters(mode、结果数、日期、sources、是否返回引用等)。本篇在发请求前做本地校验,并强调引用核对。

BINBHO · 图文教程

实时搜索相关请求常带 search_parameters(mode、结果数、日期、sources、是否返回引用等)。本篇在发请求前做本地校验,并强调引用核对。

先看清成品

  • sample_ok → OK;错误 mode/日期/过大结果数 → INVALID。
  • 3 项 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 通过。

做完之后你会得到什么?

成果 说明
search_guard.py 参数校验
样例 JSON ok/bad
test_105c.py 测试

需要准备哪些环境?

项目 说明
Python 3.10+

关键事实

事实 来源
Live Search 能力与参数以官方 Live Search 指南为准 官方
mode 常见 off/on/auto(本教程枚举) 教程约定 / 对照文档
实时结果可能过时或片面,必须看 citations 合规提醒

文件结构

105-grok-C-src/
├── search_guard.py
├── sample_ok.json
├── sample_bad.json
└── test_105c.py

第 1 步:校验脚本

#!/usr/bin/env python3
"""Validate xAI realtime search_parameters before sending a Grok request."""
from __future__ import annotations
import argparse, json
from pathlib import Path

MODES = {"off", "on", "auto"}

def validate(sp: dict) -> list[str]:
    errs = []
    if not isinstance(sp, dict):
        return ["search_parameters 须为对象"]
    mode = sp.get("mode")
    if mode is not None and mode not in MODES:
        errs.append(f"mode 须为 {sorted(MODES)}")
    msr = sp.get("max_search_results")
    if msr is not None:
        if not isinstance(msr, int) or msr < 1 or msr > 50:
            errs.append("max_search_results 建议 1..50(教程软限制)")
    for dkey in ("from_date", "to_date"):
        v = sp.get(dkey)
        if v is not None and not (isinstance(v, str) and len(v) == 10 and v[4] == "-" and v[7] == "-"):
            errs.append(f"{dkey} 应为 YYYY-MM-DD")
    sources = sp.get("sources")
    if sources is not None and not isinstance(sources, list):
        errs.append("sources 须为数组")
    # hygiene: if mode on, remind citations
    if mode in (None, "on", "auto") and sp.get("return_citations") is False:
        errs.append("实时搜索建议 return_citations=true 以便核对来源")
    return errs

def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("params_json")
    args = ap.parse_args(argv)
    sp = json.loads(Path(args.params_json).read_text(encoding="utf-8"))
    # allow wrapping
    if "search_parameters" in sp:
        sp = sp["search_parameters"]
    errs = validate(sp)
    if errs:
        print("INVALID")
        for e in errs: print("-", e)
        return 1
    print("OK")
    print(json.dumps(sp, ensure_ascii=False))
    return 0

if __name__ == "__main__":
    raise SystemExit(main())

第 2 步:测试

from pathlib import Path
import json, subprocess, sys
from search_guard import validate
HERE = Path(__file__).resolve().parent

def test_ok():
    assert validate(json.loads((HERE/"sample_ok.json").read_text())) == []

def test_bad():
    assert validate(json.loads((HERE/"sample_bad.json").read_text()))

def test_cli():
    r = subprocess.run([sys.executable, str(HERE/"search_guard.py"), str(HERE/"sample_ok.json")], capture_output=True, text=True)
    assert r.returncode == 0

第 3 步:运行

$ search_guard ok/bad
OK
{"mode": "auto", "max_search_results": 5, "from_date": "2026-10-01", "return_citations": true}

INVALID
- mode 须为 ['auto', 'off', 'on']
- max_search_results 建议 1..50(教程软限制)
- from_date 应为 YYYY-MM-DD

$ pytest -q
...                                                                      [100%]
3 passed in 0.03s

怎么检查结果?

  • OK 打印参数 JSON。
  • bad 列出 mode/日期/结果数等问题。

调试示例

关掉 return_citations 图省事。 校验会警告:没有来源就无法人工核对 X/网页上的实时说法。

常见问题

现象 原因 处理
日期格式 YYYY-MM-DD 不要写 10/01/2026
结果数很大 费配额且嘈杂 教程软上限 50
参数名变了 对照最新 Live Search 更新校验器

模板规则

  • 重要结论核对引用。
  • 不把实时传闻当事实。
  • 搜索参数先本地校验。

项目资源

用途 地址
Live Search 指南(官方) https://docs.x.ai/docs/guides/live-search
Docs(官方) https://docs.x.ai/
Console https://console.x.ai/

搜索能新,引用能证,才敢写进对外材料。