浏览文档
指南
为应用或智能体运行后台任务,从已保存的任务 ID 继续,并收集 Batch 中的每项结果。
本页内容
进程停止后继续任务
应用排队任务或可稍后完成的智能体流程适合使用后台任务。本流程运行一次 Google 搜索,保存回执,并让另一个进程通过该回执继续处理。
| 保存 | 用途 |
|---|---|
| 任务回执 | submission.json:将已接纳的任务 ID 与应用任务及原始输入一起保存。 |
| 已保存响应 | result.json:验证来源及结果后再导入。 |
| Batch 结果 | batch-results/outcomes.json:每项输入各有一条记录,包含任务 ID 及结果文件。 |
开始前
使用具备 google_search 权限且有可用额度的 API Key。提交、等待和获取结果时,选择 CLI 或 HTTP 并保持一致。Bash 示例需要 jq;HTTP 还需要 cURL 7.76+。请在新的工作目录中运行。
复用已认证的 CLI 配置档或 FLASHDATA_API_KEY,确认 data.accessVerified 为 true。命名配置请设置 FLASHDATA_PROFILE,使后续脚本也使用它。尚未配置密钥时,先按 CLI 认证指南设置。
flashdata auth status --json
flashdata account balance --json
flashdata account limits --json后续命令请在同一终端执行。智能体应从密钥存储或环境变量读取密钥。
# Bash: paste the key into a hidden prompt, not into this command.
read -r -s -p "FlashData API key: " FLASHDATA_API_KEY
printf '\n'
export FLASHDATA_API_KEY运行后台搜索
本流程提交一次 Google 搜索。检查状态和获取结果不会提交新查询。全程复用同一凭据。
1. 提交一次并保存回执
submission.json 是任务回执。HTTP 返回 id、source、status 以及 self/results 链接;CLI 将回执保存在 submission 中,并返回 remoteId。HTTP 200 表示已接受,不表示已完成。
flashdata search "battery recycling research" --num 5 \
--mode async --run-id async-first --output submission.json --json(
set -euC
: "${FLASHDATA_API_KEY:?Set FLASHDATA_API_KEY first}"
test ! -e submission.json || { echo "Use the saved receipt or a new filename." >&2; exit 1; }
curl --fail-with-body --silent --show-error \
--request POST 'https://data.flashdata.dev/v1/queries' \
--header "X-API-Key: $FLASHDATA_API_KEY" \
--header 'Content-Type: application/json' \
--data '{"source":"google_search","query":"battery recycling research","params":{"num":5}}' \
--output submission.json
jq '{id, source, status, links}' submission.json
)2. 等待已有任务
任务为 completed 时继续;若为 failed,先检查错误,再决定是否提交新任务。
等待成功时,CLI JSON 返回 data.status: completed。
(
set -euC
JOB_ID=$(jq -er '.remoteId // .id // .submission.id' submission.json)
flashdata jobs wait "$JOB_ID" --timeout 2m --json
)此命令检查一次。job.status 为 pending 或 processing 时,稍等后重复 GET。遇到 429,请按 job-headers.txt 中的 Retry-After 等待。
(
set -euC
: "${FLASHDATA_API_KEY:?Set FLASHDATA_API_KEY first}"
JOB_ID=$(jq -er '(.remoteId // .id // .submission.id) | select(test("^[A-Za-z0-9_-]+$"))' submission.json)
STATUS_URL="https://api.flashdata.dev/v2/jobs/$JOB_ID"
curl --fail-with-body --silent --show-error \
--header "X-API-Key: $FLASHDATA_API_KEY" \
--max-time 30 --dump-header job-headers.txt --output job.json "$STATUS_URL"
jq -e --arg id "$JOB_ID" '.job.id == $id' job.json >/dev/null
jq '.job | {id, source, status, error}' job.json
){
"job": {
"id": "EXAMPLE_JOB_ID",
"source": "google_search",
"status": "completed",
"error": null
}
}3. 获取并保存响应
将 result.json 保存到本地。已完成任务与结果响应是不同记录:本次搜索的响应包含 source: google_search、results 数组及 usage。下方验证接受存储结果的 done 或 completed 成功状态。
(
set -euC
JOB_ID=$(jq -er '.remoteId // .id // .submission.id' submission.json)
flashdata jobs result "$JOB_ID" --output result.json --json
jq '{source, status, results, usage}' result.json
)默认 JSON 结果重定向至签名存储地址。此代码解压存储结果,也接受直接返回的 JSON。仅 FlashData 端点接收 API Key。
(
set -euC
: "${FLASHDATA_API_KEY:?Set FLASHDATA_API_KEY first}"
JOB_ID=$(jq -er '(.remoteId // .id // .submission.id) | select(test("^[A-Za-z0-9_-]+$"))' submission.json)
SOURCE=$(jq -er '(.submission // .).source' submission.json)
jq -e --arg id "$JOB_ID" --arg source "$SOURCE" \
'.job.id == $id and .job.source == $source and .job.status == "completed"' job.json >/dev/null
test ! -e result.json || { echo "Choose a new output filename." >&2; exit 1; }
RESULT_URL="https://api.flashdata.dev/v2/jobs/$JOB_ID/results"
STATUS=$(curl --silent --show-error \
--header "X-API-Key: $FLASHDATA_API_KEY" \
--max-time 120 --dump-header result-headers.txt --output result.pending \
--write-out '%{http_code}' "$RESULT_URL")
case "$STATUS" in
200) ;;
302)
LOCATION=$(awk 'tolower($1) == "location:" { sub(/\r$/, "", $2); print $2 }' result-headers.txt)
# The signed storage URL is fetched WITHOUT the FlashData API key.
curl --fail-with-body --silent --show-error --compressed --max-time 120 --proto '=https' \
--output result.pending "$LOCATION" ;;
*) echo "Result HTTP $STATUS; inspect result.pending and result-headers.txt." >&2; exit 1 ;;
esac
jq -e --arg source "$SOURCE" '.source == $source and (.status == "done" or .status == "completed")
and (.results | type == "array")' result.pending >/dev/null
cat result.pending > result.json
jq '{id, source, status, results, usage}' result.json
)4. 在应用中使用结果
验证已保存响应,再提取 title、link、snippet,用于搜索界面或智能体的下一步。成功但 organic 数组为空表示没有匹配项;字段缺失或失败响应需要检查。
| 应用任务 | 状态变化 |
|---|---|
| 等待中 | 向用户或智能体交还控制权前,持久化已接纳的任务 ID。 |
| 可用 | 结果保存且验证通过后标记可用。使用应用任务 ID 作为导入或更新主键。 |
| 需要处理 | 保留任务 ID 与错误。轮询超时或获取失败不意味着应重新提交。 |
jq -e '.source == "google_search" and (.status == "done" or .status == "completed")
and (.results | type == "array")
and all(.results[]; (.organic | type == "array"))' result.json > /dev/null &&
jq -c '.results[] | .organic[] | {title, link, snippet}' result.json在另一个进程中继续
在相同目录打开新终端,使用相同凭据及配置档。下方命令读取 submission.json 中的任务并保存为新文件,不提交任务。复用同一个 CLI 运行 ID 需要原状态目录;HTTP 不会使用这个本地运行 ID 去重 POST。
(
set -eu
JOB_ID=$(jq -er '.remoteId // .id // .submission.id' submission.json)
flashdata jobs get "$JOB_ID" --json
flashdata jobs wait "$JOB_ID" --timeout 2m --json
flashdata jobs result "$JOB_ID" --output recovered-result.json --json
)提交多个查询
Batch 在一次请求中提交多个独立任务。以下两个查询需要至少两个查询的 Batch 容量和两个等待任务的容量;临时试用限制为一个。请在单独的工作目录中将下方数组保存为 batch.json。
[
{
"source": "google_search",
"query": "battery recycling research",
"params": {
"num": 5
}
},
{
"source": "google_search",
"query": "lithium battery recycling methods",
"params": {
"num": 5
}
}
]flashdata batch submit --input batch.json \
--run-id batch-first --output batch-submission.json --json(
set -euC
: "${FLASHDATA_API_KEY:?Set FLASHDATA_API_KEY first}"
test ! -e batch-submission.json || { echo "Keep the saved batch receipt." >&2; exit 1; }
jq '{queries: .}' batch.json > batch-request.json
curl --fail-with-body --silent --show-error \
--request POST 'https://data.flashdata.dev/v1/queries/batch' \
--header "X-API-Key: $FLASHDATA_API_KEY" \
--header 'Content-Type: application/json' \
--data-binary @batch-request.json --output batch-submission.json
jq '.queries[] | {id, source, status}' batch-submission.json
)保存 collect-batch.py
在 Batch 工作目录中、batch.json 和 batch-submission.json 旁创建 collect-batch.py,复制下方完整代码并保存。
将 batch.json、batch-submission.json 及 batch-results/ 保存在一起。已保存的输入或回执发生变化时,脚本会停止。脚本复用已完成的本地文件,读取错误不会触发新查询。
# collect-batch.py — Python 3.10+ and FlashData CLI; no new submissions.
import json
import re
import subprocess
import sys
from pathlib import Path
def read(path):
return json.loads(Path(path).read_text(encoding='utf-8-sig'))
def cli(*args):
result = subprocess.run(['flashdata', *args, '--json', '--non-interactive', '--timeout', '2m'],
check=True, capture_output=True, text=True, encoding='utf-8')
return json.loads(result.stdout)['data']
inputs = read('batch.json')
saved = read('batch-submission.json')
receipts = saved.get('submission', saved)['queries']
if not isinstance(inputs, list) or not inputs or len(inputs) != len(receipts):
raise ValueError('Keep the original batch input and matching receipt.')
ids = [r.get('id', '') for r in receipts]
if len(set(ids)) != len(ids) or any(not re.fullmatch(r'[A-Za-z0-9_-]+', x) for x in ids):
raise ValueError('Invalid or duplicate job IDs.')
folder = Path('batch-results')
folder.mkdir(exist_ok=True)
binding = json.dumps({'inputs': inputs, 'receipts': receipts}, sort_keys=True)
try:
with (folder / 'input-receipts.json').open('x', encoding='utf-8') as file:
file.write(binding)
except FileExistsError:
if (folder / 'input-receipts.json').read_text(encoding='utf-8') != binding:
raise ValueError('Inputs or receipts changed. Restore the original snapshot.')
outcomes = [{'index': index, 'input': request, 'job_id': receipt['id'], 'status': 'unread'}
for index, (request, receipt) in enumerate(zip(inputs, receipts))]
for index, (request, receipt) in enumerate(zip(inputs, receipts)):
job_id = receipt['id']
file = folder / (job_id + '.json')
row = {'index': index, 'input': request, 'job_id': job_id, 'status': 'unread'}
try:
if not file.exists():
try:
job = cli('jobs', 'wait', job_id)
except subprocess.CalledProcessError:
job = cli('jobs', 'get', job_id)
if job['id'] != job_id or job['source'] != request['source']:
raise ValueError('Job does not match the saved receipt/input.')
row.update(status=job['status'], error=job.get('error'))
if job['status'] == 'completed':
cli('jobs', 'result', job_id, '--output', str(file))
if file.exists():
result = read(file)
if (result.get('source') != request['source']
or result.get('status') not in ['done', 'completed']
or not isinstance(result.get('results'), list)):
raise ValueError('Inspect the saved result before importing it.')
row.update(status='completed', result_file=str(file), error=None)
except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as error:
row.update(status='read_error', error=getattr(error, 'stderr', None) or str(error))
outcomes[index] = row
pending = folder / 'outcomes.next'
pending.write_text(json.dumps(outcomes, ensure_ascii=False, indent=2), encoding='utf-8')
pending.replace(folder / 'outcomes.json')
print(index, job_id, row['status'])
print('Saved batch-results/outcomes.json. No queries were submitted.')
sys.exit(0 if all(row['status'] == 'completed' for row in outcomes) else 2)跟踪每个已接受的任务
保存 collect-batch.py 后,在 Batch 工作目录中使用 Python 3.10+ 及已认证 CLI 运行。两种提交方式均适用。脚本读取每个回执,每项未完成任务最多等待两分钟,并保存每个成功响应。一次只运行一个收集器;重新运行时继续读取相同任务。
样例应在 batch-results/outcomes.json 中生成两项记录。按输入索引及任务 ID 导入 completed 项。failed、pending 及 read_error 项继续保留;退出码 2 表示需要检查或继续处理。收集器不发送新查询。
python3 collect-batch.pypython collect-batch.pyjq '.[] | {index, job_id, status, result_file, error}' batch-results/outcomes.json接收完成 Webhook
在单个请求或每个 Batch 条目中,将 callback_url 放在 source、query、params 同级。请将示例 URL 替换为你的接收地址。事件报告完成或失败,结果需单独获取。
- 持久化事件并及时返回 2xx。使用 delivery_id 去重,该值也通过 X-Delivery-Id 发送。
- 事件未签名。先将 id 与 source 匹配到已保存的回执,再通过原回执的 self 链接认证读取状态。不要信任未验证事件提供的 URL。
- completed 时获取并保存结果;failed 时检查任务错误。未收到事件时,以轮询作为后备方案。
{
"source": "google_search",
"query": "battery recycling research",
"params": {
"num": 5
},
"callback_url": "https://your-app.example/webhooks/flashdata"
}{
"delivery_id": "completion:EXAMPLE_JOB_ID",
"id": "EXAMPLE_JOB_ID",
"source": "google_search",
"status": "completed",
"links": [
{
"rel": "self",
"href": "https://api.flashdata.dev/v2/jobs/EXAMPLE_JOB_ID",
"method": "GET"
},
{
"rel": "results",
"href": "https://api.flashdata.dev/v2/jobs/EXAMPLE_JOB_ID/results",
"method": "GET"
}
]
}回调 URL 要求
使用 443 端口的公网 HTTPS URL,最多 2,048 个字符,不含凭据或 fragment,所有解析出的 IP 均须为公网地址。省略 callback_url,或设为 null、空字符串,可关闭通知。
恢复已有任务
| 情况 | 处理方式 |
|---|---|
| 提交超时 | 检查 runs show async-first 及账户历史。runs recover 可获取已接纳的任务 ID;若未保存 ID,须先核对提交情况,再发送另一个 POST。 |
| pending / processing | 继续检查已有任务,这些状态不是失败。 |
| failed / 422 | 读取 job.error,修正原因,再决定是否提交新任务。 |
| 429 | 遵守 Retry-After。等待任务容量已满时降低提交并发。 |
| 404 / 409 | 404:检查 ID 和提交账户;409:结果尚未就绪。 |
| 410 | 保存的结果 JSON 在完成 24 小时后到期,请使用本地副本。已交付至你的存储的媒体遵循该存储的保留策略。 |
运行 YouTube 下载任务?
下载使用 async 或 Batch,需要具备 youtube_download 权限的所有者 API Key 和目标存储。结果 JSON 描述已交付至存储桶的媒体,结果端点不流式返回视频字节。请参阅下载指南配置存储并验证交付文件。
主机与响应格式
以上四个端点使用 X-API-Key,并应复用提交时的同一密钥。状态和结果读取免费,但有限流。示例使用 JSON;其他结果表示可在构建器中选择 Accept 和 X-Respond-With。签名存储下载使用其 URL,不发送 FlashData 密钥。
| 操作 | 端点 |
|---|---|
| 提交一个任务 | POST https://data.flashdata.dev/v1/queries |
| 提交一批任务 | POST https://data.flashdata.dev/v1/queries/batch |
| 读取状态 | GET https://api.flashdata.dev/v2/jobs/{id} |
| 读取结果 | GET https://api.flashdata.dev/v2/jobs/{id}/results |
支持的来源与模式
为你的来源构建工作流
选择来源,编辑参数并复制对应语言的完整工作流。启用回调可显示接收器示例。本构建器预览代码与示例响应,仅在你执行代码或使用控制台时发送请求。
构建请求
高级参数
从 1 开始;每页都是单独的请求。
Google 时间筛选语法,例如 qdr:d 表示过去一天。
完成通知 Webhook
Webhook 载荷、验证与重试Markdown 用于已完成的结果。提交回执和任务状态保留原始字段。
https://data.flashdata.dev/v1/queries