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
chapter5/permission-embedded-data-objects/pedo/scenarios/ecommerce.py
.py
"""Case study: E-commerce orders. Architectural pattern demonstrated: **compound state machine + reactions**. An order moves through cart -> placed -> paid -> shipped -> delivered, with refund inverting the state from delivered back to refunded. Each transition has invariants (placed orders cannot be modified; only pa...
153
6,758
ai-agent-book
chapter5/permission-embedded-data-objects/pedo/scenarios/healthcare.py
.py
"""Case study: Healthcare records. Architectural pattern demonstrated: **field-level granular access + audit reactions**. Different roles (doctor, nurse, billing, patient) see different subsets of a patient_record's fields. The schema declares per-field visibility rules; the handler does not implement view-projection ...
148
7,031
ai-agent-book
chapter5/permission-embedded-data-objects/pedo/scenarios/project_mgmt.py
.py
"""Scenario B: Multi-tenant Project Management. Objects: organizations, projects, tasks, comments, attachments Constraints: - Tenant isolation: organizations cannot see each other's data - Hierarchical permissions: project admins manage tasks within their project - Cross-object validation: task assignee must be ...
244
11,176
ai-agent-book
chapter5/permission-embedded-data-objects/pedo/scenarios/hiring.py
.py
"""Scenario A: Hiring Pipeline. Objects: organizations, positions, candidates, interviews, evaluations, audit_logs Constraints: - State machine on candidate status: applied -> screened -> interviewed -> offered -> hired/rejected - Referential integrity between candidates and positions - Cross-object validation: ...
248
11,660
ai-agent-book
chapter5/permission-embedded-data-objects/pedo/core/models.py
.py
"""Core data models for permission-embedded data objects.""" from __future__ import annotations import uuid import time from dataclasses import dataclass, field from enum import Enum from typing import Any, Optional class Operation(Enum): ACCEPT = "ACCEPT" DENY = "DENY" PENDING = "PENDING" class Privil...
132
4,115
ai-agent-book
chapter5/permission-embedded-data-objects/pedo/core/store.py
.py
"""Object store implementing the three-tier operation pipeline. This is the core of the permission-embedded data objects prototype. It sits as middleware on top of PostgreSQL, intercepting every operation and running the full pipeline: permission checks, validators, object store mechanics, and reactions. """ from __f...
720
31,212
ai-agent-book
chapter5/permission-embedded-data-objects/tests/test_core.py
.py
"""Tests for the core object store.""" import pytest from pedo.core.models import ( AccessContext, DataObject, ObjectType, Operation, PermissionRule, PrivilegeType, Relationship, RelationshipAction, ReactionDeclaration, ) from pedo.core.store import ObjectStore, PermissionDeniedError, ValidationError, Refe...
146
4,832
ai-agent-book
chapter5/permission-embedded-data-objects/tests/test_scenarios.py
.py
"""Tests for both application scenarios.""" import pytest import time from pedo.core.models import AccessContext, DataObject, PermissionRule, Operation, PrivilegeType from pedo.core.store import ObjectStore, PermissionDeniedError, ValidationError, ReferentialIntegrityError from pedo.scenarios.hiring import register_hi...
330
11,572
ai-agent-book
chapter5/coding-agent/quickstart.py
.py
#!/usr/bin/env python3 """ Quickstart script for the coding agent """ import os from agent import CodingAgent from config import Config def main(): """Run a simple coding agent interaction""" # Validate configuration try: Config.validate() except ValueError as e: print(f"Configur...
94
2,797
ai-agent-book
chapter5/coding-agent/system_state.py
.py
""" System state tracking for the coding agent """ import os import platform from dataclasses import dataclass, field from typing import Dict, Any, List from datetime import datetime @dataclass class SystemState: """System state tracking for system hints""" current_directory: str = field(default_factory=lamb...
54
2,276
ai-agent-book
chapter5/coding-agent/main.py
.py
#!/usr/bin/env python3 """ Interactive CLI for the Coding Agent Provides a command-line interface for chatting with the agent """ import os import sys from pathlib import Path from agent import CodingAgent from config import Config class Colors: """ANSI color codes for terminal output""" RESET = '\033[0m' ...
503
19,653
ai-agent-book
chapter5/coding-agent/sandbox_evaluator.py
.py
""" Sandbox safety evaluator for agent-generated code. Chapter 5 discusses the tension between giving a coding agent the power to execute code and keeping that execution safe. Experiment 5-12 discussion question #7 names the "deadly triad": private data access, untrusted content exposure, and external communication, c...
330
13,128
ai-agent-book
chapter5/coding-agent/example_complex_task.py
.py
#!/usr/bin/env python3 """ Example of a complex coding task with the agent """ from agent import CodingAgent from config import Config def run_complex_task(): """Run a complex multi-step task""" Config.validate() provider = Config.get_provider() api_key = Config.get_api_key() base_url =...
112
3,652
ai-agent-book
chapter5/coding-agent/example_with_system_hints.py
.py
#!/usr/bin/env python3 """ Example demonstrating system hints features """ from agent import CodingAgent from config import Config def demo_system_hints(): """Demonstrate system hint features like timestamps, tool counting, and TODO tracking""" Config.validate() provider = Config.get_provider()...
135
5,034
ai-agent-book
chapter5/coding-agent/config.py
.py
""" Configuration for the coding agent """ import os from pathlib import Path from dotenv import load_dotenv # Load environment variables load_dotenv() class Config: """Configuration class for the coding agent""" # API Configuration ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY") OPENAI_API_...
175
7,205
ai-agent-book
chapter5/coding-agent/tool_registry.py
.py
""" Tool registry - Maps tool names to implementations """ from typing import Dict, Type from tools import ( BaseTool, BashTool, BashOutputTool, KillBashTool, ReadTool, WriteTool, EditTool, MultiEditTool, GrepTool, GlobTool, LSTool, TodoWriteTool, ExitPlanModeTool, NotebookEditTool, WebFetchTool, W...
49
1,462
ai-agent-book
chapter5/coding-agent/agent_new.py
.py
""" Comprehensive Coding Agent - Modular implementation with pure Python tools All tools implemented without command-line dependencies """ import os import json from typing import List, Dict, Any, Optional, Iterator from pathlib import Path from datetime import datetime import anthropic try: from dotenv import lo...
302
11,888
ai-agent-book
chapter5/coding-agent/agent.py
.py
""" Comprehensive Coding Agent - Modular implementation with pure Python tools All tools implemented without command-line dependencies """ import os import json from typing import List, Dict, Any, Optional, Iterator from pathlib import Path from datetime import datetime import anthropic import openai try: from do...
523
20,213
ai-agent-book
chapter5/coding-agent/hello_world.py
.py
#!/usr/bin/env python3 from typing import Any def greet(name: str) -> str: """Return a friendly greeting for the given name.""" return f"Hello, {name}!" def main() -> None: # Requirement 1: Print "Hello, World!" print("Hello, World!") # Requirement 3: Demonstrate the function print(greet("A...
20
368
ai-agent-book
chapter5/coding-agent/tools/write_tool.py
.py
""" Write tool - File writing with automatic lint checking """ import subprocess from pathlib import Path from typing import Dict, Any, Optional from .base import BaseTool class WriteTool(BaseTool): """Writes files to the local filesystem""" @property def name(self) -> str: return "Write" ...
112
3,820
ai-agent-book
chapter5/coding-agent/tools/exit_plan_mode_tool.py
.py
""" ExitPlanMode tool - Exit plan mode after presenting plan """ from typing import Dict, Any from .base import BaseTool class ExitPlanModeTool(BaseTool): """Use this tool when you are in plan mode and ready to code""" @property def name(self) -> str: return "ExitPlanMode" def _exec...
32
871
ai-agent-book
chapter5/coding-agent/tools/task_tool.py
.py
""" Task tool - Launch sub-agents for complex tasks """ from typing import Dict, Any from .base import BaseTool class TaskTool(BaseTool): """Launch a new agent to handle complex, multi-step tasks autonomously""" @property def name(self) -> str: return "Task" def _execute_impl(self, ...
38
1,195
ai-agent-book
chapter5/coding-agent/tools/bash_tool.py
.py
""" Bash tool - Command execution in persistent shell sessions """ import time import hashlib from typing import Dict, Any from .base import BaseTool class BashTool(BaseTool): """Executes bash commands in persistent shell sessions""" @property def name(self) -> str: return "Bash" de...
76
2,821
ai-agent-book
chapter5/coding-agent/tools/__init__.py
.py
""" Tools module - All tool implementations """ from .base import BaseTool, ToolResult from .bash_tool import BashTool from .bash_output_tool import BashOutputTool from .kill_bash_tool import KillBashTool from .read_tool import ReadTool from .write_tool import WriteTool from .edit_tool import EditTool from .multi_edit...
47
1,107
ai-agent-book
chapter5/coding-agent/tools/notebook_edit_tool.py
.py
""" NotebookEdit tool - Edit Jupyter notebook cells """ import json from pathlib import Path from typing import Dict, Any from .base import BaseTool class NotebookEditTool(BaseTool): """Completely replaces the contents of a specific cell in a Jupyter notebook""" @property def name(self) -> str: ...
125
4,753
ai-agent-book
chapter5/coding-agent/tools/edit_tool.py
.py
""" Edit tool - File editing with search and replace """ import subprocess from pathlib import Path from typing import Dict, Any, Optional from .base import BaseTool class EditTool(BaseTool): """Performs exact string replacements in files""" @property def name(self) -> str: return "Edit" ...
139
4,890
ai-agent-book
chapter5/coding-agent/tools/glob_tool.py
.py
""" Glob tool - Pure Python file pattern matching """ import os from pathlib import Path from typing import Dict, Any, List from .base import BaseTool class GlobTool(BaseTool): """Fast file pattern matching tool""" @property def name(self) -> str: return "Glob" def _execute_impl(sel...
66
1,970
ai-agent-book
chapter5/coding-agent/tools/shell_session.py
.py
""" Cross-platform shell session management for persistent command execution. """ import base64 import os import queue import re import signal import shlex import shutil import subprocess import tempfile import threading import time import uuid from dataclasses import dataclass, field from typing import Dict, List, Op...
445
16,702
ai-agent-book
chapter5/coding-agent/tools/web_fetch_tool.py
.py
""" WebFetch tool - Fetch and analyze web content """ from typing import Dict, Any from .base import BaseTool class WebFetchTool(BaseTool): """Fetches content from a specified URL and processes it""" @property def name(self) -> str: return "WebFetch" def _execute_impl(self, params: ...
38
1,221
ai-agent-book
chapter5/coding-agent/tools/read_tool.py
.py
""" Read tool - File reading with support for text, images, PDFs, and notebooks """ import os from pathlib import Path from typing import Dict, Any, Optional from .base import BaseTool class ReadTool(BaseTool): """Reads files from the local filesystem""" @property def name(self) -> str: retu...
198
7,704
ai-agent-book
chapter5/coding-agent/tools/todo_write_tool.py
.py
""" TodoWrite tool - Task list management """ from typing import Dict, Any from .base import BaseTool class TodoWriteTool(BaseTool): """Creates and manages structured task lists""" @property def name(self) -> str: return "TodoWrite" def _execute_impl(self, params: Dict[str, Any]) ->...
46
1,495
ai-agent-book
chapter5/coding-agent/tools/web_search_tool.py
.py
""" WebSearch tool - Search the web """ from typing import Dict, Any from .base import BaseTool class WebSearchTool(BaseTool): """Allows Claude to search the web and use the results""" @property def name(self) -> str: return "WebSearch" def _execute_impl(self, params: Dict[str, Any]...
35
1,106
ai-agent-book
chapter5/coding-agent/tools/ls_tool.py
.py
""" LS tool - Directory listing """ import os from pathlib import Path import fnmatch from typing import Dict, Any, List from .base import BaseTool class LSTool(BaseTool): """Lists files and directories""" @property def name(self) -> str: return "LS" def _execute_impl(self, params: ...
77
2,286
ai-agent-book
chapter5/coding-agent/tools/multi_edit_tool.py
.py
""" MultiEdit tool - Multiple edits to a single file in one operation """ import subprocess from pathlib import Path from typing import Dict, Any, List, Optional from .base import BaseTool class MultiEditTool(BaseTool): """Makes multiple edits to a single file in one operation""" @property def name(...
138
5,157
ai-agent-book
chapter5/coding-agent/tools/base.py
.py
""" Base classes for tool implementation """ from typing import Dict, Any, Optional from abc import ABC, abstractmethod from dataclasses import dataclass from datetime import datetime @dataclass class ToolResult: """Result from a tool execution""" success: bool data: Dict[str, Any] error: Optional[st...
99
2,648
ai-agent-book
chapter5/coding-agent/tools/grep_tool.py
.py
""" Grep tool - Pure Python implementation without rg/grep dependencies Implements full regex search across files with all features from tools.json """ import re import os from pathlib import Path from typing import Dict, Any, List, Tuple, Optional import fnmatch from .base import BaseTool class GrepTool(BaseTool): ...
354
12,909
ai-agent-book
chapter5/coding-agent/tools/bash_output_tool.py
.py
""" BashOutput tool - Retrieve output from background bash jobs """ import os import re from typing import Dict, Any from .base import BaseTool from .shell_session import get_background_log_path class BashOutputTool(BaseTool): """Retrieves output from running or completed background bash shells""" @prop...
65
2,372
ai-agent-book
chapter5/coding-agent/tools/kill_bash_tool.py
.py
""" KillBash tool - Terminate shell sessions """ from typing import Dict, Any from .base import BaseTool class KillBashTool(BaseTool): """Kills a running background bash shell by its ID""" @property def name(self) -> str: return "KillBash" def _execute_impl(self, params: Dict[str, A...
60
1,971
ai-agent-book
chapter5/coding-agent/tests/test_multi_edit_tool.py
.py
""" Test cases for MultiEdit tool Tests all features from tools.json """ import pytest from pathlib import Path from tools.multi_edit_tool import MultiEditTool class TestMultiEditTool: """Test MultiEdit tool functionality""" def test_multiple_edits(self, system_state, temp_dir): """Test multiple...
244
8,305
ai-agent-book
chapter5/coding-agent/tests/test_notebook_edit_tool.py
.py
""" Test cases for NotebookEdit tool Tests all features from tools.json """ import pytest import json from pathlib import Path from tools.notebook_edit_tool import NotebookEditTool @pytest.fixture def sample_notebook(temp_dir): """Create a sample Jupyter notebook""" notebook_path = temp_dir / "test.ipynb" ...
243
8,118
ai-agent-book
chapter5/coding-agent/tests/test_multi_edit_empty_old_on_existing.py
.py
"""Empty old_string on an existing file must not wipe contents (match Edit).""" from tools.edit_tool import EditTool from tools.multi_edit_tool import MultiEditTool def test_empty_old_string_on_existing_file_rejected(system_state, temp_dir): path = temp_dir / "keep.txt" path.write_text("hello world", encodin...
64
2,237
ai-agent-book
chapter5/coding-agent/tests/test_read_tool.py
.py
""" Test cases for Read tool Tests all features from tools.json including images, PDFs, notebooks """ import pytest import json from pathlib import Path from tools.read_tool import ReadTool class TestReadTool: """Test Read tool functionality""" def test_basic_read(self, system_state, sample_files): ...
208
6,872
ai-agent-book
chapter5/coding-agent/tests/test_write_tool.py
.py
""" Test cases for Write tool Tests all features from tools.json """ import pytest from pathlib import Path from tools.write_tool import WriteTool class TestWriteTool: """Test Write tool functionality""" def test_basic_write(self, system_state, temp_dir): """Test basic file writing""" to...
149
4,955
ai-agent-book
chapter5/coding-agent/tests/test_read_limit_zero.py
.py
"""limit=0 on a nonempty file must not claim the file is empty.""" def test_limit_zero_on_nonempty_file(system_state, temp_dir): from tools.read_tool import ReadTool path = temp_dir / "lines.txt" path.write_text("a\nb\nc\n", encoding="utf-8") result = ReadTool(system_state).execute( {"file_pa...
39
1,296
ai-agent-book
chapter5/coding-agent/tests/test_read_negative_limit.py
.py
"""Regression: negative Read.limit must not silently drop a file suffix.""" from pathlib import Path from tools.read_tool import ReadTool from system_state import SystemState def test_negative_limit_reads_to_eof(tmp_path: Path): path = tmp_path / "f.txt" path.write_text("\n".join(f"L{i}" for i in range(1, 11...
14
484
ai-agent-book
chapter5/coding-agent/tests/test_integration.py
.py
""" Integration tests for the complete agent system Tests system hints, tool chaining, and end-to-end workflows """ import pytest from system_state import SystemState from tools.grep_tool import GrepTool from tools.write_tool import WriteTool from tools.todo_write_tool import TodoWriteTool class TestSystemHints: ...
165
5,598
ai-agent-book
chapter5/coding-agent/tests/test_kill_bash_tool.py
.py
""" Test cases for KillBash tool Tests all features from tools.json """ import pytest from tools.kill_bash_tool import KillBashTool from tools.bash_tool import BashTool class TestKillBashTool: """Test KillBash tool functionality""" def test_kill_shell_session(self, system_state): """Test killing...
73
2,295
ai-agent-book
chapter5/coding-agent/tests/test_exit_plan_mode_tool.py
.py
""" Test cases for ExitPlanMode tool Tests all features from tools.json """ import pytest from tools.exit_plan_mode_tool import ExitPlanModeTool class TestExitPlanModeTool: """Test ExitPlanMode tool functionality""" def test_basic_plan_submission(self, system_state): """Test submitting a plan"""...
69
1,558
ai-agent-book
chapter5/coding-agent/tests/__init__.py
.py
""" Test suite for the Coding Agent """
5
41
ai-agent-book
chapter5/coding-agent/tests/test_bash_tool.py
.py
""" Test cases for Bash tool Tests all features from tools.json """ import pytest import time from pathlib import Path from tools.bash_tool import BashTool class TestBashTool: """Test Bash tool functionality""" def test_basic_command(self, system_state): """Test basic command execution""" ...
231
7,642
ai-agent-book
chapter5/coding-agent/tests/test_glob_tool.py
.py
""" Test cases for Glob tool Tests all features from tools.json """ import pytest from tools.glob_tool import GlobTool class TestGlobTool: """Test Glob tool functionality""" def test_basic_glob(self, system_state, sample_files): """Test basic glob pattern""" tool = GlobTool(system_state)...
132
4,393
ai-agent-book
chapter5/coding-agent/tests/test_grep_multiline_content.py
.py
import sys from pathlib import Path # Ensure coding-agent modules can be resolved regardless of working directory sys.path.insert(0, str(Path(__file__).parent.parent)) from system_state import SystemState from tools.grep_tool import GrepTool def test_grep_tool_supports_multiline_content_matching(tmp_path): """V...
36
1,197
ai-agent-book
chapter5/coding-agent/tests/test_ls_tool.py
.py
""" Test cases for LS tool Tests all features from tools.json """ import pytest from pathlib import Path from tools.ls_tool import LSTool class TestLSTool: """Test LS tool functionality""" def test_basic_listing(self, system_state, sample_files): """Test basic directory listing""" tool =...
211
7,089
ai-agent-book
chapter5/coding-agent/tests/test_shell_session.py
.py
""" Test cases for ShellSession __CMD_DONE__ marker handling """ from unittest.mock import MagicMock, patch from tools import shell_session from tools.shell_session import ShellSession class TestShellSelection: """Test platform-specific shell selection and command wrapping.""" def test_windows_prefers_powe...
141
5,301
ai-agent-book
chapter5/coding-agent/tests/test_grep_head_limit_zero.py
.py
"""head_limit=0 must return zero results (like `head -0`), not unlimited.""" def test_head_limit_zero_files_with_matches(system_state, sample_files): from tools.grep_tool import GrepTool result = GrepTool(system_state).execute( { "pattern": "ERROR", "path": str(sample_files["t...
44
1,285
ai-agent-book
chapter5/coding-agent/tests/test_grep_negative_head_limit.py
.py
"""Regression: head_limit=-1 must mean unlimited, not stop after first hit.""" from pathlib import Path def test_source_treats_negative_head_limit_as_unlimited(): src = Path(__file__).resolve().parents[1] / "tools" / "grep_tool.py" text = src.read_text() assert "if head_limit is not None and head_limit < ...
10
404
ai-agent-book
chapter5/coding-agent/tests/test_todo_write_tool.py
.py
""" Test cases for TodoWrite tool Tests all features from tools.json """ import pytest from tools.todo_write_tool import TodoWriteTool class TestTodoWriteTool: """Test TodoWrite tool functionality""" def test_create_todo_list(self, system_state): """Test creating a TODO list""" tool = To...
143
5,053
ai-agent-book
chapter5/coding-agent/tests/test_bash_output_tool.py
.py
""" Test cases for BashOutput tool Tests all features from tools.json """ import pytest import time from pathlib import Path from tools.bash_output_tool import BashOutputTool from tools.bash_tool import BashTool class TestBashOutputTool: """Test BashOutput tool functionality""" def test_retrieve_backgro...
116
3,723
ai-agent-book
chapter5/coding-agent/tests/test_edit_tool.py
.py
""" Test cases for Edit tool Tests all features from tools.json """ import pytest from pathlib import Path from tools.edit_tool import EditTool class TestEditTool: """Test Edit tool functionality""" def test_basic_edit(self, system_state, sample_files): """Test basic search and replace""" ...
188
6,380
ai-agent-book
chapter5/coding-agent/tests/test_grep_negative_context.py
.py
"""Regression: negative -B/-A/-C must not wipe matches via empty ranges.""" from pathlib import Path def test_source_clamps_context(): src = Path(__file__).resolve().parents[1] / "tools" / "grep_tool.py" text = src.read_text() assert "context_before = max(0, int(context_before))" in text
9
303
ai-agent-book
chapter5/coding-agent/tests/test_grep_tool.py
.py
""" Test cases for Grep tool - Pure Python implementation Tests all features from tools.json """ import pytest from tools.grep_tool import GrepTool class TestGrepTool: """Test Grep tool functionality""" def test_basic_search(self, system_state, sample_files): """Test basic pattern search""" ...
285
9,940
ai-agent-book
chapter5/coding-agent/tests/conftest.py
.py
""" Pytest configuration and fixtures """ import pytest import tempfile import shutil from pathlib import Path from system_state import SystemState @pytest.fixture def system_state(): """Create a fresh system state for each test""" return SystemState() @pytest.fixture def temp_dir(): """Create a tempor...
84
1,801
ai-agent-book
chapter5/log-diagnosis/campaign.py
.py
"""Acceptance campaign for Experiment 5-8 using live HTTP, an LLM, and GitHub MCP.""" from __future__ import annotations import argparse import hashlib import json import os import re import shutil import socket import subprocess import sys import time import urllib.error import urllib.request from dataclasses import...
661
29,011
ai-agent-book
chapter5/log-diagnosis/github_mcp.py
.py
""" github_mcp.py —— GitHub Issue 创建(默认 mock,可选真实 MCP) - mock(默认):把"创建 Issue"渲染成将要提交的 Issue 结构,打印并写入本地文件, 不联网、不需要 token。 - 真实(mock=False,需 GITHUB_TOKEN + GITHUB_REPO):通过 MCP 协议连接官方 GitHub MCP Server(stdio),调用其 `create_issue` 工具在真实仓库创建 Issue。 出于安全,真实创建须由 demo.py 的 --create-issue 显式开启。 """ import json import os i...
142
6,358
ai-agent-book
chapter5/log-diagnosis/test_replay_latency.py
.py
from replay import _eval_assertion def test_latency_under_null_latency_ms(): assertion = { "type": "latency_under", "params": {"tool": "test_tool", "threshold": 150}, } traj = { "turns": [ {"tool": "test_tool", "latency_ms": None}, {"tool": "test_tool", "lat...
26
750
ai-agent-book
chapter5/log-diagnosis/replay.py
.py
""" replay.py —— 回归测试重放框架 输入:Agent 生成的回归测试用例(结构化 JSON),引用轨迹 ID 与交互轮次。 过程:从原始轨迹取出该任务的输入,喂给被测系统(sut.run_task)重放, 在重放产生的新轨迹上求值断言,给出 通过/失败。 一个测试用例的结构(Agent 需按此 DSL 生成): { "test_id": "RT-001", "trajectory_id": "T-1001", # 引用的问题轨迹 "focus_turn": 3, # 关键交互轮次(问题所在) "description": "退款前必须先做资格...
139
5,446
ai-agent-book
chapter5/log-diagnosis/test_github_mcp_bare_output.py
.py
import json import os import github_mcp def test_create_issues_bare_filename(tmp_path, monkeypatch): """out_path 为不带目录的裸文件名时,落盘不应崩溃(dirname 为空串)。""" monkeypatch.chdir(tmp_path) problems = [{"priority": "P1", "module": "refund", "title": "退款未校验", "description": "描述"}] issues = github_...
25
911
ai-agent-book
chapter5/log-diagnosis/demo.py
.py
""" demo.py —— 实验 5-8:生产日志的智能诊断系统(全流程演示) 流水线: 读轨迹集合 + 架构 + PRD -> [LLM] 诊断:定位问题、结构化报告(优先级/模块/描述/建议) -> [LLM] 生成回归测试用例(引用轨迹ID+交互轮次) -> 重放框架真正执行:先复现 bug(FAIL),再验证修复(PASS) -> (mock) 通过 MCP 对接 GitHub 创建 Issue 运行: cp env.example .env && 填入 OPENAI_API_KEY python demo.py # 完整流程(两次真实 LLM...
219
11,080
ai-agent-book
chapter5/log-diagnosis/http_service.py
.py
"""Small real HTTP system used by the Experiment 5-8 campaign. The service intentionally exposes ordinary order, refund, and inventory endpoints. The buggy/fixed distinction lives in the orchestrator under test: the buggy orchestrator skips a required endpoint and mishandles an inventory timeout, while the fixed orch...
99
3,701
ai-agent-book
chapter5/log-diagnosis/test_campaign_orchestrator.py
.py
"""Live HTTP regressions for the findings reported in issue #502.""" from __future__ import annotations import threading from collections.abc import Iterator from http.server import ThreadingHTTPServer import pytest from campaign import INVENTORY_DEADLINE_SECONDS, _trajectory from http_service import Handler @pyt...
65
1,976
ai-agent-book
chapter5/log-diagnosis/sut.py
.py
""" sut.py —— System Under Test(被测系统的确定性仿真) 回归测试的核心是"用相同输入重放,断言修复后系统能产生正确行为"。 这里用一个**确定性**的仿真器来扮演线上 Agent 系统: - run_task(task_input, fixed=False):复现线上(有 bug)的行为, 产出的轨迹会带上和生产轨迹一致的三类已知问题。 - run_task(task_input, fixed=True):模拟"修复后"的系统, 正确执行前置校验 / 重试退避 / 库存降级。 replay.py 会分别对 fixed=False / fixed=True 重放同一输入, 从而演示同一条回...
112
5,070
ai-agent-book
chapter5/log-diagnosis/diagnoser.py
.py
""" diagnoser.py —— 诊断 Agent(真实调用 OpenAI) 两个阶段,均为真实 LLM 调用: 1) diagnose() 读轨迹集合 + 架构 + PRD -> 结构化问题报告(优先级/模块/描述/建议) 2) gen_test_cases() 基于问题报告 -> 生成可被 replay.py 自动执行的回归测试用例 默认模型 gpt-5.6-luna,输出走 JSON 模式,尽量稳定可解析。 """ import json import os from typing import Dict, Any, List from openai import OpenAI MODE...
160
6,490
ai-agent-book
chapter5/conversational-ui/test_customize_non_dict_file_item.py
.py
"""apply_edits files 列表含 null/非 dict 项时,customize 应丢弃而非崩溃。""" import json import types import pytest import agent def _fake_client(arguments): fn = types.SimpleNamespace(name="apply_edits", arguments=arguments) tc = types.SimpleNamespace(id="c1", type="function", function=fn) msg = types.SimpleNamespace...
44
1,537
ai-agent-book
chapter5/conversational-ui/test_customize_malformed_json.py
.py
"""Malformed apply_edits JSON must not abort customize with JSONDecodeError.""" import types import agent def _fake_client(arguments): fn = types.SimpleNamespace(name="apply_edits", arguments=arguments) tc = types.SimpleNamespace(id="c1", type="function", function=fn) msg = types.SimpleNamespace(tool_cal...
42
1,566
ai-agent-book
chapter5/conversational-ui/campaign_browser.py
.py
#!/usr/bin/env python3 """Live Vite-HMR/browser campaign for Chapter 5, Experiment 5-11.""" from __future__ import annotations import argparse import datetime as dt import hashlib import json import os import signal import shutil import socket import subprocess import time import urllib.request from pathlib import Pa...
388
19,070
ai-agent-book
chapter5/conversational-ui/demo.py
.py
"""实验 5-11:对话式界面定制系统 —— 端到端演示与自动验证。 本 demo 在"无浏览器"的环境里,把可验证性落在【自然语言 → 代码修改被正确应用】的闭环上: 对每一条自然语言定制需求: 1) 调用真实 OpenAI,让 Agent 定位并改写前端源码(agent.customize); 2) 打印改动前后的 diff 片段(difflib),并把改动写回 frontend/src; 3) 读回源码做断言,确认改动"确实符合需求"(颜色值/字体/文案按要求变化); 4) 运行 `npm run build`(vite build),确认改动没有破坏应用(可编译通过)。 连续跑...
241
8,776
ai-agent-book
chapter5/conversational-ui/test_customize_malformed_args.py
.py
"""模型返回的 apply_edits 参数缺字段/为 null 时,customize 应干净处理而非崩溃。""" import json import types import pytest import agent def _fake_client(arguments): fn = types.SimpleNamespace(name="apply_edits", arguments=arguments) tc = types.SimpleNamespace(id="c1", type="function", function=fn) msg = types.SimpleNamespace(t...
59
2,391
ai-agent-book
chapter5/conversational-ui/agent.py
.py
"""实验 5-11:对话式界面定制 Agent。 职责:接收一条自然语言 UI 定制需求(如"把发送按钮改成蓝色"),读取前端源码, 调用 OpenAI 让模型定位并改写相应源文件(颜色 / 字体 / 文案 / 布局 / 组件)。 设计要点 -------- - 只暴露少量"可定制文件"给模型(frontend/src 下的 App.jsx 与 theme.css), 降低模型改错文件的概率,也让改动可控、可验证。 - 通过 function calling 的 `apply_edits` 工具,让模型返回"要整体改写的文件全文"。 相比零散的 search/replace,整文件改写对小文件更稳定、更少破坏语法。 -...
198
7,842
ai-agent-book
chapter5/conversational-ui/validation/runs/20260729T212727Z-5_11-hmr/app/backend/main.py
.py
"""实验 5-11:对话式界面定制系统 —— FastAPI 后端。 一个最小的 chatbot 后端:前端把用户消息 POST 到 /api/chat,后端返回回复。 开发模式下用 `uvicorn main:app --reload` 启动,改动后端代码会自动 reload (对应书中所说的"FastAPI 的热加载")。 两种回复模式(默认保持"回声式"占位,聚焦 UI 定制这一主题): - **echo(默认)**:后端把用户消息原样回显,无需任何模型 Key,开箱即用; - **llm(可选)**:设置模型后走真实 LLM 对话,让运行起来的 chatbot 真会说话。 通过命令行 `--model`...
220
8,158
ai-agent-book
chapter5/adaptive-log-parser/campaign.py
.py
#!/usr/bin/env python3 """Live self-healing parser + browser/Vision campaign for Experiment 5-7.""" from __future__ import annotations import argparse import ast import base64 import datetime as dt import hashlib import html import io import json import os import re import shutil import subprocess import time from pa...
329
17,098
ai-agent-book
chapter5/adaptive-log-parser/tester.py
.py
""" tester.py —— 自动测试(对生成的解析器做数据结构断言) 书中原方案:把生成的可视化代码放进虚拟浏览器渲染,再用 Vision LLM 检查图像。 本机没有 playwright/浏览器,因此**降级**为对解析函数做单元测试: 用一批样本日志喂给生成的 parse 函数,断言它能解析出预期的结构化字段。 这保证了“生成的代码确实能正确解析新格式”,是自愈闭环里真正的质量闸门。 """ from __future__ import annotations from typing import Callable, Dict, List, Optional ParserFn = Callable[[str], ...
60
2,230
ai-agent-book
chapter5/adaptive-log-parser/engine.py
.py
""" engine.py —— 自适应日志解析引擎(自愈闭环的“运行时”) 设计要点: - 引擎维护一个**解析器注册表**(有序列表)。每来一行日志,依次尝试每个解析器, 谁能解析(返回非空 dict)就用谁的结果;全部失败则抛出 ParseError —— 这就是 “前端检测到无法解析的新格式”的信号,触发后续的自愈流程。 - 每个解析器就是一个纯函数 `parse(line: str) -> dict | None`: * 能解析 → 返回结构化字段(dict) * 不认识这行 → 返回 None(把机会让给别的解析器,避免“抢答”) - 生成的解析器可以持久化成 parsers/*.py 模块,下...
116
5,043
ai-agent-book
chapter5/adaptive-log-parser/demo.py
.py
""" demo.py —— 自适应日志解析系统:自愈闭环演示 演示整条自愈流程(全流程自动化): 初始系统只认基础 JSON 日志 → 遇到没见过的新格式 → 解析【失败】被检测到 → 把失败样本 + 报错交给 Agent → Agent【生成解析代码】→ 【自动测试】(数据结构断言)→ 通过后【热加载注册 + 持久化】→ 系统【正确解析】了新格式。 运行: python demo.py # 完整演示(两种新格式,两次 Agent 调用,需 API Key) python demo.py --offline # 离线演示:用预置解析器跑完整机制,无需 API Key py...
301
13,045
ai-agent-book
chapter5/adaptive-log-parser/agent.py
.py
""" agent.py —— 代码生成 Agent(自愈闭环的“大脑”) 职责:拿到无法解析的失败样本 + 报错,调用 OpenAI,生成一个能正确解析该格式的 Python 解析函数 `def parse(line: str) -> dict | None`。支持把上一轮自动测试的 失败报告作为反馈再次生成(迭代修复)。 """ from __future__ import annotations import os import re from typing import List, Optional from openai import OpenAI # .env 加载(可选依赖) try: from do...
201
8,055
ai-agent-book
chapter5/adaptive-log-parser/validation/runs/20260729T212342Z-5_7-live/producer-2.py
.py
import datetime, time events=[('inventory_lookup',34,'ok','stock check completed'),('payment_api',181,'retry','upstream requested retry'),('payment_api',412,'timeout','deadline exceeded')] for tool,latency,status,message in events: started=time.perf_counter(); time.sleep(0.003); observed=max(latency,int((time.perf_...
8
638
ai-agent-book
chapter5/adaptive-log-parser/validation/runs/20260729T212342Z-5_7-live/producer-1.py
.py
import logging, sys formatter=logging.Formatter('%(asctime)s|%(levelname)s|%(name)s|step=%(step)s|%(message)s', datefmt='%Y-%m-%dT%H:%M:%SZ') handler=logging.StreamHandler(sys.stdout); handler.setFormatter(formatter) logger=logging.getLogger('checkout.worker'); logger.handlers=[handler]; logger.setLevel(logging.INFO); ...
8
547
ai-agent-book
chapter5/adaptive-log-parser/validation/runs/20260729T212342Z-5_7-live/parsers/live_pipe_parser.py
.py
import re def parse(line: str) -> dict | None: # 定义匹配日志格式的正则表达式 pattern = r'^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)\|([A-Z]+)\|([\w.]+)\|step=(\d+)\|(.*)$' match = re.match(pattern, line.strip()) if not match: return None # 提取各个字段 timestamp = match.group(1) level = match.g...
29
733
ai-agent-book
chapter5/adaptive-log-parser/validation/runs/20260729T212342Z-5_7-live/parsers/live_bracket_parser.py
.py
import re def parse(line: str) -> dict | None: # 定义日志格式的正则表达式模式 pattern = r'^\[(?P<timestamp>[^\]]+)\]\s*\((?P<level>[^)]+)\)\s*<tool=(?P<tool>[^>]+)>\s*\{latency_ms=(?P<latency_ms>\d+)\s+status=(?P<status>\w+)\}\s*::\s*(?P<message>.*)$' # 尝试匹配日志行 match = re.match(pattern, line.strip()) if not...
28
869
ai-agent-book
chapter5/code-for-math/test_campaign.py
.py
from build_aime_2024 import convert from demo import campaign_completion, paired_statistics def test_aime_converter_rejects_non_complete_fixture(): row = { "id": 1, "problem": "What is 1+1?", "answer": "2", "url": "https://example.test/aime", "year": "2024", } try: ...
75
2,559
ai-agent-book
chapter5/code-for-math/test_empty_problems.py
.py
"""Empty problems JSON must not ZeroDivisionError in the accuracy summary.""" import json import sys from pathlib import Path from types import SimpleNamespace import demo as cfm class _Resp: def __init__(self): self.choices = [ SimpleNamespace( message=SimpleNamespace(content...
64
1,602
ai-agent-book
chapter5/code-for-math/sandbox.py
.py
"""子进程 Python 沙箱:在隔离的子进程中执行模型生成的代码,带超时限制。 预装 sympy / numpy / scipy(随本项目 requirements 一并安装)。 之所以用子进程而不是 exec(),是为了: 1. 隔离:模型代码崩溃 / 死循环不会影响主进程; 2. 超时:可强制杀掉执行过久的代码; 3. 干净的命名空间:每次执行都是全新解释器。 """ import subprocess import sys import tempfile import os # 在执行前注入的前置代码:预导入常用数学库,方便模型直接使用。 PREAMBLE = """ import math import...
74
2,508
ai-agent-book
chapter5/code-for-math/demo.py
.py
"""实验 5-1:用代码生成工具提升数学解题能力 对照实验:在同一组 AIME 风格竞赛数学题上,比较 - 【纯思维链 CoT】:只靠自然语言推理,不能执行代码; - 【代码辅助】:把问题形式化为 Python(sympy 符号计算、scipy 数值优化、 numpy 矩阵),在子进程沙箱执行,返回精确结果。 两种模式跑同一个模型、同一组题、temperature=0,最后给出准确率对照表。 运行: python demo.py # 跑完整对照实验(需要 API key) python demo.py --selfcheck # 离线自检:只跑沙箱...
771
31,189
ai-agent-book
chapter5/code-for-math/build_aime_2024.py
.py
#!/usr/bin/env python3 """Build a revision-pinned official AIME 2024 benchmark for Experiment 5-1.""" from __future__ import annotations import argparse import hashlib import json import tempfile import urllib.request from pathlib import Path import pyarrow.parquet as parquet DATASET = "HuggingFaceH4/aime_2024" RE...
93
3,147
ai-agent-book
chapter5/dynamic-form/campaign.py
.py
#!/usr/bin/env python3 """Canonical live campaign for Chapter 5, Experiment 5-9. The companion demo historically stopped at static HTML inspection and a constructed submission dictionary. This campaign deliberately has no such fallback: a real model writes the form, Chromium executes its JavaScript, a single browser ...
340
13,209
ai-agent-book
chapter5/dynamic-form/test_summarize_numeric_zero_baggage.py
.py
import importlib.util from pathlib import Path _demo_path = Path(__file__).parent / "demo.py" _spec = importlib.util.spec_from_file_location("dynamic_form_demo", _demo_path) _demo = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(_demo) summarize_offline = _demo.summarize_offline def test_summarize_o...
61
2,132
ai-agent-book
chapter5/dynamic-form/demo.py
.py
"""实验 5-9:动态表单生成的意图澄清系统(★★) 核心思路 -------- 当用户请求缺少关键信息时,Agent 不是逐条追问,而是**动态生成一个自包含的 HTML 表单**(含级联显示逻辑),让用户"一次提交"补全所有澄清点;前端把表单 汇总成 JSON 交回 Agent,Agent 解析后继续任务。 本 demo 分三步验证(不依赖真实浏览器): 1) 生成澄清表单 HTML,保存为 generated_form.html; 2) 用 BeautifulSoup 结构化校验:确实含 出发城市/出发日期/旅行类型(单程,往返)/ 返程日期,且返程字段带"仅往返显示"的级联 JS 逻辑; 3) 模...
724
29,546
ai-agent-book
chapter5/dynamic-form/test_round_trip_destination.py
.py
import subprocess import sys from pathlib import Path import pytest @pytest.mark.parametrize( ("user_request", "expected_destination"), [ ("我想订一张去上海的机票", "上海"), ("我想订一张去上海的往返机票", "上海"), ("我想订一张去上海往返的机票", "上海"), ("我想订一张去上海往返机票", "上海"), ("我想订一张去广州的单程机票", "广州"), (...
58
2,021
ai-agent-book
chapter5/paper-to-video/campaign.py
.py
"""Canonical real-API paper-to-lecture-video campaign for Experiment 5-5.""" from __future__ import annotations import argparse import base64 import hashlib import json import os import re import shutil import subprocess import time from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import ...
468
21,993
ai-agent-book
chapter5/paper-to-video/test_null_bullet_item.py
.py
"""Slide bullets containing null must still render a PNG.""" import demo def test_render_slide_skips_null_bullet(tmp_path, monkeypatch): monkeypatch.setattr(demo, "SLIDES_DIR", tmp_path) slide = { "title": "Demo Title", "subtitle": "Demo Subtitle", "bullets": ["ok", None, "also"], ...
16
469
ai-agent-book
chapter5/paper-to-video/test_campaign.py
.py
import json from pathlib import Path import campaign def test_protocol_is_exact_twelve_page_five_to_fifteen_minute_contract(): protocol = json.loads(campaign.PROTOCOL_PATH.read_text()) assert len(protocol["source"]["selected_pages"]) == 12 assert protocol["acceptance"]["duration_seconds_min"] == 300 ...
90
3,184