API
并行运行批量分析
在多个数据集上并行运行同一分析,再在第二个任务中为每个结果评分
运行并评分一次分析 会运行一个分析任务并为其评分。本配方把该模式扩展:同时在五个数据集上启动同一分析,并在每个分析完成后立即在各自任务中评分。
该分析在 cBioPortal 的五个公开 TCGA PanCancer Atlas 研究(肺癌、结直肠癌、乳腺癌、黑色素瘤与胃癌)中检验 TP53 突变是否预测总生存期。每个分析写出 report.md 与 result.json。每个评分任务只读取这两个文件,并按 100 分评分标准打分。

项目中的全部六个任务都通过 API 创建并并行运行:五个 TP53 生存分析与一个基因列表复核。
前置条件
- 一个 API 密钥
- Python 3.10 或更高版本,并安装
requests包 - 来自构建 Python 客户端 的
bioagent_client.py,保存在脚本旁边
安装 requests,然后设置 API 密钥:
python -m pip install requests
export BIOAGENT_API_KEY="<your-api-key>"
脚本使用 https://bioagent.cloud/api/v1。若要改用其他部署,请把 BIOAGENT_BASE_URL 环境变量设置为该部署的 API 基础 URL。
默认情况下,脚本会创建一个名为 “API demo” 的项目。若要改用已有项目,请把 BIOAGENT_PROJECT_ID 设置为其 ID。
工作方式
为每个数据集启动一个分析
run_analysis() 为一个研究创建带有分析提示词的任务,等待其完成,并下载结果文件。它通过 model="max" 与 disable_fallbacks=True 固定模型,确保每个数据集由同一模型分析。auto_mode=True 让任务运行到完成,而不停下来等人回答问题或批准计划。
def run_analysis(bioagent, project_id, study):
task = bioagent.create_task(
project_id=project_id,
title=f"TP53 survival: {study}",
initial_messages=[
{"role": "user", "content": ANALYSIS_PROMPT.format(study=study)}
],
model="max",
disable_fallbacks=True,
auto_mode=True,
)
print(f"[{study}] analysis task {task['id']}")
bioagent.wait_for_task(task["id"], poll_interval_seconds=60)
return bioagent.download_results(task["id"], Path("analysis-results") / study)
在第二个任务中为每个结果评分
grade_analysis() 上传分析输出到项目,并启动评分任务。文件以研究专属名称上传,因此共享项目中的每个评分任务只读取自己研究的文件。评分任务写出 score.json,脚本会下载它。
def grade_analysis(bioagent, project_id, study, results_dir):
# Upload the analysis output under study-specific names so every grading
# task in the shared project reads only its own files.
prefix = f"{study}__"
for name in ("report.md", "result.json"):
staged = results_dir / f"{prefix}{name}"
shutil.copyfile(results_dir / name, staged)
bioagent.upload_file(project_id, staged)
task = bioagent.create_task(
project_id=project_id,
title=f"Grade TP53 survival: {study}",
initial_messages=[
{
"role": "user",
"content": GRADING_PROMPT.format(study=study, prefix=prefix),
}
],
model="max",
disable_fallbacks=True,
auto_mode=True,
)
print(f"[{study}] grading task {task['id']}")
bioagent.wait_for_task(task["id"], poll_interval_seconds=60)
grade_dir = bioagent.download_results(task["id"], results_dir / "grade")
return json.loads((grade_dir / "score.json").read_text())
并行运行每个数据集
main() 在各自线程中运行每个研究。某个研究的分析一完成,它的评分任务就开始,而不必等待其他研究。所有研究完成后,脚本打印汇总表。
def run_study(project_id, study):
bioagent = BioAgentClient() # one HTTP session per thread
results_dir = run_analysis(bioagent, project_id, study)
score = grade_analysis(bioagent, project_id, study, results_dir)
result = json.loads((results_dir / "result.json").read_text())
return study, result, score
def main():
bioagent = BioAgentClient()
project_id = (
os.getenv("BIOAGENT_PROJECT_ID")
or bioagent.create_project(title="API demo")["id"]
)
# At most 10 tasks run at once; each study runs one task at a time.
with ThreadPoolExecutor(max_workers=len(STUDIES)) as pool:
outcomes = list(pool.map(lambda s: run_study(project_id, s), STUDIES))
print(f"\n{'study':34} {'HR (95% CI)':22} {'cox p':>8} {'score':>6}")
for study, result, score in outcomes:
ci = (
f"{result['cox_hr']:.2f} "
f"({result['cox_hr_ci_low']:.2f}-{result['cox_hr_ci_high']:.2f})"
)
print(f"{study:34} {ci:22} {result['cox_p']:>8.3g} {score['total_score']:>6}")
同一时间最多运行 10 个任务(见速率限制)。每个研究一次只运行一个任务,因此该脚本永远不会超过五个任务。如果添加更多数据集,请降低 max_workers 或处理 429 响应。
运行脚本
把完整脚本保存为 batch_analysis.py,与 bioagent_client.py 放在同一目录,然后运行:
python batch_analysis.py
每个研究的分析输出保存在 analysis-results/<study>/ 下,评分输出保存在 analysis-results/<study>/grade/ 下。
示例结果
五个分析都得到 100/100。
| 研究 | 患者数 | TP53 突变 | 校正 Cox HR(95% CI) | Cox p | 得分 |
|---|---|---|---|---|---|
| BRCA | 1,066 | 346 | 1.48 (1.04-2.10) | 0.029 | 100 |
| COADREAD | 530 | 309 | 0.81 (0.54-1.22) | 0.324 | 100 |
| LUAD | 502 | 251 | 1.16 (0.86-1.58) | 0.329 | 100 |
| SKCM | 423 | 70 | 0.80 (0.54-1.20) | 0.285 | 100 |
| STAD | 431 | 212 | 0.99 (0.73-1.36) | 0.972 | 100 |
每个任务都保留在项目中,因此你可以在 BioAgent 中打开任意运行,阅读智能体的工作或提出后续问题。

