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
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/googlesearch_server/src/base.py
.py
import logging import os import tempfile import magic import traceback from pathlib import Path from urllib.parse import urlparse import requests from pydantic import BaseModel, Field from typing import Any, Literal class DocumentMetadata(BaseModel): """Metadata extracted from document processing.""" file...
224
7,922
ai-agent-book
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/media_server/src/image.py
.py
import base64 import json import logging import os import time import traceback from io import BytesIO from pathlib import Path from typing import Any, Union import pytesseract from PIL import Image, ImageEnhance, ImageFilter from dotenv import load_dotenv from pydantic.fields import FieldInfo from mcp.server import ...
561
18,194
ai-agent-book
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/media_server/src/video.py
.py
import base64 import json import logging import os import time import traceback from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path from typing import Union import cv2 import numpy as np from dotenv import load_dotenv from mcp.server import FastMCP from mcp.types import TextConten...
987
32,225
ai-agent-book
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/media_server/src/audio.py
.py
import json import logging import os import subprocess import time import traceback from pathlib import Path from typing import Any, Union, Literal from openai import OpenAI from pydantic.fields import FieldInfo from mcp.server import FastMCP from mcp.types import TextContent from pydantic import Field, BaseModel from...
668
23,090
ai-agent-book
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/browseruse_server/src/main.py
.py
import asyncio import logging import os import sys import traceback from typing import Union from browser_use import Agent, BrowserSession from browser_use.llm import ChatOpenAI from dotenv import load_dotenv from fastmcp.server.server import FastMCP from mcp.types import TextContent from pydantic import Field loggin...
100
3,378
ai-agent-book
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/wayback_server/src/wayback.py
.py
import json import logging import time import traceback from datetime import datetime from pathlib import Path from typing import Any, Union, Literal import chardet import pandas as pd import requests from bs4 import BeautifulSoup from dotenv import load_dotenv from pydantic.fields import FieldInfo from waybackpy impo...
616
20,810
ai-agent-book
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/download_server/src/download.py
.py
import json import logging import shutil import time import traceback from datetime import datetime from pathlib import Path from typing import Union from urllib.parse import urlparse import requests from dotenv import load_dotenv from pydantic.fields import FieldInfo from mcp.server import FastMCP from mcp.types impo...
511
16,027
ai-agent-book
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/download_server/src/base.py
.py
import logging import os import tempfile import magic import traceback from pathlib import Path from urllib.parse import urlparse import requests from pydantic import BaseModel, Field from typing import Any, Literal class DocumentMetadata(BaseModel): """Metadata extracted from document processing.""" file_...
225
7,982
ai-agent-book
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/documents_server/src/docx_server.py
.py
import json import logging import time import traceback import zipfile from pathlib import Path from typing import Any, Union, Literal from docx import Document from docx.document import Document as DocumentType from dotenv import load_dotenv from pydantic.fields import FieldInfo from mcp.server import FastMCP from m...
784
27,911
ai-agent-book
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/documents_server/src/csv_server.py
.py
import json import logging import time import traceback from pathlib import Path from typing import Any, Union, Literal import chardet import pandas as pd from dotenv import load_dotenv from pydantic.fields import FieldInfo from mcp.server import FastMCP from mcp.types import TextContent from pydantic import Field f...
447
14,957
ai-agent-book
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/documents_server/src/pdf_server.py
.py
import asyncio import json import logging import os import sys import traceback import filetype from pathlib import Path from typing import Literal, Union, Any import requests from datalab_sdk.models import ConversionResult, ConvertOptions, OCROptions from dotenv import load_dotenv from mcp.server import FastMCP from...
259
8,796
ai-agent-book
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/documents_server/src/pptx_server.py
.py
import json import logging import time import traceback import zipfile from pathlib import Path from typing import Any, Union, Literal from dotenv import load_dotenv from pptx import Presentation from pptx.presentation import Presentation as PresentationType from pydantic.fields import FieldInfo from mcp.server impo...
631
22,096
ai-agent-book
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/documents_server/src/txt_server.py
.py
import json import logging import time import traceback from pathlib import Path from typing import Any, Union, Literal import chardet from dotenv import load_dotenv from pydantic.fields import FieldInfo from mcp.server import FastMCP from mcp.types import TextContent from pydantic import Field from base import ( ...
722
24,987
ai-agent-book
chapter9/gaia-experience/AWorld/env/gaia-mcp-server/mcp_servers/documents_server/src/base.py
.py
import logging import os import tempfile import traceback from pathlib import Path from urllib.parse import urlparse import requests from pydantic import BaseModel, Field from typing import Any, Literal class DocumentMetadata(BaseModel): """Metadata extracted from document processing.""" file_name: str = ...
226
7,991
ai-agent-book
chapter9/self-modifying-agent/test_candidate_sandbox.py
.py
import unittest from unittest.mock import patch from candidate_sandbox import MAX_SOURCE_BYTES, SandboxError, _docker_command, run_in_sandbox class CandidateSandboxConfigurationTest(unittest.TestCase): def test_docker_command_enforces_isolation_and_resource_limits(self): command = _docker_command("sandbo...
45
1,697
ai-agent-book
chapter9/self-modifying-agent/test_real_evidence.py
.py
import hashlib import json from pathlib import Path ROOT = Path(__file__).parent def test_canonical_real_coding_agent_evidence_closes_all_gates(): evidence = json.loads((ROOT / "validation" / "latest.json").read_text(encoding="utf-8")) expected_sha = (ROOT / "validation" / "latest.sha256").read_text(encodin...
26
1,402
ai-agent-book
chapter9/self-modifying-agent/evolution.py
.py
"""Auditable self-modification and trusted release gates for Experiment 8-5.""" from __future__ import annotations import ast from collections import defaultdict import difflib import hashlib from pathlib import Path from typing import Any, Dict, Iterable from candidate_sandbox import MAX_SOURCE_BYTES, SandboxError,...
323
12,865
ai-agent-book
chapter9/self-modifying-agent/sandbox_runner.py
.py
"""Container entrypoint. Never import this module in the trusted host process.""" from __future__ import annotations from contextlib import redirect_stderr, redirect_stdout import inspect import json import sys from typing import Any MAX_REQUEST_BYTES = 1024 * 1024 SANDBOX_CHECKS = ( "public_api_compatible", ...
162
5,414
ai-agent-book
chapter9/self-modifying-agent/test_evolution.py
.py
import json import tempfile import unittest from pathlib import Path import uuid from evolution import ( behavior_metrics, diagnose, generate_candidate, generate_rejected_control, release_manifest, validate_candidate, ) ROOT = Path(__file__).parent class SelfModificationTest(unittest.TestCase): @classm...
155
7,608
ai-agent-book
chapter9/self-modifying-agent/demo.py
.py
"""Run the complete offline self-modification release flow.""" from __future__ import annotations import argparse import json from pathlib import Path from evolution import diagnose, generate_candidate, release_manifest, validate_candidate, write_candidate ROOT = Path(__file__).parent def main() -> None: par...
51
2,066
ai-agent-book
chapter9/self-modifying-agent/llm_generator.py
.py
"""Real API Coding Agent used by the Experiment 8-5 campaign.""" from __future__ import annotations import hashlib import json import os import re import time from typing import Any, Dict from openai import OpenAI from evolution import candidate_from_source def _extract_json(text: str) -> dict[str, Any]: clea...
134
5,107
ai-agent-book
chapter9/self-modifying-agent/run_experiment_8_5.py
.py
#!/usr/bin/env python3 """Run the real Coding-Agent self-modification campaign for Experiment 8-5.""" from __future__ import annotations import argparse from datetime import datetime, timezone import hashlib import json from pathlib import Path import shutil from typing import Any from candidate_sandbox import sandb...
248
10,639
ai-agent-book
chapter9/self-modifying-agent/candidate_sandbox.py
.py
"""Fail-closed Docker boundary for model-generated policy code.""" from __future__ import annotations from functools import lru_cache import hashlib import json import os from pathlib import Path import subprocess import threading from typing import Any, Iterable import uuid ROOT = Path(__file__).resolve().parent D...
206
7,139
ai-agent-book
chapter9/self-modifying-agent/stable/retry_policy.py
.py
"""Stable version 1.0.0. It intentionally contains the reproduced bug.""" VERSION = "1.0.0" MAX_RETRIES = 3 CIRCUIT_BREAKER_THRESHOLD = 5 NON_RETRYABLE_CODES = {"AUTH_DENIED", "INVALID_ARGUMENT"} def should_retry(error_code, retryable, attempt): """Return whether another tool call should be attempted.""" ret...
17
530
ai-agent-book
chapter9/self-modifying-agent/validation/real_20260729T171118Z/candidates/deterministic/retry_policy.py
.py
"""Stable version 1.0.0. It intentionally contains the reproduced bug.""" VERSION = "1.1.0-candidate" MAX_RETRIES = 3 CIRCUIT_BREAKER_THRESHOLD = 5 NON_RETRYABLE_CODES = {"AUTH_DENIED", "INVALID_ARGUMENT", "PAYMENT_DECLINED"} def should_retry(error_code, retryable, attempt): """Return whether another tool call s...
21
778
ai-agent-book
chapter9/self-modifying-agent/validation/real_20260729T171118Z/candidates/real_llm/retry_policy.py
.py
VERSION = "1.0.1" MAX_RETRIES = 3 CIRCUIT_BREAKER_THRESHOLD = 5 NON_RETRYABLE_CODES = {"AUTH_DENIED", "INVALID_ARGUMENT", "PAYMENT_DECLINED"} def should_retry(error_code, retryable, attempt): """Return whether another tool call should be attempted.""" if not retryable or error_code in NON_RETRYABLE_CODES: ...
19
655
ai-agent-book
chapter9/self-modifying-agent/validation/real_20260729T171118Z/candidates/rejected_control/retry_policy.py
.py
"""Stable version 1.0.0. It intentionally contains the reproduced bug.""" VERSION = "1.0.1-rejected" MAX_RETRIES = 3 CIRCUIT_BREAKER_THRESHOLD = 5 NON_RETRYABLE_CODES = {"AUTH_DENIED", "INVALID_ARGUMENT"} def should_retry(error_code, retryable, attempt): """Incorrect over-broad fix retained as a rejected candida...
19
666
ai-agent-book
chapter9/self-modifying-agent/validation/real_20260802T043954Z/candidates/real_llm/retry_policy.py
.py
"""Candidate version 1.0.1-rc.1 with permanent-failure handling.""" VERSION = "1.0.1-rc.1" MAX_RETRIES = 3 CIRCUIT_BREAKER_THRESHOLD = 5 NON_RETRYABLE_CODES = {"AUTH_DENIED", "INVALID_ARGUMENT"} def should_retry(error_code, retryable, attempt): """Return whether another tool call should be attempted.""" if n...
21
757
ai-agent-book
chapter9/trajectory-verifier/test_llm_judge_null_fields.py
.py
"""Regression: OpenAIQualityJudge must tolerate an explicit JSON null for score / confidence / evidence in the model's response — dict.get(key, default) only applies the default when the key is ABSENT, so a null value returns None and float(None) / iterating None crash the whole trajectory evaluation.""" import json im...
100
3,994
ai-agent-book
chapter9/trajectory-verifier/evidence_client.py
.py
"""Credential-free real chat-completion capture for Experiment 8-1.""" from __future__ import annotations import os import time from typing import Any from openai import OpenAI BACKENDS = { "openrouter": ("OPENROUTER_API_KEY", "https://openrouter.ai/api/v1", "openai/gpt-4o-mini"), "moonshot": ("MOONSHOT_AP...
86
3,419
ai-agent-book
chapter9/trajectory-verifier/test_claim_action_order.py
.py
import unittest from types import SimpleNamespace from customer_service_env import _derive_claims_and_promises, run_case from verifier import TrajectoryVerifier def response(content="", calls=()): tool_calls = [ SimpleNamespace( id=f"call-{index}", function=SimpleNamespace(name=na...
120
5,111
ai-agent-book
chapter9/trajectory-verifier/test_empty_dimensions_score.py
.py
""" TrajectoryVerifier.evaluate must handle empty dimensions list without raising ZeroDivisionError. """ from unittest.mock import MagicMock from verifier import TrajectoryVerifier def test_trajectory_verifier_handles_empty_dimensions(): verifier = TrajectoryVerifier() verifier.result_verifier.evaluate = Magi...
18
683
ai-agent-book
chapter9/trajectory-verifier/consistency_checker.py
.py
"""Trajectory consistency checker for chapter 8. Detects ungrounded claims, contradictions, hallucinated tool results, and unsupported conclusions in agent trajectories. Purely heuristic and deterministic: no network calls, no LLM dependency. A trajectory is a list of step dictionaries. Each step may contain: ...
380
14,880
ai-agent-book
chapter9/trajectory-verifier/test_real_campaign.py
.py
import unittest from run_experiment_8_1 import build_evidence class FakeClient: provider = "fake" model = "fake-model" base_url = "https://invalid.test/v1" credential_source_env = "FAKE_KEY" api_turns = [{"kind": "customer_service_agent"}, {"kind": "quality_judge"}] def usage_summary(self): ...
37
1,244
ai-agent-book
chapter9/trajectory-verifier/calibration.py
.py
"""Calibration helpers for comparing the verifier with expert labels.""" from __future__ import annotations from typing import Any, Dict, Iterable from verifier import FAIL, _item_get def calibration_report( trajectories: Iterable[Dict[str, Any]], reports: Iterable[Dict[str, Any]] ) -> Dict[str, Any]: pair...
51
2,194
ai-agent-book
chapter9/trajectory-verifier/run_experiment_8_1.py
.py
#!/usr/bin/env python3 """Canonical real campaign for manuscript Experiment 8-1.""" from __future__ import annotations import argparse import hashlib import json import platform import subprocess import sys from datetime import datetime, timezone from pathlib import Path from calibration import calibration_report fr...
153
8,257
ai-agent-book
chapter9/trajectory-verifier/verifier.py
.py
"""Three-layer trajectory verifier used by Experiment 8-1. Environment and policy conclusions stay deterministic. Only the two open- ended language dimensions are delegated to a quality Judge. """ from __future__ import annotations from dataclasses import asdict, dataclass from typing import Any, Dict, Iterable, Li...
352
13,665
ai-agent-book
chapter9/trajectory-verifier/customer_service_env.py
.py
"""Stateful synthetic customer-service sandbox used to collect real LLM trajectories. The customers and orders are fictional. The Agent and quality Judge are real provider calls; order state, policy enforcement, and tool results are local environment truth and are therefore independently checkable. """ from __future...
278
11,994
ai-agent-book
chapter9/trajectory-verifier/demo.py
.py
"""Run Experiment 8-1 without an API key.""" from __future__ import annotations import argparse import json from pathlib import Path from calibration import calibration_report from verifier import TrajectoryVerifier, diagnostic_utility, scalar_baseline ROOT = Path(__file__).parent def main() -> None: parser ...
46
1,734
ai-agent-book
chapter9/trajectory-verifier/llm_judge.py
.py
"""Real OpenAI Responses API judge for Experiment 8-1.""" from __future__ import annotations import json import re from typing import Any, Dict, Iterable try: from dotenv import load_dotenv load_dotenv() except ImportError: pass from verifier import DimensionResult, FAIL, PASS, UNCERTAIN def _json_obj...
120
5,366
ai-agent-book
chapter9/trajectory-verifier/test_derive_claims_promises_null_result.py
.py
import unittest from customer_service_env import _derive_claims_and_promises class TestDeriveClaimsPromisesNullResult(unittest.TestCase): def test_derive_claims_and_promises_tolerates_non_dict_result(self): """Contract: _derive_claims_and_promises handles tool calls with None or non-dict result fields. ...
25
974
ai-agent-book
chapter9/trajectory-verifier/test_verifier_null_fields.py
.py
"""Regression tests: verifier module must tolerate null/None or non-dict values for trajectory fields.""" import pytest from verifier import ( ProcessVerifier, ResultVerifier, TrajectoryVerifier, diagnostic_utility, FAIL, PASS, UNCERTAIN, ) def test_process_verifier_tolerates_null_fields()...
125
4,608
ai-agent-book
chapter9/trajectory-verifier/test_verifier.py
.py
import json import unittest from pathlib import Path from calibration import calibration_report from verifier import TrajectoryVerifier, diagnostic_utility, scalar_baseline class VerifierTest(unittest.TestCase): @classmethod def setUpClass(cls): path = Path(__file__).with_name("sample_trajectories.js...
35
1,365
ai-agent-book
chapter9/trajectory-verifier/test_calibration_report_dimension_result.py
.py
import unittest from calibration import calibration_report from verifier import DimensionResult class TestCalibrationReportDimensionResult(unittest.TestCase): def test_calibration_report_supports_dimension_result_objects(self): """Contract: calibration_report handles report dimensions containing Dimensio...
30
1,010
ai-agent-book
chapter9/self-evolving-tools/tool_manager.py
.py
""" 工具库管理:create_tool(封装并持久化)、search_tools(检索复用)、以及被封装工具的执行。 这是 Alita 式「自我进化」的核心: - Agent 用 code_interpreter 验证过某个方案后,调用 create_tool 把它固化成一个 「标准工具」——包含 name / description / JSON-Schema 参数 / Python 代码,持久化到 tool_library/。 - 下次遇到同类任务,Agent 应先 search_tools 命中已有工具并直接复用,而不是重新上网搜索、重新写代码。 """ import json import os import s...
211
9,417
ai-agent-book
chapter9/self-evolving-tools/test_normalize_schema_bare_object.py
.py
"""normalize_schema must keep bare {"type":"object"} as an empty-object schema while preserving extra metadata.""" from tool_manager import normalize_schema def test_bare_object_type_stays_empty_properties(): assert normalize_schema({"type": "object"}) == { "type": "object", "properties": {}, ...
59
1,626
ai-agent-book
chapter9/self-evolving-tools/test_web_search_num_results.py
.py
"""web_search 对模型给出的异常 num_results(null / 非数字字符串)应兜底为默认值, 而不是抛 TypeError/ValueError 中断整个 Agent 循环。""" import json import base_tools def _search_without_network(monkeypatch, num_results): """屏蔽真实网络与退避 sleep,只验证参数处理不崩溃。""" def _fake_post(*a, **k): raise RuntimeError("network disabled in test") mon...
37
1,573
ai-agent-book
chapter9/self-evolving-tools/test_tool_result_bad_json.py
.py
"""Regression: malformed __TOOL_RESULT__ JSON must not raise JSONDecodeError.""" import tempfile from pathlib import Path from tool_manager import ToolLibrary def test_malformed_tool_result_returns_error_dict(): lib = ToolLibrary(library_dir=Path(tempfile.mkdtemp())) # Tool prints a broken marker line, then ...
31
1,311
ai-agent-book
chapter9/self-evolving-tools/demo.py
.py
""" 补充案例一键演示:`python demo.py` 演示两件事: 1) 进化:Agent 从零基础工具出发 —— 搜索 → 读文档 → 沙箱测试 → 封装工具 → 用新工具给出 NVIDIA(NVDA) 的真实股价与「相对一周前」的真实涨跌幅。 2) 复用:换一支股票(AAPL) 再问一次。Agent 应先 search_tools 命中已创建的工具并直接复用, 不再重新上网搜索、重新造轮子。程序会打印轨迹并自动校验「复用」是否成立。 在线路径(默认)需要真实联网 + 真实调用 OpenAI,请先配置 OPENAI_API_KEY。 若手头没有 API key / 无法联网,可用 `--off...
281
13,980
ai-agent-book
chapter9/self-evolving-tools/base_tools.py
.py
""" 五个基础工具中的「非工具库」部分:web_search / read_webpage / code_interpreter。 设计原则(对应补充案例“最小预定义,最大自我进化”): - 这里 **不包含任何领域工具**(没有 get_stock_price、没有 get_youtube_transcript ...)。 - Agent 只能靠 web_search 找开源库/API,read_webpage 读文档, code_interpreter 在子进程沙箱里真实执行代码来验证方案是否可行。 - 所有输出都基于「真实网络结果 / 真实执行结果」,从而抑制大模型的幻觉。 """ import json impor...
212
9,058
ai-agent-book
chapter9/self-evolving-tools/agent.py
.py
""" 自我进化 Agent(Alita 式)。 只预定义五个基础工具: web_search / read_webpage / code_interpreter / create_tool / search_tools 没有任何领域工具。Agent 必须: 分析任务 → 识别能力缺口 → web_search 找库/API → read_webpage 读文档 → code_interpreter 沙箱测试 → create_tool 封装入库 → 用新工具完成任务。 再次遇到同类任务时,应先 search_tools 复用已有工具,而非重新搜索创建。 模型:OpenAI SDK,默认 gpt-5.6-...
369
18,988
ai-agent-book
chapter9/self-evolving-tools/test_search_null_fields.py
.py
from tool_manager import ToolLibrary import tempfile from pathlib import Path def test_search_null_name_or_description(): with tempfile.TemporaryDirectory() as tmpdir: lib = ToolLibrary(library_dir=Path(tmpdir)) # Create a tool file manually with null description p = Path(tmpdir) / "null_d...
23
869
ai-agent-book
chapter9/hermes-self-evolution/run_experiment_8_6.py
.py
#!/usr/bin/env python3 """Clone a pinned Hermes snapshot and let Hermes audit/update its own code. The runner keeps credentials outside retained evidence. Normal working state is written beneath ignored ``worktree/`` and ``.hermes-home/`` directories; the curated manifest and patch are written to ``validation/<run-id>...
191
6,534
ai-agent-book
chapter9/hermes-self-evolution/run_downstream_ablation.py
.py
"""Downstream Ablation Engine for Hermes Self-Evolution. Evaluates baseline vs. self-evolved agent code across synthetic and real task suites: - Pass rate uplift measurement - Execution latency change tracking - Code quality scoring (AST metrics, complexity, readability) - Regression rate analysis (tasks passed by bas...
602
24,376
ai-agent-book
chapter9/hermes-self-evolution/run_acceptance_review.py
.py
#!/usr/bin/env python3 """Run a fresh, read-only Hermes acceptance review of the candidate patch.""" from __future__ import annotations import argparse import os from pathlib import Path import re import subprocess import sys ROOT = Path(__file__).resolve().parent MODEL = "openai/gpt-5.6-luna" SECRET_PATTERNS = ( ...
100
2,864
ai-agent-book
chapter9/hermes-self-evolution/run_review_pass.py
.py
#!/usr/bin/env python3 """Continue the canonical Hermes session with independent review feedback.""" from __future__ import annotations import os from pathlib import Path import re import subprocess import sys import argparse ROOT = Path(__file__).resolve().parent RUN_ID = "exp8-6-hermes-gpt56luna-20260802-v1" MODE...
72
2,148
ai-agent-book
chapter9/hermes-self-evolution/finalize_evidence.py
.py
#!/usr/bin/env python3 """Finalize and independently validate the retained Experiment 8-6 evidence.""" from __future__ import annotations import hashlib import json from pathlib import Path import re import shutil import subprocess import tempfile ROOT = Path(__file__).resolve().parent RUN_ID = "exp8-6-hermes-gpt56...
182
7,082
ai-agent-book
tests/test_epub_external_links.py
.py
from pathlib import Path import shutil import subprocess import tempfile import pytest HAS_LUA = shutil.which("texlua") is not None or shutil.which("lua") is not None pytestmark = pytest.mark.skipif(not HAS_LUA, reason="texlua or lua executable not found in PATH") ROOT = Path(__file__).parents[1] def run_lua_link(...
91
3,558
ai-agent-book
tests/test_ch4_semantic_router_stop_words_query.py
.py
import sys from pathlib import Path import pytest pytest.importorskip("numpy") pytest.importorskip("sklearn") # Add active-tool-selection to sys.path sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "chapter4" / "active-tool-selection")) from semantic_router import SemanticRouter from tool_knowledge_b...
59
2,253
ai-agent-book
tests/test_providers.py
.py
"""Tests for the shared provider registry. Focus is behaviour parity with the three per-chapter copies this module replaces, plus the resolution rules that are easy to regress. """ import dataclasses import pytest from agentbook.providers import ( OPENROUTER_DEFAULT_MODEL, PROVIDERS, SUPPORTED_PROVIDERS...
543
21,909
ai-agent-book
tests/test_ch8_safety_policy_gate.py
.py
import sys from pathlib import Path # Add module directory to path for imports ch8_dir = Path(__file__).resolve().parent.parent / "chapter8" / "harness-safety-gate" if str(ch8_dir) not in sys.path: sys.path.insert(0, str(ch8_dir)) from safety_policy_gate import ( SafetyGateDecision, SafetyPolicyGate, ...
215
7,851
ai-agent-book
tests/test_ch6_score_prediction_unhashable_claims.py
.py
import sys from pathlib import Path HERE = Path(__file__).resolve().parent.parent EVAL_DIR = HERE / "chapter6" / "public-health-reporting-eval" if str(EVAL_DIR) not in sys.path: sys.path.insert(0, str(EVAL_DIR)) from evaluator import score_prediction # noqa: E402 def test_score_prediction_unhashable_dict_claim...
36
984
ai-agent-book
tests/test_ch5_pedo_live_security_eval.py
.py
"""Unit tests for chapter5/permission-embedded-data-objects/run_live_security_eval.py.""" from pathlib import Path import sys from typing import Any import pytest # Ensure chapter5/permission-embedded-data-objects is in sys.path ch5_dir = Path(__file__).resolve().parent.parent / "chapter5" / "permission-embedded-data...
760
30,868
ai-agent-book
tests/test_resolve_backend_whitespace_model.py
.py
from agentbook.providers.resolution import resolve_backend def test_resolve_backend_whitespace_model_uses_default(): backend = resolve_backend("ollama", model=" ") assert backend.model == "qwen3:8b"
7
211
ai-agent-book
tests/test_ch10_orchestrator_non_dict_tool_arguments.py
.py
import sys, os from unittest.mock import MagicMock sys.path.insert(0, os.path.abspath("chapter10/multi-role-transfer")) from orchestrator import MultiRoleOrchestrator def test_orchestrator_non_dict_tool_call_arguments_handled(): mock_client = MagicMock() # Mock tool call with arguments parsing to a list [1,...
38
1,248
ai-agent-book
tests/test_ch10_multi_role_transfer_unhashable_target.py
.py
import json import sys from pathlib import Path from types import SimpleNamespace import pytest ch10_mrt = Path(__file__).resolve().parent.parent / "chapter10" / "multi-role-transfer" if str(ch10_mrt) not in sys.path: sys.path.insert(0, str(ch10_mrt)) tools_backup = sys.modules.pop("tools", None) from orchestrato...
57
1,883
ai-agent-book
tests/test_ch4_notification_dispatcher.py
.py
"""Unit tests for chapter4/collaboration-tools/src/notification_dispatcher.py.""" import asyncio import logging from pathlib import Path import sys import pytest # Ensure chapter4/collaboration-tools/src is in sys.path ch4_src = (Path(__file__).resolve().parent.parent / "chapter4" / "collaboration-tools" / "src").res...
770
29,326
ai-agent-book
tests/test_ch6_cost_efficiency_analyzer.py
.py
""" Tests for CostEfficiencyAnalyzer (实验 6-9 成本效率分析). Covers trajectory parsing, per-turn metrics, cost calculation, efficiency scoring, turn classification, recommendations, and edge cases (empty, single turn, all-wasteful, all-cached). Fully offline — no model calls, no network. """ from __future__ import annotation...
477
19,713
ai-agent-book
tests/test_mkdocs_pandoc_strip.py
.py
import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) from mkdocs_pandoc_strip import on_page_markdown def test_pandoc_strip_preserves_code_blocks_and_inline_code(): """Prove that code blocks and inline code containing Pandoc-like attribute patterns (e...
74
2,653
ai-agent-book
tests/test_site_i18n.py
.py
import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) from site_i18n import canonical_nav_labels def test_canonical_nav_labels_preserves_colons_in_quoted_strings(): """Prove that double-quoted and single-quoted nav labels containing colons (e.g., "第1章:...
63
2,129
ai-agent-book
tests/test_ch4_expanded_catalog_limit_null.py
.py
import sys, os sys.path.insert(0, os.path.abspath("chapter4/perception-tools/src")) from expanded_catalog import _limit def test_expanded_catalog_limit_null_option_handled(): # Options dict with "limit": None (e.g. parsed from JSON '{"limit": null}') limit = _limit({"limit": None}, default=10) assert lim...
15
471
ai-agent-book
tests/test_ch8_hermes_downstream_ablation.py
.py
"""Unit tests for chapter8/hermes-self-evolution/run_downstream_ablation.py.""" from pathlib import Path import sys import time import math import pytest # Ensure chapter8/hermes-self-evolution is in sys.path ch8_dir = Path(__file__).resolve().parent.parent / "chapter8" / "hermes-self-evolution" if str(ch8_dir) not i...
481
16,344
ai-agent-book
tests/test_ch9_qwen2_acoustic_events.py
.py
import pytest pytest.importorskip("librosa") import importlib import sys from pathlib import Path ch9_streaming = Path(__file__).resolve().parent.parent / "chapter9" / "streaming-speech" if str(ch9_streaming) not in sys.path: sys.path.insert(0, str(ch9_streaming)) import qwen2_streaming # noqa: E402 importlib.re...
56
1,981
ai-agent-book
tests/test_ch7_multilingual_reasoning_sft.py
.py
import sys, os from unittest.mock import MagicMock sys.path.insert(0, os.path.abspath("chapter7/MultilingualReasoning")) from gpt_oss_20b_sft import format_chat_template def test_format_chat_template_handles_non_list_messages(): mock_tokenizer = MagicMock() mock_tokenizer.apply_chat_template.return_value = "...
18
673
ai-agent-book
tests/test_ch2_prompt_injection_robustness.py
.py
"""Unit tests for chapter2/prompt-injection/robustness_evaluator.py. Verifies the PromptInjectionRobustnessEvaluator across positive, negative, boundary, and edge cases using deterministic mock response functions — no network or live API calls. """ from __future__ import annotations import sys from pathlib import Pa...
271
11,189
ai-agent-book
tests/test_ch6_rate_ramp_benchmark.py
.py
"""Unit tests for chapter6/model-benchmark/rate_ramp_benchmark.py.""" from pathlib import Path import sys # Ensure chapter6/model-benchmark is in sys.path ch6_dir = Path(__file__).resolve().parent.parent / "chapter6" / "model-benchmark" if str(ch6_dir) not in sys.path: sys.path.insert(0, str(ch6_dir)) from rate_...
262
10,360
ai-agent-book
tests/test_ch3_bm25_zero_avgdl.py
.py
import pytest import os import sys sys.path.insert(0, os.path.abspath("chapter3/sparse-embedding")) from collections import Counter from bm25_engine import InvertedIndex, BM25 def test_bm25_calculate_term_score_zero_avgdl(): """Prove that calculating term score when avgdl is 0 handles division by zero safely.""...
32
925
ai-agent-book
tests/test_ch3_document_store_stale_metadata.py
.py
import pytest import sys from pathlib import Path ch3_retrieval = Path(__file__).resolve().parent.parent / "chapter3" / "retrieval-pipeline" if str(ch3_retrieval) not in sys.path: sys.path.insert(0, str(ch3_retrieval)) from document_store import DocumentStore # noqa: E402 def test_add_document_clears_stale_met...
47
1,738
ai-agent-book
tests/test_ch7_evaluate_multilingual.py
.py
"""Unit tests for chapter7/MultilingualReasoning/evaluate_multilingual.py.""" from pathlib import Path import sys import warnings # Ensure chapter7/MultilingualReasoning is in sys.path ch7_dir = Path(__file__).resolve().parent.parent / "chapter7" / "MultilingualReasoning" if str(ch7_dir) not in sys.path: sys.path...
296
11,590
ai-agent-book
tests/test_ch3_bm25_reindex_doc.py
.py
import pytest """Regression test: re-indexing an existing doc_id in InvertedIndex must clear old terms and not inflate total_documents.""" import os import sys sys.path.insert(0, os.path.abspath("chapter3/sparse-embedding")) from bm25_engine import InvertedIndex, BM25 # noqa: E402 def test_reindex_maintains_doc_co...
50
1,768
ai-agent-book
tests/test_ch3_hybrid_structured_retriever.py
.py
"""Unit tests for chapter3/structured-index/hybrid_retriever.py (HybridStructuredRetriever).""" import importlib.util import os import sys from pathlib import Path import pytest pytest.importorskip("numpy") import numpy as np # Dynamic import for hyphenated module path _module_path = ( Path(__file__).resolve().p...
385
15,015
ai-agent-book
tests/test_ch1_search_codegen_null_response.py
.py
import importlib.util import os import sys from pathlib import Path import pytest from unittest.mock import MagicMock _module_path = ( Path(__file__).resolve().parent.parent / "chapter1" / "search-codegen" / "agent.py" ) _spec = importlib.util.spec_from_file_location("search_codegen_agent", _module_path) _module =...
49
1,792
ai-agent-book
tests/test_ch10_bilingual_consistency_auditor.py
.py
"""Unit tests for chapter10/book-translation/consistency_auditor.py.""" from pathlib import Path import sys # Ensure chapter10/book-translation is in sys.path ch10_dir = (Path(__file__).resolve().parent.parent / "chapter10" / "book-translation").resolve() if str(ch10_dir) not in sys.path: sys.path.insert(0, str(c...
299
11,889
ai-agent-book
tests/test_ch8_verifier_string_expression_issues.py
.py
import sys import os sys.path.insert(0, os.path.abspath("chapter8/trajectory-verifier")) from verifier import HeuristicQualityJudge, FAIL def test_heuristic_quality_judge_string_expression_issues(): """Contract: HeuristicQualityJudge supports string items in quality_facts.expression_issues without throwing Attr...
34
1,019
ai-agent-book
tests/test_docs_experiment_status_links.py
.py
"""Regression tests for docs/EXPERIMENT_STATUS.md ledger links. Closes the class where ledger bullet-list entries used literal ``+- `` prefixes that render as text instead of Markdown list items, and where linked ledger files could drift out of existence. """ from __future__ import annotations import re from pathlib...
35
1,310
ai-agent-book
tests/test_gen_star_history_iso_formats.py
.py
import sys from datetime import datetime, timezone from pathlib import Path import pytest pytest.importorskip("matplotlib") sys.path.insert(0, str(Path(__file__).parent.parent / "scripts")) from gen_star_history import build_series, parse_iso_timestamp def test_parse_iso_timestamp_supports_various_iso_formats(): ...
45
1,348
ai-agent-book
tests/test_ch10_field_spec_validate_none.py
.py
import pytest import sys from pathlib import Path ch10_dir = Path(__file__).resolve().parent.parent / "chapter10" / "autonomous-phone-registration" if str(ch10_dir) not in sys.path: sys.path.insert(0, str(ch10_dir)) from models import FieldSpec def test_validate_none_value_when_required(): field = FieldSpec...
55
1,664
ai-agent-book
tests/test_core_clean_site_links.py
.py
import pytest import tempfile from pathlib import Path from scripts.clean_site_files import rendered_links, linked_json_files, clean def test_rendered_links_extracts_src_and_href_from_all_asset_tags(): html_text = """ <script src="config.json"></script> <link href="style.json" rel="stylesheet"> <iframe src="fram...
67
2,191
ai-agent-book
tests/test_git_revision_dates.py
.py
"""Regression tests for Git dates in the assembled online-reading site.""" import os from pathlib import Path import subprocess import sys from types import SimpleNamespace sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) from site_source_paths import ( # noqa: E402 git_commit_range, ...
184
6,040
ai-agent-book
tests/test_ch9_validate_evidence_none_case.py
.py
import pytest import json import sys from pathlib import Path ch9_e2e = Path(__file__).resolve().parent.parent / "chapter9" / "end-to-end-speech" if str(ch9_e2e) not in sys.path: sys.path.insert(0, str(ch9_e2e)) from validate_evidence import validate def test_validate_handles_none_case_arms(tmp_path): evide...
22
626
ai-agent-book
tests/test_ch6_bradley_terry_single_model.py
.py
import pytest pytest.importorskip("pandas") 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: sys.path.insert(0, str(ELO_DIR)) from bradley_terry import compute_mle_elo # noqa: E4...
56
1,657
ai-agent-book
tests/test_ch8_assistant_text_null_content.py
.py
import pytest import sys import os sys.path.insert(0, os.path.abspath("chapter8/trajectory-verifier")) from verifier import _assistant_text, ProcessVerifier, PASS def test_assistant_text_handles_null_content(): """Contract: _assistant_text does not output literal 'None' for assistant tool-call messages with con...
33
1,055
ai-agent-book
tests/test_ch5_sandbox_evaluator.py
.py
"""Unit tests for chapter5/coding-agent/sandbox_evaluator.py. Covers the static risk analysis, risk classification, sandbox configuration checking, dimension scoring, batch evaluation, and recommendation generation of ``CodeSandboxEvaluator``. No code is executed by the evaluator, so these tests are deterministic and ...
397
16,190
ai-agent-book
tests/test_mkdocs_pandoc_strip_null.py
.py
import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) from mkdocs_pandoc_strip import on_page_markdown def test_mkdocs_pandoc_strip_none_input(): """Prove that on_page_markdown handles None input without raising TypeError.""" result = on_page_markdown(N...
19
535
ai-agent-book
tests/test_ch3_retrieval_stage_evaluator.py
.py
"""Unit tests for chapter3/retrieval-pipeline/stage_evaluator.py. Covers the atomic metric primitives (precision@k, recall@k, NDCG@k, MRR), single-stage evaluation, multi-stage pipeline evaluation, marginal improvement, diminishing-returns detection, best-combination selection, and the boundary / edge cases (empty res...
431
18,489
ai-agent-book
tests/test_ch5_grep_tool_file_filters.py
.py
import sys from pathlib import Path import pytest 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.grep_tool import GrepTool # noqa: E402 from system_state import SystemState # noqa: E402...
82
2,408
ai-agent-book
tests/test_ch4_chess_game_over_status.py
.py
import pytest pytest.importorskip("chess") """ Regression test suite for chess get_game_status covering rule-based draws, stalemate, insufficient material, checkmate, and game in progress. """ import asyncio import sys from pathlib import Path import chess sys.path.insert( 0, str( Path(__file__).resol...
106
3,040
ai-agent-book
tests/test_build_site_assets.py
.py
from pathlib import Path import subprocess def run_cleanup(site: Path) -> None: helper = Path(__file__).parents[1] / "scripts" / "clean_site_files.py" subprocess.run(["python3", str(helper), str(site)], check=True) def test_cleanup_preserves_rendered_json_links_only(tmp_path): site = tmp_path / "site" ...
68
2,019
ai-agent-book
tests/test_ch8_verifier_diagnostic_utility.py
.py
import pytest import os import sys sys.path.insert(0, os.path.abspath("chapter8/trajectory-verifier")) from verifier import DimensionResult, FAIL, PASS, diagnostic_utility def test_diagnostic_utility_with_dimension_result_objects(): dim1 = DimensionResult( dimension="task_resolution", layer="env...
78
2,241
ai-agent-book
tests/test_ch8_trajectory_consistency_checker.py
.py
import os import sys sys.path.insert(0, os.path.abspath("chapter8/trajectory-verifier")) import pytest from consistency_checker import ( ConsistencyReport, ConsistencyViolation, TrajectoryConsistencyChecker, VIOLATION_CONTRADICTION, VIOLATION_HALLUCINATED, VIOLATION_UNGROUNDED, VIOLATION_...
406
15,600