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
chapter1/learning-from-experience/tests/test_zero_episodes.py
.py
#!/usr/bin/env python3 """Regression tests for zero-episode division guards. Bug: train()/evaluate() divided victory counts by episode counts, so num_episodes=0 (accepted by experiment.py's argparse) crashed with ZeroDivisionError. Fixed by guarding the divisions and rejecting episode counts < 1 in experiment.py's fro...
44
1,545
ai-agent-book
chapter1/learning-from-experience/tests/test_basic.py
.py
#!/usr/bin/env python3 """ Basic test to verify all components work correctly. """ import sys from pathlib import Path PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) def test_game_environment(): """Test that the game environment...
168
4,862
ai-agent-book
chapter1/learning-from-experience/tests/test_rl_progress_small_episodes.py
.py
"""Regression: progress prints must not ZeroDivisionError when episodes < 10.""" def test_progress_every_never_zero(): for num_episodes in (1, 5, 9, 10, 100): progress_every = max(1, num_episodes // 10) assert progress_every >= 1 # modulo must be defined for episode in range(num_ep...
17
587
ai-agent-book
chapter1/learning-from-experience/tests/manual/rl_learning_check.py
.py
#!/usr/bin/env python3 """ Manual check to verify Q-learning can learn the simplified game. """ import sys import argparse from pathlib import Path import numpy as np PROJECT_ROOT = Path(__file__).resolve().parents[2] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) from game_environme...
183
6,260
ai-agent-book
chapter1/context/create_sample_pdf.py
.py
""" Create Sample PDF for Testing Generates a financial report PDF with various currency amounts and calculations """ from reportlab.lib import colors from reportlab.lib.pagesizes import letter, A4 from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, PageBreak from reportlab.lib.styl...
275
10,567
ai-agent-book
chapter1/context/main.py
.py
""" Main entry point for Context-Aware Agent """ import os import sys import argparse import logging from agent import ContextAwareAgent, ContextMode from config import PROVIDERS, SUPPORTED_PROVIDERS, canonical_provider, resolve_backend import json from pathlib import Path import subprocess import time from typing imp...
1,229
51,297
ai-agent-book
chapter1/context/test_main_result_semantics.py
.py
from main import _completed def test_completed_field_is_authoritative_over_legacy_success_alias(): assert _completed({"completed": False, "success": True}) is False assert _completed({"completed": True, "success": False}) is True def test_completed_falls_back_for_old_result_artifacts(): assert _complete...
12
400
ai-agent-book
chapter1/context/run_experiment_1_1.py
.py
#!/usr/bin/env python3 """Run the exact five-arm context ablation from book/chapter1.md. Unlike the legacy demo table, this runner persists every credential-free API request and response. That makes it possible to prove which context component was removed on every inference instead of inferring the ablation from a CL...
464
17,119
ai-agent-book
chapter1/context/test_experiment_1_1.py
.py
from agent import AgentTrajectory, ContextMode from run_experiment_1_1 import ( canonical_answer_correct, evaluate_context_contract, summarize_arm, ) def turn(messages, *, tools=True, reasoning="reason"): request = {"messages": messages} if tools: request.update({"tools": [{"type": "functi...
126
4,423
ai-agent-book
chapter1/context/config.py
.py
""" Configuration module for Context-Aware Agent """ import os from typing import Optional from dotenv import load_dotenv # Load environment variables load_dotenv() def _reasoning_safe_temperature(model, requested=1.0): """Reasoning models (Kimi K3, GPT-5, ...) only accept temperature=1. Return 1 for those;...
219
7,174
ai-agent-book
chapter1/context/agent.py
.py
""" Context-Aware AI Agent with Tool Calls An agent using Qwen model from SiliconFlow with document parsing, currency conversion, and calculator tools. Designed to demonstrate the importance of context through ablation studies. """ import json import logging from typing import List, Dict, Any, Optional from dataclasse...
967
40,573
ai-agent-book
chapter1/context/tests/test_malformed_tool_json.py
.py
"""Regression: malformed tool-argument JSON must not abort the ReAct loop.""" from types import SimpleNamespace from unittest.mock import MagicMock from agent import ContextAwareAgent, ContextMode def _choice(*, content=None, tool_calls=None): msg = SimpleNamespace( content=content, tool_calls=to...
75
2,669
ai-agent-book
chapter1/context/tests/test_agent.py
.py
#!/usr/bin/env python3 """ Test script for Context-Aware Agent Validates installation and basic functionality """ import sys from agent import ContextAwareAgent, ContextMode, ToolRegistry import unittest from unittest.mock import MagicMock, patch class TestToolRegistry(unittest.TestCase): """Test the tool regist...
306
10,842
ai-agent-book
chapter1/context/tests/test_code_interpreter.py
.py
#!/usr/bin/env python3 """ Test the code_interpreter tool with the agent """ import os from agent import ContextAwareAgent, ContextMode def test_code_interpreter(): """Test code interpreter integration""" print("\n" + "="*60) print("🧪 CODE INTERPRETER TEST") print("="*60) # Check API ke...
126
3,592
ai-agent-book
chapter1/context/tests/conftest.py
.py
"""Pytest bootstrap for the context experiment tests.""" from pathlib import Path import sys PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
10
227
ai-agent-book
chapter1/context/tests/manual/quickstart.py
.py
#!/usr/bin/env python3 """ Quick Start Script for Context-Aware Agent Run this to test the agent with a simple example """ import os import sys from _bootstrap import add_project_root add_project_root() from agent import ContextAwareAgent, ContextMode from config import Config def main(): """Quick start demons...
115
3,910
ai-agent-book
chapter1/context/tests/manual/check_deepseek.py
.py
#!/usr/bin/env python3 """ Test script for DeepSeek model integration. Tests deepseek-v4-flash (default) with conversation and tool calling. """ import os import sys from _bootstrap import add_project_root add_project_root() from dotenv import load_dotenv from agent import ContextAwareAgent, ContextMode from config...
227
6,673
ai-agent-book
chapter1/context/tests/manual/check_deepseek_quick.py
.py
#!/usr/bin/env python3 """ Quick smoke test for DeepSeek provider (deepseek-v4-flash). """ import os import sys import time from _bootstrap import add_project_root add_project_root() from dotenv import load_dotenv load_dotenv() task = "What is 10 + 5? Provide FINAL ANSWER with just the number." print("=" * 60) p...
67
1,656
ai-agent-book
chapter1/context/tests/manual/check_doubao_quick.py
.py
#!/usr/bin/env python3 """ Quick test with Doubao as default """ import os import sys import time from _bootstrap import add_project_root add_project_root() # Set a very simple task to test quickly task = "What is 10 + 5? Provide FINAL ANSWER with just the number." print("="*60) print("QUICK TEST - Doubao Default ...
61
1,454
ai-agent-book
chapter1/context/tests/manual/check_provider_switching.py
.py
#!/usr/bin/env python3 """ Test script to verify provider switching functionality """ import os from _bootstrap import add_project_root add_project_root() from dotenv import load_dotenv from agent import ContextAwareAgent, ContextMode from config import Config # Load environment variables load_dotenv() def test_p...
118
3,939
ai-agent-book
chapter1/context/tests/manual/check_doubao.py
.py
#!/usr/bin/env python3 """ Quick test for Doubao provider """ import os from _bootstrap import add_project_root add_project_root() from agent import ContextAwareAgent, ContextMode def test_doubao(): """Test Doubao provider with a simple task""" print("\n" + "="*60) print("🧪 DOUBAO PROVIDER TEST")...
65
1,985
ai-agent-book
chapter1/context/tests/manual/check_conversation_history.py
.py
#!/usr/bin/env python3 """ Test script to verify conversation history persistence """ import os from _bootstrap import add_project_root add_project_root() from dotenv import load_dotenv from agent import ContextAwareAgent, ContextMode import json # Load environment variables load_dotenv() def test_conversation_hi...
138
5,139
ai-agent-book
chapter1/context/tests/manual/check_kimi.py
.py
#!/usr/bin/env python3 """ Test script for Kimi K3 model integration Tests the Kimi K3 model (kimi-k3) with various tasks """ import os import sys from _bootstrap import add_project_root add_project_root() from dotenv import load_dotenv from agent import ContextAwareAgent, ContextMode from config import Config # L...
250
7,234
ai-agent-book
chapter1/context/tests/manual/demo_conversation.py
.py
#!/usr/bin/env python3 """ Demo script showing conversation history persistence """ import os from _bootstrap import add_project_root add_project_root() from dotenv import load_dotenv from agent import ContextAwareAgent, ContextMode # Load environment variables load_dotenv() def main(): # Get API key (use any...
86
2,877
ai-agent-book
chapter1/context/tests/manual/check_pdf_task.py
.py
#!/usr/bin/env python3 """ Test script to verify PDF parsing and currency conversion """ import os import sys from _bootstrap import add_project_root add_project_root() from agent import ContextAwareAgent, ContextMode def test_pdf_with_currencies(): """Test PDF parsing with currency conversion""" prin...
102
3,378
ai-agent-book
chapter1/context/tests/manual/check_default_provider.py
.py
#!/usr/bin/env python3 """ Test that Doubao is the default provider """ import os import sys from _bootstrap import add_project_root add_project_root() # Test without any arguments - should use Doubao print("Testing default provider...") # Check if ARK_API_KEY is available ark_key = os.getenv("ARK_API_KEY") sf_key...
46
1,350
ai-agent-book
chapter1/context/tests/manual/check_provider_config.py
.py
#!/usr/bin/env python3 """ Test script to verify provider configuration """ import os from _bootstrap import add_project_root add_project_root() from agent import ContextAwareAgent, ContextMode def test_providers(): """Test different provider configurations""" print("\n" + "="*60) print("🧪 PROVID...
130
4,535
ai-agent-book
chapter1/context/tests/manual/check_kimi_quick.py
.py
#!/usr/bin/env python3 """ Quick test script to verify Kimi K3 model integration """ import os from _bootstrap import add_project_root add_project_root() from dotenv import load_dotenv from agent import ContextAwareAgent, ContextMode # Load environment variables load_dotenv() def main(): # Get API key api...
58
1,461
ai-agent-book
chapter1/context/tests/manual/_bootstrap.py
.py
"""Helpers for running manual smoke scripts from tests/manual.""" from pathlib import Path import sys def add_project_root() -> Path: project_root = Path(__file__).resolve().parents[2] if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) return project_root
12
304
ai-agent-book
chapter1/context/tests/manual/show_sample_tasks.py
.py
#!/usr/bin/env python3 """ Demo script to showcase sample tasks with PDF functionality """ import os import sys from pathlib import Path from _bootstrap import add_project_root add_project_root() from main import get_sample_tasks, ensure_sample_pdfs def main(): """Demo the sample tasks""" print("\n" + "="*...
87
2,712
ai-agent-book
chapter1/context/tests/manual/check_simple_task.py
.py
#!/usr/bin/env python3 """ Test with a simpler task to diagnose the issue """ import os import sys import time from _bootstrap import add_project_root add_project_root() from agent import ContextAwareAgent, ContextMode def test_simple_task(): """Test with a very simple task to check if the agent is working""" ...
88
2,575
ai-agent-book
chapter1/web-search-agent/quickstart.py
.py
#!/usr/bin/env python3 """ 快速开始脚本 - 一键体验 Kimi Web Search Agent """ import os import sys from agent import WebSearchAgent from config import Config # 彩色输出 class Colors: HEADER = '\033[95m' BLUE = '\033[94m' CYAN = '\033[96m' GREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' END = '\...
197
6,176
ai-agent-book
chapter1/web-search-agent/main.py
.py
""" 主程序 - Web Search Agent 使用示例 演示第一章的 ReAct 循环(Reasoning + Acting):模型先思考,再调用 web_search 行动,观察搜索结果后继续思考,直到综合出最终答案。运行时会逐步打印 ReAct 轨迹。 """ import os import sys import json import argparse import logging from typing import Optional from agent import WebSearchAgent, run_offline_demo from config import Config # 设置日志 logg...
223
8,593
ai-agent-book
chapter1/web-search-agent/run_experiment_1_2.py
.py
#!/usr/bin/env python3 """Run Experiment 1-2 through Kimi K3's official Formula web-search tool.""" from __future__ import annotations import argparse import hashlib import json import os import platform import shutil import subprocess import sys import time from datetime import datetime, timezone from pathlib import...
282
10,982
ai-agent-book
chapter1/web-search-agent/examples.py
.py
""" 高级示例 - 展示 Web Search Agent 的各种用法 """ import asyncio import json from typing import List, Dict, Any from agent import WebSearchAgent, is_failure_answer from config import Config import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class AdvancedWebSearchAgent(WebSearchAgent...
325
10,130
ai-agent-book
chapter1/web-search-agent/config.py
.py
""" 配置文件 - Kimi API 配置 """ import os from typing import Optional from dotenv import load_dotenv load_dotenv() from dotenv import load_dotenv # Read the nearest .env, searching upward from the working directory, so a # single file at the repository root serves every chapter. load_dotenv() # Provider resolution liv...
93
2,698
ai-agent-book
chapter1/web-search-agent/agent.py
.py
""" Kimi Web Search Agent 一个基于 Kimi API 的智能搜索 Agent,能够理解用户问题,通过搜索引擎获取信息,并总结出答案。 """ import json from typing import List, Dict, Any, Optional from openai import OpenAI from openai.types.chat.chat_completion import Choice import logging import os import requests import time # 设置日志 logging.basicConfig(level=logging.INFO...
599
26,362
ai-agent-book
chapter1/web-search-agent/tests/test_config.py
.py
"""Unit tests for model mapping and provider selection.""" import pytest from config import map_model_to_openrouter, resolve_llm_backend @pytest.mark.parametrize( ("model", "expected"), [ ("openai/gpt-5.6-luna", "openai/gpt-5.6-luna"), ("gpt-5.6-luna", "openai/gpt-5.6-luna"), ("o3-min...
79
2,564
ai-agent-book
chapter1/web-search-agent/tests/test_examples.py
.py
"""Unit tests for AdvancedWebSearchAgent helpers and failure classification.""" from unittest.mock import Mock from agent import ( MAX_ITERATIONS_MESSAGE, NO_INFO_MESSAGE, SEARCH_ERROR_PREFIX, is_failure_answer, ) from examples import AdvancedWebSearchAgent def build_advanced(answers): """Advanc...
44
1,494
ai-agent-book
chapter1/web-search-agent/tests/test_experiment_1_2.py
.py
from run_experiment_1_2 import fiber_ids, validate def formula_tool(): return { "type": "function", "function": { "name": "web_search", "description": "Search the web", "parameters": { "type": "object", "properties": {"query": {"t...
186
6,008
ai-agent-book
chapter1/web-search-agent/tests/test_agent.py
.py
"""Unit tests for ReAct formatting, tools, and the agent loop.""" from unittest.mock import Mock from agent import WebSearchAgent, _reasoning_safe_temperature, format_trace_step class FakeResponse: def __init__(self, payload, status_code=200): self._payload = payload self.status_code = status_co...
285
9,591
ai-agent-book
chapter1/web-search-agent/tests/test_offline_demo.py
.py
"""Tests for the deterministic offline ReAct demonstration.""" from agent import run_offline_demo def test_offline_demo_returns_a_complete_deterministic_trace(): result = run_offline_demo("캐싱이 뭐야?", verbose=False) assert result["question"] == "캐싱이 뭐야?" assert [step["type"] for step in result["trace"]] =...
38
1,099
ai-agent-book
chapter1/web-search-agent/tests/test_main.py
.py
"""Tests for CLI parsing, offline dispatch, and JSON output.""" import json import main as cli from config import Config def test_parser_defaults_to_interactive_kimi_mode(): args = cli.build_parser().parse_args([]) assert args.query == [] assert args.provider == "kimi" assert args.model == Config.D...
82
2,332
ai-agent-book
chapter1/web-search-agent/tests/conftest.py
.py
"""Shared pytest fixtures for the web search agent test suite.""" import json import socket from types import SimpleNamespace import pytest PROVIDER_ENV_VARS = ( "MOONSHOT_API_KEY", "KIMI_API_KEY", "OPENROUTER_API_KEY", "OPENROUTER_BASE_URL", "OPENROUTER_MODEL", ) @pytest.fixture(autouse=True) ...
81
2,166
ai-agent-book
chapter1/search-codegen/quickstart.py
.py
#!/usr/bin/env python3 """ Quick Start Demo for GPT-5 Native Tools Agent Demonstrates basic usage of web_search and code_interpreter tools """ import os import sys from agent import GPT5NativeAgent from config import Config def demo_web_search(): """Demonstrate web search capability""" print("\n" + "="*60) ...
162
4,830
ai-agent-book
chapter1/search-codegen/main.py
.py
""" Main entry point for GPT-5 Native Tools Agent Interactive CLI for using web_search and code_interpreter tools """ import sys import json import logging from typing import Optional from agent import GPT5NativeAgent, GPT5AgentChain from config import Config import argparse # Set up logging logging.basicConfig( ...
445
15,959
ai-agent-book
chapter1/search-codegen/example_request.py
.py
#!/usr/bin/env python3 """ Example showing the exact OpenRouter GPT-5 request format matching the Go implementation """ import json import requests import os from typing import Dict, Any try: from dotenv import load_dotenv load_dotenv() except ImportError: pass def make_gpt5_openrouter_request( api_k...
250
7,659
ai-agent-book
chapter1/search-codegen/run_experiment_1_3.py
.py
#!/usr/bin/env python3 """Run Experiment 1-3 on a hosted web-search + code-execution Responses API. Acceptance policy (author-mandated, 2026-07-31): the experiment's essence is model-directed multi-round web search + hosted code execution, clarification before tools, and a current answer with authoritative sources. Th...
448
16,885
ai-agent-book
chapter1/search-codegen/test_responses_agent.py
.py
from agent import GPT5NativeAgent from config import Config from run_experiment_1_3 import ( acceptance, independent_asean_reference, validate_asean, validate_clarification, ) DASHSCOPE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1" def test_request_uses_official_responses_tool_shapes...
193
7,098
ai-agent-book
chapter1/search-codegen/config.py
.py
"""Configuration for the exact GPT-5.6 Responses API companion.""" import os from typing import Optional, Tuple from dotenv import load_dotenv load_dotenv() def _optional_int_env(name: str) -> Optional[int]: """Read an optional integer without making module import configuration-fatal.""" raw_value = os.get...
87
3,400
ai-agent-book
chapter1/search-codegen/test_config_and_usage.py
.py
import os from pathlib import Path import subprocess import sys import example_request ROOT = Path(__file__).parent def _import_config_with(value: str | None) -> subprocess.CompletedProcess[str]: env = os.environ.copy() if value is None: env.pop("DEFAULT_MAX_TOKENS", None) else: env["DE...
90
2,520
ai-agent-book
chapter1/search-codegen/agent.py
.py
"""Exact GPT-5.6 Responses API agent for Experiment 1-3. The previous companion sent Responses-style hosted tools to Chat Completions through a proxy and then reported an empty ``tool_calls`` list. This module uses the actual ``/v1/responses`` protocol and preserves its typed output items (``web_search_call``, ``code...
397
16,312
ai-agent-book
chapter1/search-codegen/tests/manual/agent_cases.py
.py
""" Live manual cases for GPT-5 Native Tools Agent. These cases demonstrate web_search with the OpenRouter format and require OPENROUTER_API_KEY. """ import json import logging import sys from typing import Dict, Any, List from datetime import datetime from pathlib import Path PROJECT_ROOT = Path(__file__).resolve()...
364
11,743
ai-agent-book
book-ar/svg_lib.py
.py
"""SVG diagram generation library for book illustrations. Style: black/white/grayscale for B&W printing. - White (#fff) backgrounds - Light gray (#f0f0f0) box fills - Medium gray (#d0d0d0) secondary fills - Dark gray (#999) emphasis fills - Black (#333) borders and text - 2px stroke, 6px rounded corners - Sans-serif f...
693
27,564
ai-agent-book
book-ar/test_svg_lib.py
.py
import unittest from svg_lib import _char_w, _text_width, _wrap_line class ArabicTextWidthTests(unittest.TestCase): def test_combining_marks_have_zero_width(self): self.assertEqual(_char_w('\u064e'), 0) # Fatha self.assertEqual(_char_w('\u0651'), 0) # Shadda def test_harakat_do_not_force_a...
23
692
ai-agent-book
book-zhtw/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_t...
112
3,577
ai-agent-book
book-zhtw/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
chapter8/speech-sft-experiment/run_orpheus.py
.py
#!/usr/bin/env python3 """Run the Orpheus half of Experiment 7-6 on one local CUDA GPU. The campaign deliberately keeps a held-out split and emits base/adapted audio for identical prompts and seeds. It is bounded for a workstation, but it is not a one-batch smoke test: the default run encodes 144 real utterances and ...
309
12,098
ai-agent-book
chapter8/speech-sft-experiment/test_experiment.py
.py
import importlib.util from pathlib import Path import torch HERE = Path(__file__).parent def load(name): spec = importlib.util.spec_from_file_location(name, HERE / f"{name}.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def test_sesame_tag_catego...
50
1,638
ai-agent-book
chapter8/speech-sft-experiment/analyze_campaign.py
.py
#!/usr/bin/env python3 """Build the strict, hash-verified acceptance package for Experiment 7-6.""" from __future__ import annotations import argparse import hashlib import itertools import json from pathlib import Path import librosa import numpy as np import soundfile as sf import torch from huggingface_hub import...
290
14,968
ai-agent-book
chapter8/speech-sft-experiment/run_sesame.py
.py
#!/usr/bin/env python3 """Run the Sesame CSM paralinguistic-tag half of Experiment 7-6.""" from __future__ import annotations import argparse import hashlib import json import os import random import re import shutil import tempfile import time from pathlib import Path import numpy as np import soundfile as sf impor...
315
13,148
ai-agent-book
chapter8/continued-pretraining/continued-pretrain.py
.py
# -*- coding: utf-8 -*- """Continued pretraining - Korean + Unsloth.ipynb Automatically generated by Colab. Original file is located at https://colab.research.google.com/drive/1tEd1FrOXWMnCU9UIvdYhs61tkxdMuKZu To run this, press "*Runtime*" and press "*Run all*" on a **free** Tesla T4 Google Colab instance! <div...
646
30,047
ai-agent-book
chapter8/continued-pretraining/evaluate_model.py
.py
# -*- coding: utf-8 -*- """ Evaluation script for Korean Mistral continued-pretrained models Loads saved LoRA adapters and evaluates on Korean and English tasks """ import os import argparse # 说明:unsloth / torch / transformers 等重型依赖在函数内按需导入, # 这样 `python evaluate_model.py --help` 无需 GPU 环境即可查看参数。 # ANSI color codes ...
286
10,402
ai-agent-book
chapter8/continued-pretraining/compare_models.py
.py
# -*- coding: utf-8 -*- """ Compare baseline → pretrained → finetuned Korean Mistral models (3-way comparison) Shows progression from original model to final Korean-capable model """ import argparse # 说明:unsloth / torch 等重型依赖在函数内按需导入, # 这样 `python compare_models.py --help` 无需 GPU 环境即可查看参数。 # ANSI color codes for col...
297
13,980
ai-agent-book
chapter8/continued-pretraining/validation/validate_evidence.py
.py
#!/usr/bin/env python3 """Fail-closed validator for the canonical Experiment 7-5 report evidence.""" from __future__ import annotations import argparse import hashlib import json import re from pathlib import Path from typing import Any HERE = Path(__file__).resolve().parent EXPERIMENT_DIR = HERE.parent REPO_ROOT =...
213
9,947
ai-agent-book
chapter8/continued-pretraining/validation/test_report_audit.py
.py
from __future__ import annotations import importlib.util import json from pathlib import Path HERE = Path(__file__).resolve().parent def load_module(name: str, path: Path): spec = importlib.util.spec_from_file_location(name, path) assert spec and spec.loader module = importlib.util.module_from_spec(spe...
55
1,985
ai-agent-book
chapter8/continued-pretraining/validation/run_report_audit.py
.py
#!/usr/bin/env python3 """Build the canonical, checkpoint-free evidence package for Experiment 7-5. The historical RTX 4090 run is retained as a raw terminal transcript in ``model_eval_results.md``. This tool does not pretend to rerun that GPU job. It extracts the fifteen saved generations, submits five stage-blind c...
781
30,897
ai-agent-book
chapter8/premature-completion-dpo/train_dpo.py
.py
"""DPO 训练脚本(实验 7-17 主线,需要单卡 GPU)。 默认配置面向单卡:bf16、gradient checkpointing、LoRA r=16 alpha=32、 per_device_batch_size=1、gradient_accumulation 2、learning_rate 3e-5、 beta 0.1、4 epochs。小数据集使用较小的累积步数,确保确实有足够的更新步;可用 `--epochs`、`--gradient-accumulation` 和 `--learning-rate` 覆盖。训练产物:output/adapter/(仅 LoRA adapter), 训练回执 validation...
174
6,919
ai-agent-book
chapter8/premature-completion-dpo/llm_client.py
.py
"""OpenAI 兼容 API 客户端与证据回执工具(真实 LLM 路径专用)。 约定与 chapter8/self-modifying-agent/llm_generator.py 一致: 原始请求、原始响应、token 用量、延迟、请求/响应哈希都进入证据回执; validation/<run>/evidence.json 保存完整证据,validation/latest.json 指向最近一次。 """ from __future__ import annotations import hashlib import json import os import time from pathlib import Path ...
100
3,901
ai-agent-book
chapter8/premature-completion-dpo/test_pipeline.py
.py
"""实验 7-17 的离线单元测试(pytest,不依赖 API key 与 GPU)。 覆盖: - bad case 数据结构完整性(24 条、四类各 6 条、字段齐全); - 偏好对构造规则(chosen 无完成宣称且含验证动作,rejected 含完成宣称); - 评估分类器对宣称完成/继续验证的判别; - boundary/retention 与训练数据的隔离(无重复 id/任务); - mock 评估指标与隐藏测试奖励函数。 """ from __future__ import annotations import json from pathlib import Path import pytest from...
201
7,328
ai-agent-book
chapter8/premature-completion-dpo/evaluate.py
.py
"""评估脚本:对比 base 与 base+adapter 在边界集/保留集上的"下一步动作"行为。 指标口径: - boundary 过早宣称率:任务未真正完成时仍宣称完成的比例(训练后应下降); - retention 正常收尾率:任务确实完成时正常宣称完成的比例(训练后应保持); - 过度矫正率 = 1 - retention 正常收尾率(模型被训得永远不敢收尾的程度)。 判定使用确定性分类器(关键词/模式),不依赖 LLM;可选 --judge 用 LLM 复核并留证据回执。 --mock 模式不加载模型,用预置样例输出演示评估逻辑,离线可跑。 """ from __future__ import annotatio...
352
15,385
ai-agent-book
chapter8/premature-completion-dpo/demo.py
.py
"""离线端到端教学演示(实验 7-17)。 不依赖 API key、不依赖 GPU,演示完整链路: 1. 从过早结束 bad case 构造 DPO 偏好对(离线确定性路径); 2. 展示 2 条样例偏好对; 3. 用 --mock 评估演示指标计算(base vs adapter 的预置样例输出); 4. 打印全流程摘要与真实训练所需的后续步骤。 """ from __future__ import annotations import json from build_preference_data import build_pairs, load_bad_cases from evaluate import compu...
64
2,960
ai-agent-book
chapter8/premature-completion-dpo/train_grpo_optional.py
.py
"""可选 RL 分支:GRPO + 隐藏验收测试作为奖励(实验 7-17 可选路径,主线是 DPO)。 奖励函数 = 隐藏验收测试:对每个端到端任务,模型输出若宣称完成,则在隔离的 临时目录里还原工作区并运行该任务附带的隐藏检查脚本: - 宣称完成且隐藏测试通过:+1 - 宣称完成但测试不过:-1 - 未宣称完成但执行了验证动作:+0.3 - 其它:0 隐藏测试定义在 data/hidden_tests.json。脚本真实可运行,但属于可选分支: 正文以 DPO 为主线,GRPO 路径需要 GPU 且训练成本更高。 """ from __future__ import annotations import argparse...
131
4,684
ai-agent-book
chapter8/premature-completion-dpo/build_preference_data.py
.py
"""从过早结束 bad case 构造 DPO 偏好对。 两条 chosen 生成路径: 1. 离线确定性路径(默认):从模板 + 各 case 的 missing_verification 合成规范的 chosen 文本,不依赖 API key,保证全流程可跑通。 2. 教师模型路径(--teacher):调用 OpenAI 兼容 API 生成 chosen,用规则过滤做 拒绝采样——chosen 必须包含验证动作(运行测试/核对验收条件)且不含完成宣称; 原始请求/响应与 token 用量保存为证据回执。 输出 DPO 格式的 output/preference_pairs.jsonl,每行含 promp...
190
8,009
ai-agent-book
chapter8/sesame/inference.py
.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Sesame CSM (1B) TTS - Inference Script This script loads a trained LoRA model and generates speech from text. """ import argparse import torch import soundfile as sf from pathlib import Path from datasets import load_dataset, Audio from unsloth import FastModel from ...
231
6,813
ai-agent-book
chapter8/sesame/test_batch_inference.py
.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Regression tests for batch_inference.py JSON input handling: - Items missing the required "text" field must raise a clear ValueError (previously a bare KeyError: 'text' aborted the whole batch). - An explicit JSON null "output" must fall back to the default filename...
86
2,987
ai-agent-book
chapter8/sesame/sesame_csm_sft_unsloth.py
.py
# -*- coding: utf-8 -*- """Sesame_CSM_(1B)-TTS.ipynb Automatically generated by Colab. Original file is located at https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Sesame_CSM_(1B)-TTS.ipynb To run this, press "*Runtime*" and press "*Run all*" on a **free** Tesla T4 Google Colab instance!...
415
17,435
ai-agent-book
chapter8/sesame/batch_inference.py
.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Sesame CSM (1B) TTS - Batch Inference Script This script loads a trained LoRA model and generates speech from multiple texts. """ import argparse import json import torch import soundfile as sf from pathlib import Path from typing import List, Dict from tqdm import t...
239
7,430
ai-agent-book
chapter8/curly-quote-sft/quality_audit.py
.py
"""Deterministic quality gate for the scope-sensitive synthetic corpus. This is the machine-checkable part of the manual audit: a reviewer samples rows from each language/type stratum, while this gate rejects malformed or ambiguous targets before they reach SFT. """ from __future__ import annotations import json, re ...
68
2,616
ai-agent-book
chapter8/curly-quote-sft/evaluate.py
.py
from __future__ import annotations import argparse, hashlib, json, re from pathlib import Path import torch from peft import PeftModel from transformers import AutoModelForCausalLM, AutoTokenizer ROOT = Path(__file__).resolve().parent def rows(path): return [json.loads(x) for x in Path(path).read_text(encoding="utf-8"...
45
3,636
ai-agent-book
chapter8/curly-quote-sft/generate_data.py
.py
from __future__ import annotations import hashlib import json from pathlib import Path ROOT = Path(__file__).resolve().parent DATA = ROOT / "data" VERSIONS = ["v2", "v2.1", "v3", "v4-beta", "2026.08", "release-候选"] ACTIONS = ["先运行测试", "先备份数据", "检查权限", "重新读取文件", "核对验收条件", "查看变更记录"] STATUSES = ["ok", "ready", "pending...
150
8,626
ai-agent-book
chapter8/curly-quote-sft/train_sft.py
.py
from __future__ import annotations import argparse import hashlib import json from datetime import datetime, timezone from pathlib import Path import torch from peft import LoraConfig, get_peft_model from transformers import AutoModelForCausalLM, AutoTokenizer ROOT = Path(__file__).resolve().parent def load_rows(p...
94
5,199
ai-agent-book
chapter8/curly-quote-sft/tests/test_curly_pipeline.py
.py
import json from pathlib import Path ROOT = Path(__file__).parents[1] def test_splits_are_nonempty_and_structured(): for name in ("train", "eval", "boundary"): rows = [json.loads(x) for x in (ROOT / "data" / f"{name}.jsonl").read_text(encoding="utf-8").splitlines() if x.strip()] assert rows ...
50
2,663
ai-agent-book
chapter8/cot-distillation/test_load_verified_messages_colon.py
.py
"""Regression: load_verified_messages must accept fullwidth colon and case-insensitive Final Answer.""" import json from pathlib import Path from train_student import load_verified_messages def test_load_verified_messages_fullwidth_colon(tmp_path: Path): sample = { "messages": [ {"role": "use...
33
1,154
ai-agent-book
chapter8/cot-distillation/test_analyze_null_assistant_content.py
.py
"""SFT rows with null assistant content must not TypeError in analyze_data.""" import json import sys import analyze_data as ad def test_null_assistant_content_skipped(tmp_path, monkeypatch, capsys): sft = tmp_path / "sft.jsonl" rows = [ { "messages": [ {"role": "user", "...
67
1,846
ai-agent-book
chapter8/cot-distillation/test_student_pipeline.py
.py
import json from evaluate_student import ( BEHAVIORS, behavior_flags, compare_binary, completion_and_findings, exact_two_sided_sign_p_value, ) from train_student import load_verified_messages def test_load_verified_messages_rejects_unverified_shape(tmp_path): path = tmp_path / "bad.jsonl" ...
60
2,153
ai-agent-book
chapter8/cot-distillation/train_student.py
.py
#!/usr/bin/env python3 """Train the Experiment 7-9 student on verified teacher CoT trajectories. This is the parameter-update stage missing from the original collection-only companion. It deliberately has no mock training mode: a successful run writes a real Hugging Face/PEFT checkpoint plus a provenance manifest. ""...
342
14,304
ai-agent-book
chapter8/cot-distillation/evaluate_student.py
.py
#!/usr/bin/env python3 """Baseline/student/teacher acceptance campaign for Experiment 7-9.""" from __future__ import annotations import argparse import hashlib import json import math import re from datetime import datetime, timezone from pathlib import Path from typing import Any from generate_data import ANSWER_SU...
279
11,221
ai-agent-book
chapter8/cot-distillation/test_empty_problems.py
.py
"""Empty problems JSONL must not ZeroDivisionError in the pass-rate summary.""" import asyncio import json import os from types import ModuleType import sys # generate_data imports openai; stub if missing so the test stays offline. try: import openai # noqa: F401 except ImportError: _oai = ModuleType("openai...
119
3,976
ai-agent-book
chapter8/cot-distillation/analyze_data.py
.py
"""统计蒸馏得到的 SFT 数据:规模、token/字符分布、思考链特征。""" import argparse import json import re def main(): parser = argparse.ArgumentParser(description="统计 CoT 蒸馏 SFT 数据") parser.add_argument("--sft", default="./data/sft_cot_distill_aime.jsonl") parser.add_argument("--raw", default="./data/raw_trajectories_aime.jsonl")...
72
2,742
ai-agent-book
chapter8/cot-distillation/generate_data.py
.py
""" CoT 蒸馏数据采集脚本(实验 7-9 配套代码) 方法(对应书中实验 7-9 的三步流程之第一步"采集轨迹"): 1. 从 problems.jsonl 读取带标准答案的数学题(规则可验证的任务分布); 2. 通过 OpenRouter 调用前沿教师模型(默认 Claude),开启 reasoning 获取 完整"思考 + 答案"轨迹(Claude 4 系列返回的是 summarized thinking——由另一个 模型对原始思维链做的高保真摘要,原始思维链只存在于加密的 signature 字段中); 3. 用规则验证器核对最终答案,只把答对的轨迹写成 SFT 训练数据 ("...
321
14,508
ai-agent-book
chapter8/cot-distillation/test_analyze_short_messages.py
.py
"""SFT rows with messages shorter than 2 must not IndexError in analyze_data.""" import json import sys from pathlib import Path import analyze_data as ad def test_short_messages_skipped_without_index_error(tmp_path, monkeypatch, capsys): sft = tmp_path / "sft.jsonl" rows = [ {"messages": [{"role": ...
65
1,884
ai-agent-book
chapter8/cot-distillation/sft_data_auditor.py
.py
""" SFT training-data quality auditor (chapter 7 CoT distillation). Every chapter 7 SFT experiment (7-8, 7-9, 7-17, 7-18, 7-19) consumes JSONL training data: one JSON object per line, each carrying a ``messages`` array of ``{"role", "content"}`` pairs. ``generate_data.py`` synthesizes that data and ``analyze_data.py``...
666
26,998
ai-agent-book
chapter8/orpheus/test_orpheus_inference.py
.py
import importlib.util import sys from pathlib import Path from types import ModuleType from unittest.mock import MagicMock, patch import pytest import torch def _optional_dependency_stubs(): torchaudio = ModuleType("torchaudio") torchaudio.__path__ = [] transforms = ModuleType("torchaudio.transforms") ...
86
2,696
ai-agent-book
chapter8/orpheus/inference.py
.py
#!/usr/bin/env python3 """ Orpheus TTS Inference Script This script provides a standalone inference interface for the Orpheus text-to-speech model. It supports both single-speaker and multi-speaker TTS generation. Usage: python inference.py Or import as a module: from inference import OrpheusInference tt...
385
13,974
ai-agent-book
chapter8/orpheus/orpheus_sft_unsloth.py
.py
# -*- coding: utf-8 -*- """Orpheus_(3B)-TTS.ipynb Automatically generated by Colab. Original file is located at https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Orpheus_(3B)-TTS.ipynb To run this, press "*Runtime*" and press "*Run all*" on a **free** Tesla T4 Google Colab instance! <div ...
510
19,987
ai-agent-book
chapter8/MiniMind-pretrain/validation/run_training_report_audit.py
.py
#!/usr/bin/env python3 """Build checkpoint-free retained training evidence for Experiment 7-3. The book already contains the author's historical six-cell evaluation report: original versus QK-Norm + Muon at pretrain, SFT, and DPO. This program does not pretend to rerun the GPU training job. It extracts every saved g...
761
34,784
ai-agent-book
chapter8/MiniMind-pretrain/validation/validate_evidence.py
.py
#!/usr/bin/env python3 """Fail-closed validator for Experiment 7-3 retained training evidence.""" from __future__ import annotations import argparse import hashlib import json import re from pathlib import Path from typing import Any HERE = Path(__file__).resolve().parent EXPERIMENT_DIR = HERE.parent REPO_ROOT = EX...
314
14,855
ai-agent-book
chapter8/MiniMind-pretrain/validation/validate_vlm_evidence.py
.py
#!/usr/bin/env python3 """Fail-closed validator for the canonical Experiment 7-4 evidence package.""" from __future__ import annotations import argparse import base64 import hashlib import json import re from pathlib import Path from typing import Any import run_vlm_training_report_audit as audit HERE = Path(__file...
360
14,797
ai-agent-book
chapter8/MiniMind-pretrain/validation/run_vlm_training_report_audit.py
.py
#!/usr/bin/env python3 """Build checkpoint-free retained training evidence for Experiment 7-4. The book contains 64 historical MiniMind-V image descriptions: eight model configurations evaluated on the same eight images. This program extracts all of them, asks a real image-capable model to judge every anonymous candi...
923
42,148