一个已完成的分析(BRCA):智能体总结,以及结果面板中的 report.md 与 result.json。

BRCA 评分任务:得分与每项评分标准的理由。
为你的分析改编本配方
- 把
STUDIES换为你的数据集,把ANALYSIS_PROMPT与GRADING_PROMPT换为你的分析与评分标准。 - 要求输出固定键的机器可读文件,就像这里的
result.json,这样无需解析自然语言即可比较运行。 - 让评分者除了它评分的文件外看不到其他内容,这样它的得分只反映输出本身。
完整脚本
"""Batch analysis: run one analysis across many datasets, then grade each
result in a second task."""
import json
import os
import shutil
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from bioagent_client import BioAgentClient
# Five public TCGA PanCancer Atlas studies on cBioPortal.
STUDIES = [
"luad_tcga_pan_can_atlas_2018",
"coadread_tcga_pan_can_atlas_2018",
"brca_tcga_pan_can_atlas_2018",
"skcm_tcga_pan_can_atlas_2018",
"stad_tcga_pan_can_atlas_2018",
]
ANALYSIS_PROMPT = """
Test whether TP53 mutation status is associated with overall survival in the
cBioPortal study {study}. Download the study's mutation and clinical data from
cBioPortal yourself.
- Call a patient TP53-mutant if they carry any nonsynonymous TP53 mutation.
- Compare overall survival with Kaplan-Meier curves and a log-rank test.
- Fit a Cox model for TP53 status adjusted for age at diagnosis and AJCC
pathologic stage.
Save two files under /mnt/results/:
1. report.md: cohort, definitions, methods, code, results, interpretation, and
limitations.
2. result.json, raw JSON with exactly these keys: study_id, n_patients,
n_tp53_mutant, logrank_p, cox_hr, cox_hr_ci_low, cox_hr_ci_high, cox_p,
conclusion.
""".strip()
GRADING_PROMPT = """
Grade the TP53 overall-survival analysis of {study} in the project files
{prefix}report.md and {prefix}result.json. Judge only those two files. Do not
redo the analysis or read any other file.
Score each criterion and explain why:
1. Cohort and TP53 definition (20): nonsynonymous mutations only, patients
without survival data excluded, counts reported.
2. Survival analysis (25): Kaplan-Meier plus log-rank test, done correctly.
3. Adjusted model (25): Cox model with age and stage, hazard ratio, 95% CI and
p-value reported.
4. Consistency (15): result.json matches the numbers in report.md.
5. Interpretation (15): conclusion follows from the numbers, limitations noted.
Save raw JSON (no code fence) at /mnt/results/score.json:
{{"study_id": "{study}", "total_score": 0,
"criteria": [{{"criterion": "...", "points": 0, "max_points": 0, "reason": "..."}}],
"summary": "..."}}
""".strip()
def run_analysis(bioagent, project_id, study):
task = bioagent.create_task(
project_id=project_id,
title=f"TP53 survival: {study}",
initial_messages=[
{"role": "user", "content": ANALYSIS_PROMPT.format(study=study)}
],
model="max",
disable_fallbacks=True,
auto_mode=True,
)
print(f"[{study}] analysis task {task['id']}")
bioagent.wait_for_task(task["id"], poll_interval_seconds=60)
return bioagent.download_results(task["id"], Path("analysis-results") / study)
def grade_analysis(bioagent, project_id, study, results_dir):
# Upload the analysis output under study-specific names so every grading
# task in the shared project reads only its own files.
prefix = f"{study}__"
for name in ("report.md", "result.json"):
staged = results_dir / f"{prefix}{name}"
shutil.copyfile(results_dir / name, staged)
bioagent.upload_file(project_id, staged)
task = bioagent.create_task(
project_id=project_id,
title=f"Grade TP53 survival: {study}",
initial_messages=[
{
"role": "user",
"content": GRADING_PROMPT.format(study=study, prefix=prefix),
}
],
model="max",
disable_fallbacks=True,
auto_mode=True,
)
print(f"[{study}] grading task {task['id']}")
bioagent.wait_for_task(task["id"], poll_interval_seconds=60)
grade_dir = bioagent.download_results(task["id"], results_dir / "grade")
return json.loads((grade_dir / "score.json").read_text())
def run_study(project_id, study):
bioagent = BioAgentClient() # one HTTP session per thread
results_dir = run_analysis(bioagent, project_id, study)
score = grade_analysis(bioagent, project_id, study, results_dir)
result = json.loads((results_dir / "result.json").read_text())
return study, result, score
def main():
bioagent = BioAgentClient()
project_id = (
os.getenv("BIOAGENT_PROJECT_ID")
or bioagent.create_project(title="API demo")["id"]
)
# At most 10 tasks run at once; each study runs one task at a time.
with ThreadPoolExecutor(max_workers=len(STUDIES)) as pool:
outcomes = list(pool.map(lambda s: run_study(project_id, s), STUDIES))
print(f"\n{'study':34} {'HR (95% CI)':22} {'cox p':>8} {'score':>6}")
for study, result, score in outcomes:
ci = (
f"{result['cox_hr']:.2f} "
f"({result['cox_hr_ci_low']:.2f}-{result['cox_hr_ci_high']:.2f})"
)
print(f"{study:34} {ci:22} {result['cox_p']:>8.3g} {score['total_score']:>6}")
if __name__ == "__main__":
main()