repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
ai-agent-book | tests/test_ch4_semantic_router_empty_servers.py | .py | import pytest
pytest.importorskip("numpy")
"""Regression test for SemanticRouter initialization with empty servers list."""
import sys
from pathlib import Path
# Add active-tool-selection to sys.path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "chapter4" / "active-tool-selection"))
from semantic_r... | 38 | 1,291 |
ai-agent-book | tests/test_i18n_figure_placement.py | .py | from pathlib import Path
from xml.etree import ElementTree
ROOT = Path(__file__).resolve().parents[1]
CHAPTER_1_LOCALE_ANCHORS = {
"es": {
2: ("Posentrenamiento", "externalizado"),
3: ("Prompt del sistema", "Sin historial"),
},
"ja": {
2: ("ポストトレーニング", "外部化学習"),
3: ("システム",... | 117 | 4,024 |
ai-agent-book | tests/test_ch2_benchmark_compression.py | .py | import sys
from pathlib import Path
# Add module directory to path for imports
ch2_dir = Path(__file__).resolve().parent.parent / "chapter2" / "context-compression"
if str(ch2_dir) not in sys.path:
sys.path.insert(0, str(ch2_dir))
from benchmark_compression import (
ContextCompressionBenchmark,
StrategyMe... | 199 | 7,857 |
ai-agent-book | tests/test_ch1_ch2_system_hint_tool_error_null.py | .py | import pytest
"""
Test suite verifying choke-point fix for SystemHintAgent handling
None / empty / non-string error fields in tool results.
"""
import logging
import sys
from pathlib import Path
from unittest.mock import MagicMock
sys.path.insert(0, str(Path(__file__).parent.parent / "chapter2" / "system-hint"))
from... | 84 | 2,950 |
ai-agent-book | tests/test_ch5_notebook_edit_zero_cell_id.py | .py | import pytest
import json
import sys
from pathlib import Path
ch5_tools_dir = Path(__file__).resolve().parent.parent / "chapter5" / "coding-agent"
if str(ch5_tools_dir) not in sys.path:
sys.path.insert(0, str(ch5_tools_dir))
from tools.notebook_edit_tool import NotebookEditTool # noqa: E402
from system_state imp... | 50 | 1,478 |
ai-agent-book | tests/test_ch9_interruption_manager.py | .py | """Unit tests for chapter9/streaming-speech/interruption_manager.py (DuplexInterruptionManager)."""
import importlib.util
import os
import sys
from pathlib import Path
import pytest
pytest.importorskip("numpy")
import numpy as np
# Dynamic import for hypenated module path
_module_path = (
Path(__file__).resolve(... | 303 | 12,110 |
ai-agent-book | tests/test_ch9_phone_agent_redact_secrets_non_serializable.py | .py | import datetime
import importlib.util
import os
import sys
from pathlib import Path
import pytest
pytest.importorskip("openai")
_module_path = (
Path(__file__).resolve().parent.parent / "chapter9" / "phone-agent" / "agent.py"
)
_spec = importlib.util.spec_from_file_location("phone_agent", _module_path)
_module = ... | 44 | 1,266 |
ai-agent-book | tests/test_ch10_werewolf_wolf_vote_tie_consensus.py | .py | import sys
from pathlib import Path
import pytest
ch10_werewolf = Path(__file__).resolve().parent.parent / "chapter10" / "voice-werewolf"
if str(ch10_werewolf) not in sys.path:
sys.path.insert(0, str(ch10_werewolf))
from werewolf.game import Judge
from werewolf.agent import PlayerAgent
from werewolf.roles import ... | 42 | 1,813 |
ai-agent-book | tests/test_flatten_epub_toc.py | .py | import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from flatten_epub_toc import flatten_nav, flatten_ncx
def test_flatten_nav_after_flatten_ncx_preserves_default_xhtml_namespace():
"""Contract: flatten_nav must re-register the default XHTML namespace so that element... | 117 | 4,284 |
ai-agent-book | tests/test_ch8_llm_judge_non_dict_payload.py | .py | import pytest
import json
import os
import sys
import types
sys.path.insert(0, os.path.abspath("chapter8/trajectory-verifier"))
from llm_judge import OpenAIQualityJudge
class _FakeClient:
model = "fake-model"
def __init__(self, payload):
self._payload = payload
def complete(self, **kwargs):
... | 43 | 1,306 |
ai-agent-book | tests/test_ch6_bradley_terry_calibration.py | .py | import pytest
pytest.importorskip("pandas")
"""
Test suite for compute_mle_elo calibration model and calibration rating handling.
"""
import sys
from pathlib import Path
import pandas as pd
HERE = Path(__file__).resolve().parent.parent
ELO_DIR = HERE / "chapter6" / "elo-leaderboard"
if str(ELO_DIR) not in sys.path:
... | 77 | 2,415 |
ai-agent-book | tests/test_split_search_index.py | .py | """Tests for scripts/split_search_index.py (the per-edition search index hook)."""
import importlib.util
import json
from pathlib import Path
import pytest
def _load_hook():
path = Path(__file__).parents[1] / "scripts" / "split_search_index.py"
spec = importlib.util.spec_from_file_location("split_search_ind... | 136 | 5,120 |
ai-agent-book | tests/test_no_bare_except.py | .py | """Static regression check: no bare ``except:`` in book-owned Python code.
Closes the class where bare ``except:`` clauses swallowed
``KeyboardInterrupt`` / ``SystemExit`` and masked real errors. Vendored
third-party trees and test fixtures are excluded; the invariant applies
only to code the book authors own.
"""
fr... | 67 | 2,137 |
ai-agent-book | tests/test_ch6_char_error_rate.py | .py | import pytest
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent.parent
TTS_DIR = HERE / "chapter6" / "tts-quality-eval"
if str(TTS_DIR) not in sys.path:
sys.path.insert(0, str(TTS_DIR))
sys.modules.pop("config", None)
import pipeline # noqa: E402
def test_char_error_rate_empty_referen... | 55 | 1,527 |
ai-agent-book | tests/test_ch3_english_figures.py | .py | import re
from pathlib import Path
from xml.etree import ElementTree
ROOT = Path(__file__).resolve().parents[1]
CHAPTER = ROOT / "book-en" / "chapter3.md"
IMAGE_DIR = ROOT / "book-en" / "images"
EXPECTED_ANCHORS = {
1: ("User Memory (Individual Scale)", "Knowledge Base (Group Scale)"),
2: ("Simple Notes", "Ad... | 48 | 1,857 |
ai-agent-book | tests/test_ch10_subscription_empty_types.py | .py | import pytest
"""Regression test: Subscription with empty types list [] must filter out all message types."""
import sys
from pathlib import Path
ch10_pwr = Path(__file__).resolve().parent.parent / "chapter10" / "parallel-web-research"
if str(ch10_pwr) not in sys.path:
sys.path.insert(0, str(ch10_pwr))
from messa... | 47 | 1,980 |
ai-agent-book | tests/test_ch10_message_bus_non_json_payload.py | .py | import sys
import os
sys.path.insert(0, os.path.abspath("chapter10/parallel-web-research"))
from message_bus import Envelope, MessageBus
def test_envelope_short_handles_non_json_payload():
"""Contract: Envelope.short does not raise TypeError when payload contains non-JSON serializable objects."""
class Cust... | 51 | 1,335 |
ai-agent-book | tests/test_ch7_sft_data_auditor.py | .py | """
Tests for the SFT training-data quality auditor (chapter 7 CoT distillation).
Covers valid data, format errors, length outliers, exact and near duplicates,
label noise, tokenizer risks, boundary gaps, empty/single/all-duplicate
datasets, and quality-score computation. All tests are fully offline and
deterministic.... | 394 | 14,801 |
ai-agent-book | scripts/clean_site_files.py | .py | #!/usr/bin/env python3
"""Keep reader-facing site assets and JSON files linked from rendered Markdown."""
from __future__ import annotations
import sys
from html.parser import HTMLParser
from pathlib import Path
from urllib.parse import unquote, urlsplit
import markdown
ALWAYS_PUBLISHED_SUFFIXES = {
".css",
... | 102 | 2,954 |
ai-agent-book | scripts/gen_og_card.py | .py | #!/usr/bin/env python3
"""Generate assets/og-card.png — the Open Graph / Twitter share card.
The card is a static 1200x630 PNG checked into the repo (regenerating it
is only needed when the branding text changes). scripts/seo_meta.py
references it as <site_url>/assets/og-card.png on every page.
Fonts are macOS system... | 55 | 1,971 |
ai-agent-book | scripts/site_i18n.py | .py | #!/usr/bin/env python3
"""Validate and build the static site's browser-side translation catalog.
The site contains all book editions in one MkDocs build. MkDocs Material can
only use one ``theme.language`` per build, so its generated chrome is Chinese
and translated editions localize it in the browser. This hook combi... | 348 | 13,344 |
ai-agent-book | scripts/git_revision_dates.py | .py | """Use tracked source files for revision dates in the assembled MkDocs site.
``scripts/build_site.sh`` copies documentation into the ignored ``_web/``
directory before MkDocs runs. The git revision-date plugin would otherwise
query those generated paths, find no history, and give every page the build
time. This hook... | 77 | 2,680 |
ai-agent-book | scripts/seo_meta.py | .py | """Inject Open Graph + Twitter Card meta tags into every page so links
look rich when shared to WeChat / Twitter / Slack.
Material's `social` plugin can do this but needs cairosvg + image
rendering that silently no-ops in some CI environments. This hook is
simpler: it derives all tags from page + site config, no image... | 51 | 2,166 |
ai-agent-book | scripts/gen_star_history.py | .py | #!/usr/bin/env python3
"""Render this repo's star history as PNG images (light + dark variants).
Fetches stargazer timestamps from the GitHub REST API, drops everything
before START_DATE, and draws a cumulative "stars over time" chart with a
gradient fill. Output: assets/star-history-{light,dark}.png
Usage:
pytho... | 312 | 11,262 |
ai-agent-book | scripts/mkdocs_pandoc_strip.py | .py | """MkDocs hook: strip Pandoc-specific attributes before rendering.
The book source uses Pandoc/LaTeX attributes that Python-Markdown does not
understand and would otherwise render as literal text:
## 标题 {.unnumbered} -> ## 标题
{height=55%} -> 
[文本](#sec:foo){.unnumbered} ... | 37 | 1,250 |
ai-agent-book | scripts/sync_chapter2_figures.py | .py | #!/usr/bin/env python3
"""Synchronize localized Chapter 2 SVGs with the Chinese golden layouts.
The Chapter 2 figure sequence changed after several translations had copied an
older set of diagrams. This script keeps the affected layouts tied to the
Chinese edition while applying an explicit, reviewable localization m... | 948 | 58,248 |
ai-agent-book | scripts/site_source_paths.py | .py | """Map pages in the generated MkDocs tree to their repository sources."""
from __future__ import annotations
from pathlib import Path, PurePosixPath
import subprocess
import time
from typing import Any, Iterable
REPO_ROOT = Path(__file__).resolve().parents[1]
Commit = tuple[str, int]
def source_path_for_page(src_... | 103 | 3,162 |
ai-agent-book | scripts/check_i18n_consistency.py | .py | #!/usr/bin/env python3
"""检查多语言版本的结构完整性。
防止主页或某章 README 改动后,其它语言版本跟不上而漂移。CI 中运行;
本地也可直接 `python scripts/check_i18n_consistency.py` 跑。
核心原则:**自动发现语言,不硬编码**。下次有人加新语言(日语、韩语…)时,
CI 自动适配,无需改脚本。
目录约定(中文为主语言):
- 中文主 README:仓库根目录 README.md(不放进 docs/)
- 其它语言主 README:docs/<locale>/README.md(如 docs/en/README.md)
- 学习建议:d... | 244 | 8,907 |
ai-agent-book | scripts/split_search_index.py | .py | #!/usr/bin/env python3
"""Split Material's monolithic search index into one file per book edition.
MkDocs' search plugin emits a single ``search/search_index.json`` covering
every page in the build. This site ships all 13 book editions plus the ~94
companion-experiment pages from one build, so that file had grown to ~... | 164 | 6,379 |
ai-agent-book | book-vi/fix_svg_text_layout.py | .py | #!/usr/bin/env python3
"""Repair and validate Vietnamese text layout in the book's SVG diagrams.
The Vietnamese labels are usually wider than their Chinese counterparts. This
tool restores the original type sizes and wraps labels with SVG ``tspan``
elements. It deliberately does not use ``textLength`` because librsv... | 615 | 25,149 |
ai-agent-book | book-es/gen_ch2_figs.py | .py | """Regenerate this edition's Chapter 2 figures from the Chinese golden layouts.
The shared synchronizer owns the current Chapter 2 figure numbering, localized
labels, and authoritative context-compression measurements.
"""
import subprocess
import sys
from pathlib import Path
if __name__ == "__main__":
root = Pa... | 17 | 491 |
ai-agent-book | book-es/gen_ch4_figs.py | .py | """Generate all SVG illustrations for Chapter 4 (Tools & MCP & Async)."""
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from svg_lib import (
SVG, COLORS, FS_TITLE, FS_BODY, FS_SMALL, FS_TINY,
)
OUT = os.path.join(os.path.dirname(__file__), 'images')
def _pill(svg, x, y, w, h, label, fill=... | 873 | 37,510 |
ai-agent-book | book-es/gen_ch9_figs.py | .py | """[DEPRECATED] Old Chapter 9 (multi-Agent) figure generator.
⚠️ DO NOT RUN: After the 2026-03-12 refactoring, chapter numbers changed (original Ch 9 → Ch 10).
The figures generated by this file actually correspond to the current [Chapter 10] content (multi-Agent collaboration), but are still saved as fig9-*.svg.
Runn... | 17 | 759 |
ai-agent-book | book-es/gen_ch1_figs.py | .py | """Generate all Chapter 1 figures in Spanish."""
import sys, os
sys.path.insert(0, os.path.dirname(__file__))
from svg_lib import *
OUT = os.path.join(os.path.dirname(__file__), 'images')
def fig1_4():
"""Kimi K3 / GPT-5.6 native agent architecture — caption Figure 1-4"""
s = SVG(820, 520)
# Title
s... | 500 | 20,669 |
ai-agent-book | book-es/gen_cover.py | .py | #!/usr/bin/env python3
"""Generate the book cover image with an image-generation model.
This is, fittingly, the book eating its own dog food: the cover of a book about
AI agents is produced by calling an image-generation model. Run it once; the
cover (cover.tex) automatically switches to images/cover-image.png when pr... | 77 | 3,461 |
ai-agent-book | book-es/gen_ch8_figs.py | .py | #!/usr/bin/env python3
"""Chapter 8 figures — Agent's self-evolution."""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from svg_lib import SVG, FS_SMALL, FS_TINY, FS_BODY
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'images')
def _pipeline(stages, fname, W=88... | 123 | 6,194 |
ai-agent-book | book-es/gen_ch3_figs.py | .py | """Generate all Chapter 3 figures in Spanish (Knowledge Base & RAG)."""
import math
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from svg_lib import (
SVG, COLORS, FS_TITLE, FS_BODY, FS_SMALL, FS_TINY, STROKE_W,
)
OUT = os.path.join(os.path.dirname(__file__), 'images')
def fig3_1():
""... | 742 | 32,175 |
ai-agent-book | book-es/gen_ch5_figs.py | .py | """Generate all SVG illustrations for Chapter 5 (Code Generation)."""
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from svg_lib import (
SVG, COLORS, FS_TITLE, FS_BODY, FS_SMALL, FS_TINY, FS_LABEL,
CORNER_R,
)
OUT = os.path.join(os.path.dirname(__file__), 'images')
def _pill(svg, x, y... | 1,005 | 43,884 |
ai-agent-book | book-id/gen_ch2_figs.py | .py | """Regenerate this edition's Chapter 2 figures from the Chinese golden layouts.
The shared synchronizer owns the current Chapter 2 figure numbering, localized
labels, and authoritative context-compression measurements.
"""
import subprocess
import sys
from pathlib import Path
if __name__ == "__main__":
root = Pa... | 17 | 491 |
ai-agent-book | book-id/gen_ch4_figs.py | .py | #!/usr/bin/env python3
"""Generate all SVG illustrations for Chapter 4 (Tools).
Figures (9 total):
fig4-1: MCP protocol sequence diagram (concrete message payloads)
fig4-2: Event-driven architecture (real event sources & payloads)
fig4-3: Async event processing (cancellation/queued/parallel timing)
fig4-4: ... | 737 | 31,801 |
ai-agent-book | book-id/gen_ch9_figs.py | .py | """[DEPRECATED] Old Chapter 9 (multi-Agent) figure generator.
⚠️ DO NOT RUN: After the 2026-03-12 refactoring, chapter numbers changed (original Ch 9 → Ch 10).
The figures generated by this file actually correspond to the current [Chapter 10] content (multi-Agent collaboration), but are still saved as fig9-*.svg.
Runn... | 1,053 | 50,274 |
ai-agent-book | book-id/gen_ch1_figs.py | .py | """Generate all Chapter 1 figures."""
import sys, os
sys.path.insert(0, os.path.dirname(__file__))
from svg_lib import *
OUT = os.path.join(os.path.dirname(__file__), 'images')
def fig1_4():
"""Kimi K3 / GPT-5.6 native agent architecture — caption Figure 1-4"""
s = SVG(820, 520)
# Title
s.text(410, ... | 538 | 21,776 |
ai-agent-book | book-id/gen_ch8_figs.py | .py | #!/usr/bin/env python3
"""Chapter 8 figures — Agent's self-evolution.
NOTE: this generator was previously a stray copy of chapter 9's figures, which
left fig8-1..fig8-7 showing chapter-9 content. It has been rewritten so each
figure matches its caption in chapter8.md. Figures are built with svg_lib;
titles live in the... | 116 | 6,133 |
ai-agent-book | book-id/gen_ch3_figs.py | .py | #!/usr/bin/env python3
"""Generate all SVG illustrations for Chapter 3 (Knowledge Base & RAG).
Figures (14 total):
fig3-1: Chapter roadmap
fig3-2: RAG end-to-end pipeline (concrete example)
fig3-3: Dense embedding evolution (with dimensions & training)
fig3-4: HNSW index structure (enlarged)
fig3-5: BM2... | 861 | 37,424 |
ai-agent-book | book-id/gen_ch5_figs.py | .py | #!/usr/bin/env python3
"""Generate all SVG illustrations for Chapter 5 (Code Generation).
Figures (11 total):
fig5-1: OpenClaw architecture — Coding Agent as core of general Agent
fig5-2: Coding Agent multi-phase workflow (concrete file ops & tool calls)
fig5-3: Search tool comparison (4 types with real query... | 1,095 | 47,409 |
ai-agent-book | book/strip_titles.py | .py | #!/usr/bin/env python3
"""Strip in-figure titles from checked-in SVGs and crop top whitespace.
按学术规范:图本身不包含标题(标题写在正文)。本脚本保守地处理
`images/` 中已签入的 SVG 文件。
判定规则(保守):
- 第一处出现的 <text> 元素,若同时满足:font-size>=20 且 y<60 且 text-anchor=middle,
则视为图标题——删除该元素,并将 viewBox 上沿和 height 各下移/缩小 CROP_PX。
- 否则该文件不做任何修改。
用法:python3 strip_ti... | 112 | 3,574 |
ai-agent-book | book/gen_cover.py | .py | #!/usr/bin/env python3
"""Generate the book cover image with an image-generation model.
This is, fittingly, the book eating its own dog food: the cover of a book about
AI agents is produced by calling an image-generation model. Run it once; the
cover (cover.tex) automatically switches to images/cover-image.png when pr... | 85 | 4,156 |
ai-agent-book | chapter7/package_evidence.py | .py | #!/usr/bin/env python3
"""Create a credential-free integrity manifest for a Chapter 6 run directory."""
from __future__ import annotations
import argparse
import hashlib
import json
import subprocess
from datetime import datetime, timezone
from pathlib import Path
def sha256(path: Path) -> str:
digest = hashlib... | 77 | 2,570 |
ai-agent-book | chapter7/model-benchmark/campaign.py | .py | #!/usr/bin/env python3
"""Full Experiment 6-8 campaign runner.
This is the long-form, resumable experiment described by the book. It stores
every real request in SQLite so a 168-hour availability campaign or a large
100-request workload matrix can be resumed without losing completed cells.
There is deliberately no sy... | 1,075 | 40,965 |
ai-agent-book | chapter7/model-benchmark/analysis.py | .py | #!/usr/bin/env python3
"""Analyze the SQLite evidence produced by the full Experiment 6-8 campaign."""
from __future__ import annotations
import argparse
import json
import math
import sqlite3
import statistics
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path
from t... | 865 | 37,688 |
ai-agent-book | chapter7/model-benchmark/test_campaign.py | .py | from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
from analysis import availability_summary, completion_audit, markdown, percentile, summarize_workloads
from campaign import (
CampaignStore,
Observation,
Price,
PromptFactory,
Provider,
error_details,... | 425 | 15,650 |
ai-agent-book | chapter7/model-benchmark/benchmark.py | .py | """
多维度模型性能基准测试(实验 6-8 配套代码)
对多个 OpenAI 兼容的 LLM API 提供商,测量以下核心指标:
- TTFT(Time To First Token,首个 token 到达延迟)
- 端到端延迟(发出请求到接收完整响应)
- 吞吐(tokens/s,按生成的输出 token 计;并发下另给聚合吞吐 / RPS)
- 标准差 / p50 / p95 / p99 延迟分位数(方差大意味着体验不稳定)
- 可用性 / 成功率(失败即计入可用性下降,不中断整表)
支持两种模式:
- 单档位对比:多提供商横向对比表(默认)。
- 并发扫描(压测):... | 444 | 17,816 |
ai-agent-book | chapter7/model-benchmark/rate_ramp_benchmark.py | .py | """Rate Ramp Benchmark for LLM Endpoints (Chapter 6).
Simulates multi-concurrency load testing (1 to 50 req/s) against LLM endpoints,
measuring 429 rate limit backoff curves, TTFT percentiles (p50, p95, p99),
error rates, and compiling N=100 evidence packages.
"""
from __future__ import annotations
from datetime imp... | 322 | 12,923 |
ai-agent-book | chapter7/model-benchmark/demo.py | .py | """
demo.py —— 一条命令跑出多提供商性能对比表 / 并发压测表。
用法:
python demo.py # 使用默认参数,多提供商横向对比
python demo.py --num-requests 20 --concurrency 5
python demo.py --serial # 串行发送(并发=1)
python demo.py --list # 仅列出将要测试的提供商
# 指定任意一个 OpenAI 兼容端点(不改代码即可测新模型/新提供商):
python de... | 410 | 17,023 |
ai-agent-book | chapter7/user-memory-system-evaluation/build_63_evidence.py | .py | #!/usr/bin/env python3
"""Derive canonical Experiment 6-3 evidence from the completed 6-4 campaign.
The completed 6-4 report ran the Experiment 6-3 judge on every one of its
60 cases and three memory systems. This validator creates a small, auditable
index without changing, adding, or re-judging any paid API trajecto... | 150 | 5,817 |
ai-agent-book | chapter7/user-memory-system-evaluation/supplement_63_missing.py | .py | #!/usr/bin/env python3
"""Re-judge only incomplete saved 6-3 rubric records without mutating 6-4.
The source campaign remains immutable. Each supplemental judgment records the
source record identity and answer hash so the full 6-3 validator can join it
without confusing it with a newly executed memory-system trajecto... | 116 | 4,027 |
ai-agent-book | chapter7/user-memory-system-evaluation/test_run_full.py | .py | """Offline checkpoint-validity tests for the resumable full runner."""
import json
from run_full import required_611_cells, valid_checkpoint
def record(experiment="6-4", status="ok", system="advanced_json_cards"):
row = {
"experiment": experiment,
"test_id": "case-1",
"status": status,
... | 92 | 3,188 |
ai-agent-book | chapter7/user-memory-system-evaluation/probe_candidates.py | .py | #!/usr/bin/env python3
"""Exploratory backend probes for Experiment 6-11 readiness (2026-07-31).
Probes candidate substitutions with minimal real calls (1-line embed, 1-token
chat, tiny rerank) and records sanitized, credential-free receipts. Secrets are
read from the environment only; every recorded error string is s... | 182 | 8,058 |
ai-agent-book | chapter7/user-memory-system-evaluation/enrich_rubrics.py | .py | #!/usr/bin/env python3
"""Add complete 6-3 rubric evidence to saved 6-4/6-11 case checkpoints."""
from __future__ import annotations
import argparse
import json
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Any, Dict
from experiment import EVA... | 105 | 4,560 |
ai-agent-book | chapter7/user-memory-system-evaluation/experiment.py | .py | #!/usr/bin/env python3
"""Experiments 6-4 and 6-11: end-to-end user-memory system evaluation.
Unlike the old response-file comparison, this module builds memory from every
test case, invokes real embedding/reranking/chat APIs, runs the answering agent,
and judges its answer. All operational metrics come from the actu... | 2,016 | 89,569 |
ai-agent-book | chapter7/user-memory-system-evaluation/run_full.py | .py | #!/usr/bin/env python3
"""Restart-safe bounded-parallel runner for the full 60-case experiments."""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Any, D... | 313 | 11,551 |
ai-agent-book | chapter7/user-memory-system-evaluation/rebuild_report.py | .py | #!/usr/bin/env python3
"""Rebuild aggregate/report metadata from saved live trajectory records.
This performs no model calls and never invents records. It is useful when report
logic changes (for example, the stricter core-dimension success gate) while the
underlying expensive API answers and judge dimension scores re... | 117 | 4,489 |
ai-agent-book | chapter7/user-memory-system-evaluation/calibration_summary.py | .py | #!/usr/bin/env python3
"""Summarize calibration output: per-case calls/tokens/cost, projected to 60 cases."""
import json
import sys
from collections import defaultdict
path = sys.argv[1]
data = json.load(open(path))
records = data["records"]
ok = [r for r in records if r["status"] == "ok"]
err = [r for r in records ... | 62 | 2,522 |
ai-agent-book | chapter7/user-memory-system-evaluation/test_experiment.py | .py | """Offline tests for the experiment harness; live API evidence is stored separately."""
import json
from pathlib import Path
from experiment import (
AgentResult,
CardBuilder,
ChatTurn,
Chunk,
MemoryAgent,
LLMReranker,
NoReranker,
ToolCall,
TokenPricing,
Usage,
VectorMemory... | 368 | 13,266 |
ai-agent-book | chapter7/user-memory-system-evaluation/probe_backends.py | .py | #!/usr/bin/env python3
"""Probe every backend required by a config without exposing credentials."""
import argparse
import json
import os
import time
from pathlib import Path
from experiment import (
ChatBackend,
Chunk,
EmbeddingBackend,
EndpointSpec,
ExperimentRunner,
execution_config_fingerp... | 129 | 5,297 |
ai-agent-book | chapter7/user-memory-system-evaluation/validation/verify_full_matrix_20260731.py | .py | #!/usr/bin/env python3
"""Honest verification of the merged Experiment 6-11 (README row 6-11) full matrix.
Checks, without trusting the runner's own summary:
1. All 60 cases present, each with exactly 24 cells (4 embeddings x 3 rerankers x 2 main models).
2. 1,440 total records; zero error trajectories; zero unpri... | 90 | 3,489 |
ai-agent-book | chapter7/openvla-robotwin2-eval/instrument_upstream.py | .py | #!/usr/bin/env python3
"""Fail-closed instrumentation for a disposable SimpleVLA-RL worktree."""
from __future__ import annotations
import argparse
from pathlib import Path
EPISODE_RECORDER = ''' # Experiment 6-12 instrumentation. This patch is applied only to a
# disposable worktree; the upstream ch... | 117 | 5,432 |
ai-agent-book | chapter7/openvla-robotwin2-eval/experiment.py | .py | #!/usr/bin/env python3
"""Exact companion for manuscript Experiment 6-12.
The runner deliberately separates three things:
1. a non-destructive host/upstream preflight;
2. generation or execution of the two real upstream val-only arms; and
3. strict analysis of episode-level evidence.
Paper numbers, historical rollout... | 784 | 33,511 |
ai-agent-book | chapter7/openvla-robotwin2-eval/annotate_timeouts.py | .py | #!/usr/bin/env python3
"""Create auditable timeout annotations from complete Experiment 6-12 evidence.
This helper only labels an episode when the upstream recorder says it failed at
the configured action horizon and an exact failure-video match can be probed.
It refuses early failures, missing videos, duplicate video... | 136 | 5,263 |
ai-agent-book | chapter7/openvla-robotwin2-eval/finalize_evidence.py | .py | #!/usr/bin/env python3
"""Finalize and verify the retained Experiment 6-12 evidence package."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
from typing import Any
import experiment
HERE = Path(__file__).resolve().parent
DEFAULT_RUN = HERE / "validation" / ... | 175 | 6,678 |
ai-agent-book | chapter7/openvla-robotwin2-eval/test_experiment.py | .py | import importlib.util
import json
import os
from datetime import datetime, timezone
from pathlib import Path
HERE = Path(__file__).resolve().parent
SPEC = importlib.util.spec_from_file_location("exp612", HERE / "experiment.py")
exp = importlib.util.module_from_spec(SPEC)
assert SPEC.loader
SPEC.loader.exec_module(exp... | 121 | 4,861 |
ai-agent-book | chapter7/user-memory-policy-eval/runner.py | .py | #!/usr/bin/env python3
"""Real-API trajectory-prefix evaluation for user-memory policy use.
The experiment deliberately supplies the memory to the model. It does not
measure whether a retriever found a fact; it measures whether the next action
uses, scopes, overrides, or refuses that known fact correctly.
"""
from _... | 323 | 13,580 |
ai-agent-book | chapter7/user-memory-policy-eval/test_runner.py | .py | from __future__ import annotations
import json
from pathlib import Path
from runner import HERE, memory_text, parse_json, score, sha256
def case_fixture() -> dict:
return json.loads((Path(__file__).parent / "cases.json").read_text(encoding="utf-8"))["cases"][1]
def test_all_memory_encodings_retain_scope_field... | 60 | 2,272 |
ai-agent-book | chapter7/android-world/run_controlled_experiment.py | .py | #!/usr/bin/env python3
"""Run a real, evidence-producing Experiment 6-11 T3A ablation.
This companion runner imports the adjacent, unmodified AndroidWorld checkout.
It supports a paired control/treatment experiment and a subsequent candidate
rerun. It never substitutes mock episodes or manuscript example numbers.
"""
... | 1,826 | 76,108 |
ai-agent-book | chapter7/android-world/merge_candidate_shards.py | .py | #!/usr/bin/env python3
"""Merge independently executed Experiment 6-11 trial shards without hiding failures."""
from __future__ import annotations
import argparse
import copy
import hashlib
import json
from pathlib import Path
from typing import Any
from experiment_core import (
BASELINE_TASK_COUNT,
aggregat... | 272 | 11,368 |
ai-agent-book | chapter7/android-world/experiment_core.py | .py | """Pure reporting helpers for the Experiment 6-11 AndroidWorld loop.
The runtime runner deliberately keeps AndroidWorld imports out of this module so
the evidence checks and report generation can be tested without an emulator.
"""
from __future__ import annotations
from collections import defaultdict
import json
imp... | 589 | 24,201 |
ai-agent-book | chapter7/android-world/test_experiment.py | .py | """Focused, offline checks for Experiment 6-11 evidence/reporting."""
from __future__ import annotations
from argparse import Namespace
import sqlite3
import pytest
from experiment_core import (
BASELINE_TASK_COUNT,
aggregate_episodes,
choose_decision,
choose_efficiency_decision,
enforce_scope_c... | 475 | 15,280 |
ai-agent-book | chapter7/experiment-6-2-human-benchmark/run_android_human.py | .py | #!/usr/bin/env python3
"""Run one pinned AndroidWorld task with the upstream HumanAgent and evaluator."""
from __future__ import annotations
import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
import sys
def load_uiautomator_env(args):
from android_env import loader
... | 100 | 3,720 |
ai-agent-book | chapter7/agent-cost-analysis/tracer.py | .py | """
自建的轻量级 tracing / 可观测系统。
设计沿用分布式追踪的 span 树模型(见书 6.x「Agent 的可观测性」):
- 一次 agent 任务 = 一条 Trace
- 每次 LLM 调用 / 工具调用 = 一个 Span
- Span 记录:所属步骤、类型、token 用量(prompt/completion/cached)、时延、成本
用法:
tracer = Tracer(client)
resp = tracer.chat(step="turn-1", tool="query_order",
model=...,... | 285 | 12,309 |
ai-agent-book | chapter7/agent-cost-analysis/demo.py | .py | """
实验 6-7:Agent 任务的端到端成本分析(可运行 demo + CLI)。
两种运行方式:
1) 在线(--live,默认):真实调用模型(默认 gpt-5.6-luna),token 与 cached_tokens
取自 API 返回的 usage,成本按单价换算。需要 OPENAI_API_KEY 或 OPENROUTER_API_KEY
(无 OpenAI key 时自动回退到 OpenRouter;gpt-5.x 只要有 OpenRouter key 就优先走它)。
2) 离线(--offline):不打模型,读入一份此前真实运行录下的 trace(canned token
... | 292 | 13,477 |
ai-agent-book | chapter7/agent-cost-analysis/config.py | .py | """
全局配置:模型与价格。
价格换算成本时使用「每百万 token 单价(美元)」。
默认值取自 OpenAI gpt-4o-mini 的公开定价(2024-2025):
- 输入 : $0.15 / 1M tokens
- 缓存命中输入 : $0.075 / 1M tokens (命中 prompt cache 的输入按 5 折计费)
- 输出 : $0.60 / 1M tokens
注意:
1. 默认模型为 gpt-5.6-luna(当前廉价旗舰)。首选凭据是 OPENAI_API_KEY;若未设置,
自动回退到 OPENROUTER_API_KEY 并把... | 130 | 5,701 |
ai-agent-book | chapter7/agent-cost-analysis/agent.py | .py | """
一个多轮「客服退款 Agent」任务,用于成本分析(对应书 6.x 表6-4 的客服退款示例)。
为了让实验可复现、不依赖模型工具调用的随机性,这里用「受控工具环境」:
每一轮我们把上一步工具的返回结果喂给模型,由模型(真实 LLM 调用)决定下一步怎么做。
工具返回内容是预设好的(真实 API 里会是订单系统/物流系统的返回),
但每一次 LLM 调用、每一份 token 用量、每一分成本都是真实的。
本文件把「是否 KV-cache 友好」和「是否压缩上下文」两个开关正交拆开,
可组合出完整的 2×2 A/B(对应书中「对比启用/禁用 KV Cache、启用/禁用上下文压缩」):
run_scenario(kv_... | 274 | 17,109 |
ai-agent-book | chapter7/agent-cost-analysis/cost_efficiency_analyzer.py | .py | """
Agent trajectory cost-efficiency analyzer (实验 6-9 成本效率分析).
Builds on the span/trace model from ``tracer.py``: an agent task is a sequence
of turns, each turn carrying token usage (prompt / cached / completion), tool
context tokens, and latency. This module turns a recorded trajectory into an
:class:`EfficiencyRepo... | 453 | 17,713 |
ai-agent-book | chapter7/agent-cost-analysis/tests/test_chat_null_usage.py | .py | """Tracer.chat must tolerate response.usage == None (OpenAI-compatible providers)."""
from types import SimpleNamespace
import config
from tracer import Tracer
class _FakeClient:
def __init__(self, usage):
self.chat = SimpleNamespace(
completions=SimpleNamespace(create=self._create)
... | 45 | 1,313 |
ai-agent-book | chapter7/agent-cost-analysis/tests/test_trace_offline.py | .py | """
Regression tests for offline trace parsing (实验 6-7 成本分析).
Covers two crash classes found in --offline mode:
- Tracer.from_records: trace JSON with explicit null token fields -> int(None) TypeError
- demo.collect_offline: scenario dict missing the optional "spans" key -> KeyError
"""
import json
import pytest
... | 97 | 3,480 |
ai-agent-book | chapter7/agent-cost-analysis/tests/conftest.py | .py | """Test import bootstrap for the agent-cost-analysis experiment."""
from pathlib import Path
import sys
EXPERIMENT_ROOT = Path(__file__).resolve().parents[1]
if str(EXPERIMENT_ROOT) not in sys.path:
sys.path.insert(0, str(EXPERIMENT_ROOT))
| 10 | 247 |
ai-agent-book | chapter7/elo-leaderboard/quickstart.py | .py | """
Quick start demo - minimal example to get started quickly
"""
from elo_rating import EloRatingSystem
def demo_basic_elo():
"""Demonstrate basic Elo rating calculation with synthetic data."""
print("="*60)
print("Quick Start: Elo Rating System Demo")
print("="*60)
print()
# Initia... | 81 | 2,787 |
ai-agent-book | chapter7/elo-leaderboard/animation.py | .py | """
Create animated bar chart race showing leaderboard evolution over time
"""
import pandas as pd
import numpy as np
from typing import List, Tuple
import json
import os
def prepare_animation_data(history_df: pd.DataFrame, top_n: int = 15) -> dict:
"""
Prepare data for D3.js bar chart race animation.
... | 437 | 13,632 |
ai-agent-book | chapter7/elo-leaderboard/main.py | .py | """
Main script for Model Leaderboard Calculation
Experiment 6-6: Building Model Leaderboard from Pairwise Comparison Data
Supports two methods (following official Chatbot Arena):
1. Online Elo (K=4) - Simple but order-dependent
2. Bradley-Terry MLE - Official leaderboard method (more stable)
"""
import os
import sys
... | 243 | 9,084 |
ai-agent-book | chapter7/elo-leaderboard/optimized_elo.py | .py | """
Optimized Elo rating system using NumPy vectorization and Numba JIT
"""
import numpy as np
import pandas as pd
from typing import Dict, Tuple, List
from numba import jit
from tqdm import tqdm
@jit(nopython=True)
def expected_score_fast(rating_a: float, rating_b: float) -> float:
"""
Fast expected score ca... | 304 | 11,076 |
ai-agent-book | chapter7/elo-leaderboard/elo_rating.py | .py | """
Elo Rating System Implementation
Based on Bradley-Terry model for pairwise comparison
"""
import numpy as np
from typing import Dict, Tuple, Optional
class EloRatingSystem:
"""
Implementation of Elo rating system for model comparison.
The Elo system updates ratings based on pairwise comparison ou... | 170 | 6,221 |
ai-agent-book | chapter7/elo-leaderboard/parallel_processing.py | .py | """
Parallel processing utilities for Elo rating computation
"""
import pandas as pd
import numpy as np
from multiprocessing import Pool, cpu_count
from functools import partial
from typing import List, Tuple
from tqdm import tqdm
from elo_rating import EloRatingSystem
def process_time_slice(args: Tuple) -> Tuple:
... | 323 | 10,619 |
ai-agent-book | chapter7/elo-leaderboard/benchmark.py | .py | """
Benchmark script to compare performance of different Elo implementations
"""
import time
import pandas as pd
import numpy as np
from elo_rating import EloRatingSystem
from optimized_elo import build_leaderboard_optimized
from data_loader import load_arena_data, filter_data
def benchmark_basic_elo(df: pd.DataFrame... | 145 | 5,174 |
ai-agent-book | chapter7/elo-leaderboard/visualization.py | .py | """
Visualization tools for Elo leaderboard analysis
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from typing import List, Tuple, Optional
import plotly.graph_objects as go
import plotly.express as px
def plot_leaderboard(leaderboard_data: list, top_n: int = 20, sav... | 284 | 9,236 |
ai-agent-book | chapter7/elo-leaderboard/bradley_terry.py | .py | """
Bradley-Terry Model Implementation
Official Chatbot Arena leaderboard calculation method
"""
import math
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
def compute_mle_elo(df: pd.DataFrame,
SCALE: int = 400,
BASE: int = 10,
... | 239 | 8,420 |
ai-agent-book | chapter7/elo-leaderboard/llm_judge.py | .py | """
LLM-as-judge pairwise battles with position-bias mitigation.
This is the only battle source that needs network access; `simulate` and
`arena` run fully offline.
Two backends are supported, selected automatically or via ``backend=``:
* ``anthropic`` – the official ``anthropic`` SDK, using ``ANTHROPIC_API_KEY``... | 272 | 10,856 |
ai-agent-book | chapter7/elo-leaderboard/data_loader.py | .py | """
Data loading and preprocessing for Chatbot Arena voting data
"""
import pandas as pd
import requests
import os
from typing import Optional
from tqdm import tqdm
def download_arena_data(output_path: str = "arena_data.json", force_download: bool = False) -> str:
"""
Download Chatbot Arena voting data via HT... | 224 | 7,930 |
ai-agent-book | chapter7/elo-leaderboard/cli.py | .py | #!/usr/bin/env python3
"""
实验 6-6:从配对比较数据构建模型排行榜 —— 命令行入口
统一的 argparse 命令行工具,把整个流程拆成三个子命令:
battle 运行两两对战,生成对战结果(模拟 / Chatbot Arena 真实数据 / LLM 评判)
elo 从对战结果计算 Elo 或 Bradley-Terry 评分
leaderboard 把对战结果或评分渲染成最终排行榜表格
pipeline 一步跑完 对战 -> Elo -> 排行榜(默认离线可复现)
其中 battle 的 simulate/aren... | 344 | 16,209 |
ai-agent-book | chapter7/elo-leaderboard/battle_simulator.py | .py | """
Synthetic pairwise battle generator (offline).
Generates head-to-head "battle" outcomes from a set of known latent skill
scores, so the whole battles -> Elo -> leaderboard pipeline can be demonstrated
end-to-end without downloading the 2GB Chatbot Arena dataset or calling any API.
Because the ground-truth skills ... | 78 | 2,957 |
ai-agent-book | chapter7/elo-leaderboard/leaderboard.py | .py | """
Leaderboard calculation and analysis
"""
import pandas as pd
import numpy as np
from typing import Dict, List, Tuple
from tqdm import tqdm
from elo_rating import EloRatingSystem
def build_leaderboard(df: pd.DataFrame,
initial_rating: float = 1000.0,
k_factor: float = 3... | 244 | 8,217 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.