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
chapter10/autonomous-phone-registration/bus.py
.py
"""Asynchronous, timestamped point-to-point bus for the two live Agents.""" from __future__ import annotations import asyncio import json import time from collections import defaultdict from pathlib import Path from typing import DefaultDict, List, Optional from models import AgentMessage class MessageBus: def...
76
2,681
ai-agent-book
chapter10/autonomous-phone-registration/run_acceptance.py
.py
#!/usr/bin/env python3 """Run the complete safe current Experiment 10-3 acceptance scenario. The form and its submission endpoint are localhost-only. Synthetic personal data is spoken by the configured TTS provider, crosses a real WebRTC audio track, is recorded at the remote peer, and goes through the configured ASR...
327
12,221
ai-agent-book
chapter10/autonomous-phone-registration/webrtc_channel.py
.py
"""Local WebRTC transport for the Experiment 10-3 Phone Agent. The participant page contains the two ends of a standards-based WebRTC call. The agent sends synthesized speech on one RTP audio track; the participant sends a microphone track in the other direction. Only the peer-side recording is handed to ASR, and it...
649
28,224
ai-agent-book
chapter10/autonomous-phone-registration/decision.py
.py
"""LLM decision point that may autonomously call ``initiate_phone_call_agent``.""" from __future__ import annotations import json import os import time from pathlib import Path from models import DecisionRecord, FieldSpec TOOL_NAME = "initiate_phone_call_agent" def _clients_and_models(): from openai import As...
250
9,324
ai-agent-book
chapter10/autonomous-phone-registration/test_validate_acceptance.py
.py
import hashlib import json import shutil from pathlib import Path import pytest from validate_acceptance import ValidationFailure, validate_run ROOT = Path(__file__).parent RUN = ROOT / "validation/runs/exp10-5-webrtc-raw-20260731-v4" def _write(path: Path, value: dict) -> None: path.write_text(json.dumps(value...
78
2,836
ai-agent-book
chapter10/autonomous-phone-registration/test_webrtc_channel.py
.py
import io import math import struct import wave import pytest from demo import _rtp_is_bidirectional, _webrtc_answer_plan from models import FieldSpec from run_acceptance import _has_credential, _synthetic_values from webrtc_channel import CALL_PAGE, WebRTCPhoneChannel class ToneSpeechBackend: provider = "deter...
88
3,136
ai-agent-book
chapter10/autonomous-phone-registration/browser.py
.py
"""Real Playwright Computer Use surface for registration forms.""" from __future__ import annotations import asyncio from typing import List, Optional from models import FieldSpec class RecoverableFillError(RuntimeError): """A page-specific field failure that may be reported without aborting the call.""" cla...
162
6,842
ai-agent-book
chapter10/autonomous-phone-registration/test_exp105_validation_evidence.py
.py
import hashlib import json from pathlib import Path ROOT = Path(__file__).parent WEBRTC_RUN = ROOT / "validation/runs/exp10-5-webrtc-raw-20260731-v4" def test_persisted_evidence_is_redacted_and_does_not_overclaim_voice(): report = json.loads((ROOT / "validation/real_browser_llm_2026-07-29.json").read_text()) ...
111
5,598
ai-agent-book
chapter10/parallel-web-research/test_official_experiment.py
.py
import hashlib import json import re from pathlib import Path ROOT = Path(__file__).resolve().parent RUN = ROOT / "validation" / "runs" / "exp10-6-real-receipts-20260730-v2" def sha256_bytes(value: bytes) -> str: return hashlib.sha256(value).hexdigest() def canonical_bytes(value) -> bytes: return json.dum...
72
3,033
ai-agent-book
chapter10/parallel-web-research/run_official_experiment.py
.py
#!/usr/bin/env python3 """Run Experiment 10-4 with provenance-complete real-provider receipts.""" from __future__ import annotations import argparse import asyncio import hashlib import importlib.metadata import json import os import platform import re import subprocess import sys import time from datetime import dat...
424
15,422
ai-agent-book
chapter10/parallel-web-research/sources.py
.py
"""Real university website inputs for Experiment 10-4.""" from __future__ import annotations import json from dataclasses import dataclass from pathlib import Path from typing import List @dataclass(frozen=True) class Website: name: str college: str url: str TARGET = "Andrew Ng" # All are real Stanfo...
51
2,261
ai-agent-book
chapter10/parallel-web-research/test_completed_worker_ack_regression.py
.py
import asyncio import pytest from agents import Coordinator, TaskRecord from message_bus import MessageBus from sources import Website @pytest.mark.asyncio async def test_worker_completing_before_winner_is_not_reported_as_missing_ack(): """Contract proved: Coordinator.run excludes workers that completed with not_f...
83
3,289
ai-agent-book
chapter10/parallel-web-research/test_worker_terminate_before_task.py
.py
import asyncio import pytest import sys from pathlib import Path # Ensure chapter10/parallel-web-research is in sys.path sys.path.insert(0, str(Path(__file__).parent)) from agents import WorkerAgent from message_bus import MessageBus, BROADCAST from sources import Website @pytest.mark.asyncio async def test_worker_...
33
1,334
ai-agent-book
chapter10/parallel-web-research/agents.py
.py
"""Real-browser workers and central coordinator for Experiment 10-4.""" from __future__ import annotations import asyncio import time from dataclasses import dataclass, field from enum import Enum from typing import Callable, Dict, List, Optional from llm import extract_profile from message_bus import BROADCAST, Mes...
397
16,421
ai-agent-book
chapter10/parallel-web-research/llm.py
.py
"""Evidence-grounded profile extraction with real configured LLM APIs.""" from __future__ import annotations import json import os import time from typing import Callable, Dict, Optional ReceiptSink = Optional[Callable[[Dict[str, object]], None]] def _backends(): from openai import AsyncOpenAI out = [] ...
104
4,551
ai-agent-book
chapter10/parallel-web-research/test_exp106_validation_evidence.py
.py
import json from pathlib import Path ROOT = Path(__file__).parent / "validation" def test_real_parallel_serial_evidence_closes_every_context_and_measures_speedup(): data = json.loads((ROOT / "real_parallel_serial_2026-07-29.json").read_text()) assert data["overall_status"] == "pass" assert data["paralle...
23
923
ai-agent-book
chapter10/parallel-web-research/demo.py
.py
#!/usr/bin/env python3 """Experiment 10-4: parallel real-browser faculty search.""" from __future__ import annotations import argparse import asyncio import json import time from pathlib import Path try: from dotenv import load_dotenv load_dotenv() except Exception: pass from agents import BrowserPool, ...
94
3,982
ai-agent-book
chapter10/parallel-web-research/test_coordination.py
.py
import asyncio from types import SimpleNamespace import pytest from agents import Coordinator from agents import WorkerAgent from message_bus import MessageBus from sources import DEFAULT_SITES, load_sites @pytest.mark.asyncio async def test_near_simultaneous_hits_settle_and_broadcast_once(): bus = MessageBus(v...
152
5,522
ai-agent-book
chapter10/parallel-web-research/message_bus.py
.py
""" 进程内异步消息总线(Message Bus) ================================ 模仿 Redis Pub/Sub 的语义,但完全跑在单进程的 asyncio 事件循环里, 无需真正部署 Redis。它承担实验 10-4 里"中心协调"的通信底座: - 每条消息都封装在 ``Envelope`` 信封里,带上 sender_id / target / type / payload; - Agent 通过 ``subscribe()`` 拿到一个订阅句柄,按消息类型接收; - Agent 通过 ``publish()`` 把消息投递给指定目标或广播给所有人; - 总线本身不做任何业务判断,只负...
141
5,414
ai-agent-book
chapter10/book-translation/test_official_experiment.py
.py
import hashlib import json from pathlib import Path from types import SimpleNamespace import pytest import agents from run_official_experiment import ( DIMENSIONS, campaign_fingerprint, judge_chapter, load_checkpoint, markdown_fidelity, restore_arm, serialize_arm, split_translation_uni...
226
8,647
ai-agent-book
chapter10/book-translation/run_official_experiment.py
.py
#!/usr/bin/env python3 """Run Experiment 10-2 on a real illustrated, code-heavy technical book. The tiny four-file fixture remains useful for a cheap tutorial. This is the acceptance campaign: it translates Chapters 1 and 2 of the English edition of this book (more than 240 KB, with real figures and fenced code), com...
861
38,358
ai-agent-book
chapter10/book-translation/consistency.py
.py
""" 术语一致性检查工具。 思路:对每个受关注的英文术语,预先列出它在中文里“几种常见但不同”的译法。 扫描全书各章译文,统计每个术语实际出现了几种不同译法: - 只出现 1 种 → 全书一致; - 出现 >= 2 种 → 术语漂移(不一致)。 这不是给模型评分,而是用确定性的字符串匹配,客观度量“同一术语是否全书统一”。 """ # 每个术语:canonical 为推荐/术语表规定译法;variants 为若干“互不相同”的常见译法。 # 注意:variants 之间尽量不互为子串,避免重复计数(如“嵌入向量”归入“嵌入”一族)。 TRACKED_TERMS = [ {"en": "token", ...
140
5,870
ai-agent-book
chapter10/book-translation/consistency_auditor.py
.py
"""Bilingual Consistency Auditor module for translated technical Markdown documentation. Audits domain terminology mapping, code block synchronization (matching book/ source), LaTeX formula syntax preservation, and link targets across translated Markdown files. """ from dataclasses import dataclass, field import os f...
452
18,302
ai-agent-book
chapter10/book-translation/agents.py
.py
""" 实验 10-2:书籍翻译 Agent —— 管理者模式(Orchestration) 本模块实现四种专职 Agent,以及两种运行方式: 1) 管理者模式(orchestrate):Manager 只保存任务/计划/调用记录/文件索引, 不保存完整译文;各子 Agent 拥有独立、隔离的上下文。 2) 单 Agent 模式(single_agent):一个 Agent 在同一条不断增长的对话里 依次读全书、逐章翻译,用于对照“上下文膨胀”与“术语漂移”。 核心验证点: - 记录每个 Agent / Manager 的上下文 token 消耗; - 证明管理者模式下 Manager 的上...
750
33,227
ai-agent-book
chapter10/book-translation/demo.py
.py
""" 实验 10-2 一键演示。 python demo.py # 完整跑:管理者模式 + 单 Agent 对照 python demo.py --help # 查看全部参数 python demo.py --dry-run # 离线:只画四 Agent 协作图 + token 预算,不调 API python demo.py --model gpt-5.6-luna # 换用更强的模型 python demo.py --skip-single # 只跑管理者模式,跳过单 Agent...
362
17,798
ai-agent-book
chapter10/book-translation/tests/test_glossary_robustness.py
.py
"""回归测试:Glossary Agent 返回不合规 JSON 时,run_orchestration 不应崩溃。 覆盖两类模型失误(此前会让整轮管理者模式直接 KeyError/AttributeError): 1) glossary 条目缺 en/zh 键、或值为显式 null / 空串 -> 条目被丢弃; 2) 顶层 JSON 是数组而非对象 -> glossary_agent 返回空表。 不依赖真实 API:llm_chat / get_client 被打桩。 """ import json import agents # 混合各种坏条目的 glossary:错键名 / null / 空串 都应被丢弃,只...
62
2,708
ai-agent-book
chapter10/book-translation/tests/test_null_glossary.py
.py
"""Null glossary from Glossary Agent must behave like empty list.""" import agents def test_glossary_agent_null_glossary_like_empty(): def fake_llm_chat(client, tracker, agent, messages, json_mode=False, note=""): tracker.record(agent, 10, 5, note) return '{"glossary": null}' agents.llm_chat...
34
1,148
ai-agent-book
chapter10/book-translation/tests/test_proofread_non_dict.py
.py
"""Proofreading must return a dict when the model emits a JSON array or junk.""" from agents import _loads_lenient, _report_issues, proofreading_agent def test_loads_lenient_empty_and_junk_return_none(): assert _loads_lenient("") is None assert _loads_lenient("not json") is None assert _loads_lenient('{"a...
55
1,703
ai-agent-book
chapter10/book-translation/tests/test_null_issues.py
.py
"""Null proofread issues must not TypeError when building report summaries.""" from agents import _report_issues def test_null_issues_like_empty(): assert _report_issues({"issues": None}) == [] summary_issues = _report_issues({"issues": None})[:5] assert summary_issues == [] details = [i.get("detail",...
16
532
ai-agent-book
chapter10/book-translation/tests/test_non_dict_issue_item.py
.py
"""Non-dict proofread issue entries must not AttributeError on .get.""" from agents import _report_issues def test_string_issue_items_dropped(): report = { "issues": [ "术语不一致:token", {"chapter": "Ch1", "type": "术语不一致", "detail": "用了标记"}, ], } issues = _report_issues...
29
905
ai-agent-book
chapter10/book-translation/tests/conftest.py
.py
"""Shared bootstrap for book-translation regression tests.""" import sys from pathlib import Path from types import ModuleType PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) try: import openai # noqa: F401 except ImportError: ...
27
777
ai-agent-book
chapter10/multi-role-transfer/test_official_experiment.py
.py
import hashlib import json import re from pathlib import Path ROOT = Path(__file__).resolve().parent RUN = ROOT / "validation" / "runs" / "exp10-2-kimi-k2.5-tavily-receipts-20260730-v3" def sha256_bytes(value: bytes) -> str: return hashlib.sha256(value).hexdigest() def canonical_bytes(value) -> bytes: ret...
77
3,367
ai-agent-book
chapter10/multi-role-transfer/run_official_experiment.py
.py
#!/usr/bin/env python3 """Run Experiment 10-1 with raw Moonshot/Tavily receipts and source hashes.""" from __future__ import annotations import argparse import hashlib import json import os import re import subprocess import time from datetime import datetime, timezone from pathlib import Path from typing import Any,...
279
9,641
ai-agent-book
chapter10/multi-role-transfer/skill_orchestrator.py
.py
"""Skill-based implementation for Experiment 10-1. The system prompt and the tool definitions are fixed for the whole run. A role is selected by loading a ``SKILL.md`` through ``load_skill``; the loaded document is added as a tool result in the shared trajectory. This deliberately models progressive disclosure and m...
322
13,766
ai-agent-book
chapter10/multi-role-transfer/evaluation.py
.py
"""Deterministic scoring helpers for the two Experiment 10-1 paths. The evaluator intentionally scores observable trajectory and outcome fields. It never tries to infer hidden chain-of-thought. The protocol in README.md explains how to add blinded human/LLM judging and paired statistics for live runs. """ from __fu...
311
14,272
ai-agent-book
chapter10/multi-role-transfer/run_comparison.py
.py
#!/usr/bin/env python3 """Run the pre-registered Experiment 10-1 comparison. Within each paired cell both paths use the same model, task text, temperature and fresh conversation. The script saves per-trial trajectories and the deterministic rubric results; it does not claim a result until the requested trials have act...
614
27,827
ai-agent-book
chapter10/multi-role-transfer/judge_comparison.py
.py
#!/usr/bin/env python3 """Blind, position-swapped quality review for retained Experiment 10-1 pairs.""" from __future__ import annotations import argparse import json import os import random import re from datetime import datetime, timezone from pathlib import Path from typing import Any from openai import OpenAI ...
150
5,906
ai-agent-book
chapter10/multi-role-transfer/roles.py
.py
""" roles.py —— 定义多个「专业角色 Agent」。 实验 10-1 的核心:一个会话里存在多个专业角色,每个角色有 (1) 独立的系统提示词(system prompt) (2) 专属工具集(tools) 角色之间通过 transfer_to_agent(target_role, reason) 自主移交控制权。 与 10-1(软件开发单任务的预定义阶段流水线)不同,这里强调跨领域、 由 Agent 自主判断该切换到哪个角色——不是预先规划好的线性流程。 """ from __future__ import annotations from dataclasses import dataclass, ...
143
6,988
ai-agent-book
chapter10/multi-role-transfer/demo.py
.py
""" demo.py —— 实验 10-1 演示入口:多角色转换 / transfer_to_agent 最简运行(一条命令,跑默认复合任务): python demo.py 其它常用方式: python demo.py --list-roles # 离线:只打印角色花名册后退出(无需 API Key) python demo.py --scenario coding # 换一个内置场景(会路由到 coding 角色) python demo.py --task "..." # 自定义任务 python demo.py ...
377
15,556
ai-agent-book
chapter10/multi-role-transfer/package_comparison.py
.py
#!/usr/bin/env python3 """Package a completed Experiment 10-1 campaign into auditable evidence.""" from __future__ import annotations import argparse import hashlib import json import os import re from datetime import datetime, timezone from pathlib import Path from typing import Any ROOT = Path(__file__).resolve()...
285
12,966
ai-agent-book
chapter10/multi-role-transfer/validate_comparison.py
.py
#!/usr/bin/env python3 """Independently verify the retained Experiment 10-1 comparison package.""" from __future__ import annotations import argparse import hashlib import json import re from pathlib import Path ROOT = Path(__file__).resolve().parent def sha256(path: Path) -> str: return hashlib.sha256(path.r...
64
2,657
ai-agent-book
chapter10/multi-role-transfer/tools.py
.py
""" tools.py —— 各专业角色的专属工具实现 + OpenAI function-calling schema。 设计原则(配合实验 10-1): - 所有被实验场景实际调用的工具都执行真实工作,不用预置答案冒充检索。 - research.web_search:Tavily 真实联网检索,并返回可追溯 URL 与摘录。 - coding.execute_python:真实执行 Python 代码并捕获标准输出(子进程 + 超时)。 - data_analysis.calculate / descriptive_stats:真实的安全计算。 - writing.count_characters:真实的中英文字数统计。 ...
298
11,481
ai-agent-book
chapter10/multi-role-transfer/orchestrator.py
.py
""" orchestrator.py —— 多角色移交(handoff)编排器。 核心机制(实验 10-1): - 全程维护一段【共享对话历史】history(user/assistant/tool 消息)。 - 每次调用大模型时,把【当前角色】的系统提示词临时拼到 history 前面, 并只暴露【当前角色的工具集 + transfer_to_agent】。 - 模型可以: 1) 调用自己的专属工具(正常 function calling); 2) 调用 transfer_to_agent 把控制权移交给别的角色—— 此时编排器换掉「系统提示词 + 工具集」,但 history 原样保留, ...
314
14,015
ai-agent-book
chapter10/multi-role-transfer/tests/test_count_characters_null.py
.py
from tools import count_characters def test_count_characters_null_text(): result = count_characters(None) assert result == "总字符数=0, 其中中文字符=0" def test_count_characters_normal(): result = count_characters("你好hi") assert "总字符数=4" in result assert "中文字符=2" in result
13
328
ai-agent-book
chapter10/multi-role-transfer/tests/test_tool_dispatch_errors.py
.py
"""回归测试:模型传错/漏工具参数时,编排器不应崩溃,而应把错误作为工具结果 回给模型(让它自行纠正),流程继续推进到最终回复。 此前 orchestrator.py 的 `impl(**args)` 未加保护:{"q": ...} 这类错键名、 缺必填参数、或无法 float() 转换的取值都会以 TypeError/ValueError 炸掉整个 多角色移交流程。 """ import json import sys from types import SimpleNamespace from orchestrator import MultiRoleOrchestrator FINAL_TEXT = "已查完,最终汇...
82
3,053
ai-agent-book
chapter10/multi-role-transfer/tests/test_execute_python_timeout.py
.py
"""Regression: execute_python must not hang on infinite loops.""" import time from tools import execute_python def test_execute_python_timeout_on_infinite_loop(): t0 = time.time() result = execute_python("while True: pass", timeout=1) elapsed = time.time() - t0 assert "执行超时" in result assert elap...
18
458
ai-agent-book
chapter10/multi-role-transfer/tests/test_skill_comparison.py
.py
import json from pathlib import Path from evaluation import BOUNDARY_CASES, evaluate_boundary, evaluate_task from run_comparison import _static_prefix_hashes from skill_orchestrator import SKILLS, SKILL_TOOLS, SkillOrchestrator, _fixed_system_prompt, load_skill def test_skill_catalog_and_bodies_are_complete(): a...
124
5,807
ai-agent-book
chapter10/multi-role-transfer/tests/conftest.py
.py
"""Shared bootstrap for multi-role-transfer regression tests.""" import sys from pathlib import Path from types import ModuleType PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) try: import openai # noqa: F401 except ImportError...
18
433
ai-agent-book
chapter10/staged-system-prompt/evidence.py
.py
"""Credential-free raw provider receipts for Experiment 10-1.""" from __future__ import annotations import json import time from datetime import datetime, timezone from pathlib import Path from typing import Any def _jsonable(value: Any) -> Any: if hasattr(value, "model_dump"): return value.model_dump(m...
92
3,280
ai-agent-book
chapter10/staged-system-prompt/run_official_experiment.py
.py
"""Run and package the strict real-provider Experiment 10-1 campaign.""" from __future__ import annotations import argparse import hashlib import json import os import time from datetime import datetime, timezone from pathlib import Path from openai import OpenAI from agent import STAGE_PROMPTS, STAGE_TOOLS, Staged...
237
9,742
ai-agent-book
chapter10/staged-system-prompt/test_official_evidence.py
.py
"""Focused structural tests for the strict Experiment 10-1 evidence path.""" from agent import STAGE_PROMPTS, STAGE_TOOLS from run_official_experiment import usage_cost, validate_manifest from tools import Workspace def test_stage_contracts_are_distinct_and_tool_gated(): assert len(set(STAGE_PROMPTS.values())) =...
79
3,384
ai-agent-book
chapter10/staged-system-prompt/demo.py
.py
""" 实验 10-1 演示入口:一条命令跑通“需求澄清 -> 代码实现 -> 代码审查”三阶段。 python demo.py # 默认任务、默认模型、最多 3 次审查回退 python demo.py --list-stages # 离线查看三阶段配置(无需 API Key) python demo.py --help # 查看全部可选参数 演示任务:用户想要“写一个整理下载文件夹的 Python 脚本”。 需求本身模糊,因此需求澄清阶段的 Agent 会主动提问,由模拟用户自动回答; 之后进入实现阶段写代码、审查阶段严格把关(可能回退重写)。 "...
114
4,593
ai-agent-book
chapter10/staged-system-prompt/simulated_user.py
.py
""" 模拟用户:在需求澄清阶段自动回答 Agent 的提问,实现无人值守跑通三阶段。 真实产品里,ask_clarifying_question 会把问题抛给真人;这里用一组预设答案, 按关键词“打分匹配”Agent 的问题并给出回答(命中关键词最多者胜)。 另外内置一个防重复机制:如果同一个问题被反复追问,就明确告诉 Agent “已经回答过、没别的要求了,请开始实现”,避免澄清阶段陷入死循环。 """ from typing import Dict, List, Tuple class SimulatedUser: def __init__(self) -> None: # (关键词列表, 预设...
63
3,658
ai-agent-book
chapter10/staged-system-prompt/config.py
.py
""" 配置模块:集中读取环境变量。 实验 10-1 使用 OpenAI 官方 SDK,所有可调项都通过环境变量注入, 方便切换到兼容 OpenAI 协议的其他厂商(Kimi / Doubao 等)。 """ import os try: # 允许把配置写在 .env 里(可选依赖) from dotenv import load_dotenv load_dotenv() except Exception: # pragma: no cover - dotenv 不是硬性依赖 pass def _to_openrouter_model(model: str) -> str: ""...
71
2,900
ai-agent-book
chapter10/staged-system-prompt/tools.py
.py
""" 工具实现与工具集定义。 本文件包含两部分: 1. Workspace:一个进程内的“虚拟工作区”,负责保存需求、文件内容, 并提供真实的代码执行 / 语法检查 / 复杂度分析能力。 2. 三个阶段各自的工具 JSON Schema(供 OpenAI function calling 使用)。 关键点:不同阶段暴露给模型的工具集是不同的,这是“阶段化系统提示词”实验 的核心之一——提示词换了角色,工具也随之切换。 """ from __future__ import annotations import ast import hashlib import os import subprocess import s...
330
14,026
ai-agent-book
chapter10/staged-system-prompt/agent.py
.py
""" StagedAgent:根据“执行阶段”切换系统提示词与工具集的 Coding Agent。 设计要点(对应实验 10-1 的 6 项要求): 1) 三个阶段各有明确角色的系统提示词(STAGE_PROMPTS)。 2) 每个阶段配套独立工具集(tools.STAGE*_TOOLS)。 3) 阶段转换由“特定工具调用”触发(complete_requirements_analysis / submit_for_review / request_revision / approve_code)。 4) 上下文跨阶段连续:self.history 一直累加,切阶段时只换掉 system 提示词, 历史消息(含之前的...
519
23,251
ai-agent-book
chapter10/staged-system-prompt/runs/exp10-1-kimi-k3-20260730-v3/workspace/organize_downloads.py
.py
#!/usr/bin/env python3 """整理下载文件夹脚本。 按文件类型将下载文件夹顶层的文件(不递归子目录)移动到对应的分类子文件夹: 图片 (jpg/png/gif) -> Images 文档 (pdf/doc/txt) -> Documents 音频 (mp3/wav) -> Audio 视频 (mp4/mov) -> Videos 压缩包 (zip/rar) -> Archives 其余文件 -> Others(含隐藏文件与无扩展名文件) 用法: python organize_downloads.p...
189
5,946
ai-agent-book
chapter10/staged-system-prompt/runs/exp10-1-kimi-k3-20260730-v2/workspace/organize_downloads.py
.py
#!/usr/bin/env python3 """整理下载文件夹:按文件类型把顶层文件移动到分类子文件夹中。 用法: python organize_downloads.py [下载文件夹路径] 不传路径时默认使用 ~/Downloads。分类子文件夹(Images、Documents、Audio、 Videos、Archives、Others)会创建在下载文件夹内部,文件被移动(而非复制) 到对应子文件夹中;同名冲突时自动追加 _1、_2 序号,绝不覆盖已有文件。 """ import argparse import shutil import sys from pathlib import Path # 扩展名...
125
4,200
ai-agent-book
chapter10/staged-system-prompt/runs/exp10-1-kimi-k3-20260730-v1/workspace/organize_downloads.py
.py
#!/usr/bin/env python3 """整理下载文件夹脚本。 按文件类型将下载文件夹根目录下的文件移动到对应的分类子文件夹中: - 图片 (jpg/png/gif) -> Images - 文档 (pdf/doc/txt) -> Documents - 音频 (mp3/wav) -> Audio - 视频 (mp4/mov) -> Videos - 压缩包 (zip/rar) -> Archives - 其余类型 -> Others 行为说明: - 仅处理下载目录根层的文件,不递归进入已...
187
5,744
ai-agent-book
chapter10/staged-system-prompt/tests/test_null_question.py
.py
"""Null ask_clarifying_question.question must coerce to empty string.""" import tools as T from agent import StagedAgent from simulated_user import SimulatedUser def _bare_agent(): ag = object.__new__(StagedAgent) ag.workspace = T.Workspace() ag.logs = [] ag.verbose = False ag.stage = "requiremen...
31
851
ai-agent-book
chapter10/staged-system-prompt/tests/test_null_issues.py
.py
"""Null issues on request_revision must behave like empty list.""" from unittest.mock import MagicMock from agent import StagedAgent import tools as T def test_null_issues_like_empty(): agent = StagedAgent.__new__(StagedAgent) agent.workspace = T.Workspace() agent.revision_count = 0 agent.logs = [] ...
18
561
ai-agent-book
chapter10/staged-system-prompt/tests/test_null_tool_args.py
.py
"""回归测试:模型对必填工具参数显式传 null 时,工具分发不应崩溃。 此前 write_file 的 content 为 null 时 len(None) -> TypeError, execute_code 的 code 为 null 时在日志切片处就 None[:80] -> TypeError; 现在分发处统一把 None 归一化为空串。不实例化 StagedAgent.__init__ (避免 Config 校验 API Key),只测 _dispatch_tool 本身。 """ import tools as T from agent import StagedAgent from simulated_user...
45
1,456
ai-agent-book
chapter10/staged-system-prompt/tests/conftest.py
.py
"""Shared bootstrap for staged-system-prompt regression tests.""" import sys from pathlib import Path from types import ModuleType PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) try: import openai # noqa: F401 except ImportErro...
18
434
ai-agent-book
chapter10/talkact-reproduction/validate_campaign.py
.py
#!/usr/bin/env python3 """Validate the retained historical 10-4 campaign for current Experiment 10-3.""" from __future__ import annotations import argparse import hashlib import json import re from collections import Counter from pathlib import Path TASKS = ( "forms-insurance", "booking-flight", "webmai...
200
7,038
ai-agent-book
chapter10/generative-agents/action_arena_compat.py
.py
#!/usr/bin/env python3 """Runtime compatibility for legacy action-arena response cleanup. The pinned upstream prompt asks the model for ``{arena}``, then removes only the closing brace. Current models reliably follow that format, leaving an invalid leading brace at the spatial-memory boundary. This module wraps only...
159
5,617
ai-agent-book
chapter10/generative-agents/provider_adapter.py
.py
"""OpenAI-0.27 compatibility adapter with credential-free call receipts.""" from __future__ import annotations import datetime as dt import hashlib import json import os import re import threading import time from pathlib import Path from types import SimpleNamespace from typing import Any _SECRET_PATTERNS = ( ...
236
8,075
ai-agent-book
chapter10/generative-agents/validate_campaign.py
.py
#!/usr/bin/env python3 """Independently validate the retained historical 10-7 evidence for current Experiment 10-5.""" from __future__ import annotations import argparse import gzip import hashlib import json import re from collections import Counter from pathlib import Path ARMS = ("baseline", "custom_goal", "no_r...
268
10,823
ai-agent-book
chapter10/generative-agents/supervise_campaigns.py
.py
#!/usr/bin/env python3 """Supervise and automatically resume all long-running Experiment 10-5 arms.""" from __future__ import annotations import argparse import datetime as dt import json import os import signal import subprocess import time from pathlib import Path ARMS = ("baseline", "custom_goal", "no_reflection...
194
6,424
ai-agent-book
chapter10/generative-agents/start_supervisor.py
.py
#!/usr/bin/env python3 """Start the Experiment 10-5 supervisor in a detached process session.""" from __future__ import annotations import argparse import datetime as dt import json import os import subprocess import sys from pathlib import Path def main() -> int: parser = argparse.ArgumentParser() parser.a...
61
1,815
ai-agent-book
chapter10/generative-agents/launch_campaigns.py
.py
#!/usr/bin/env python3 """Launch or resume all Experiment 10-5 arms as detached local processes.""" from __future__ import annotations import argparse import datetime as dt import json import os import subprocess import sys from pathlib import Path ARMS = ("baseline", "custom_goal", "no_reflection") def main() ->...
87
2,786
ai-agent-book
chapter10/generative-agents/monitor_campaign.py
.py
#!/usr/bin/env python3 """Report durable Experiment 10-5 progress without reading credentials.""" from __future__ import annotations import argparse import gzip import json import os from pathlib import Path ARMS = ("baseline", "custom_goal", "no_reflection") def process_alive(pid: int | None) -> bool: if not...
86
2,735
ai-agent-book
chapter10/generative-agents/analyze_campaign.py
.py
#!/usr/bin/env python3 """Analyze memory, reflection, diffusion, and action logs for Experiment 10-5.""" from __future__ import annotations import argparse import collections import datetime as dt import json import statistics from pathlib import Path from typing import Any, Iterable ARMS = ("baseline", "custom_goa...
223
8,377
ai-agent-book
chapter10/generative-agents/package_evidence.py
.py
#!/usr/bin/env python3 """Create a compact, complete, reviewable Experiment 10-5 evidence package.""" from __future__ import annotations import argparse import gzip import hashlib import json import os import platform import shutil import subprocess import sys from pathlib import Path ARMS = ("baseline", "custom_go...
166
6,273
ai-agent-book
chapter10/generative-agents/judge_plausibility.py
.py
#!/usr/bin/env python3 """Run arm-blind Anthropic plausibility judgments for baseline vs ablation.""" from __future__ import annotations import argparse import datetime as dt import hashlib import json import os import statistics import time import urllib.error import urllib.request from pathlib import Path from typi...
329
12,655
ai-agent-book
chapter10/generative-agents/run_campaign.py
.py
#!/usr/bin/env python3 """Checkpointed runner for the pinned Stanford Generative Agents experiment.""" from __future__ import annotations import argparse import csv import datetime as dt import gzip import json import os import queue import re import shutil import subprocess import sys import threading import time fr...
625
21,904
ai-agent-book
chapter10/generative-agents/tests/test_judge_plausibility.py
.py
from __future__ import annotations import json import pytest from judge_plausibility import ( DIMENSIONS, evenly_sample, load_canonical_judgments, parse_json_object, ) def test_evenly_sample_keeps_endpoints(): assert evenly_sample(list(range(10)), 4) == [0, 3, 6, 9] assert evenly_sample([1,...
48
1,530
ai-agent-book
chapter10/generative-agents/tests/test_provider_adapter.py
.py
from __future__ import annotations import json import sys from types import SimpleNamespace from provider_adapter import ReceiptRecorder, install class Response(dict): def to_dict_recursive(self): return dict(self) def test_recorder_materializes_zero_call_checkpoint(tmp_path): receipt = tmp_path /...
155
5,004
ai-agent-book
chapter10/generative-agents/tests/test_campaign_storage.py
.py
from __future__ import annotations import json from pathlib import Path from supervise_campaigns import live_receipt_has_error def test_runner_creates_movement_directory_after_fork(): source = Path(__file__).resolve().parents[1] / "run_campaign.py" text = source.read_text(encoding="utf-8") constructor =...
42
1,628
ai-agent-book
chapter10/generative-agents/tests/test_runner_helpers.py
.py
from __future__ import annotations import gzip import json import pytest from action_arena_compat import normalize_action_arena from run_campaign import ( CUSTOM_CURRENTLY, ValidatedZero, normalize_task_decomp_response, quarantine_artifact, receipt_summary, safe_task_decomp_generate, vali...
194
6,483
ai-agent-book
chapter10/generative-agents/tests/test_validate_campaign.py
.py
from __future__ import annotations from validate_campaign import ( canonical_provider_receipt, compatibility_correction_valid, positive_provider_usage, ) def test_positive_provider_usage_ignores_nested_token_details(): row = { "response": { "usage": { "prompt_token...
42
1,336
ai-agent-book
chapter10/generative-agents/tests/conftest.py
.py
from __future__ import annotations import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))
11
182
ai-agent-book
chapter10/generative-agents/compat/utils.py
.py
"""Runtime configuration overlay for the pinned Generative Agents source. The upstream project asks users to put a plaintext API key in its ``utils.py``. Experiment 10-5 instead imports this overlay ahead of the upstream source and reads credentials exclusively from the environment. """ from __future__ import annotat...
29
853
ai-agent-book
agentbook/__init__.py
.py
"""Shared packaging and plumbing for the ai-agent-book companion experiments. This package exists so the repo can declare its dependencies once (see the root ``pyproject.toml``) instead of repeating them across per-project ``requirements.txt`` files. Install what a chapter needs:: pip install -e ".[ch1]" # c...
20
689
ai-agent-book
agentbook/providers/resolution.py
.py
"""Resolution policy: turning a provider name into a usable backend. This module owns the *rules* -- which credential wins, when to reroute through OpenRouter, what to do when nothing is configured. The registry owns the data those rules operate on. The precedence chain is deliberately expressed as one readable seque...
192
7,731
ai-agent-book
agentbook/providers/legacy.py
.py
"""Backwards-compatible shim for the pre-registry chapter helper. Before the shared registry existed, three chapter experiments each carried their own copy of ``resolve_llm_backend``. It is still imported by three chapter modules and called by two of them, so it stays until all of them are migrated: * ``chapter1/web-...
76
3,015
ai-agent-book
agentbook/providers/models.py
.py
"""Dataclasses describing providers and resolved backends. This module is the leaf of the package's dependency graph: it defines the two value types the rest of the package builds on, and imports nothing from its siblings. """ from __future__ import annotations import os from dataclasses import dataclass __all__ = ...
105
3,904
ai-agent-book
agentbook/providers/__init__.py
.py
"""Single source of truth for LLM provider resolution. Every chapter experiment talks to an OpenAI-compatible endpoint. What differs per provider is only the base URL, the default model id, and which environment variable holds the key -- so all of that lives here instead of being repeated in each experiment. Typical ...
69
2,232
ai-agent-book
agentbook/providers/registry.py
.py
"""The provider registry: which backends exist and what they are called. This module is pure data plus lookup. Adding a provider means adding one entry to :data:`PROVIDERS` and nothing else -- chapter CLIs build their ``--provider`` choices from :data:`SUPPORTED_PROVIDERS`, so a new entry becomes selectable without to...
175
6,303
ai-agent-book
agentbook/providers/openrouter.py
.py
"""OpenRouter endpoint constants and model-id mapping. OpenRouter is the universal fallback: it speaks the OpenAI protocol and hosts models from many vendors, so any chapter can run against it with a single key. The catch is that it namespaces model ids (``openai/gpt-4o`` rather than ``gpt-4o``), which is what :func:`...
133
5,058
ai-agent-book
book-en/fit_svg_text.py
.py
"""Repair text overflow in checked-in book SVGs (in place). This tool applies the svg_lib.fit_overflow width model to any SVG on disk, shrinking only the font-size of text runs that spill outside their containing rectangle or the canvas. It is safe (positions are never moved) and idempotent (re-running makes no furthe...
45
1,310
ai-agent-book
chapter1/learning-from-experience/quick_demo.py
.py
#!/usr/bin/env python3 """ Quick demo showing the LLM learning process in detail. This script runs a simplified experiment to demonstrate how LLMs learn from experience. """ import os import sys from pathlib import Path from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() # Add p...
164
5,722
ai-agent-book
chapter1/learning-from-experience/llm_agent.py
.py
""" LLM-based Agent using In-Context Learning with the Kimi (Moonshot) API. This demonstrates how LLMs can generalize through reasoning without extensive training. Default model is Kimi K3 (matching 实验 7-2 in the book); override via the `model` argument or the MOONSHOT_MODEL environment variable. """ import os import ...
640
25,848
ai-agent-book
chapter1/learning-from-experience/finalize_experiment_7_2.py
.py
#!/usr/bin/env python3 """Finalize a completed Experiment 7-2 campaign without repeating API calls.""" from __future__ import annotations import argparse import json import platform import sys from datetime import datetime, timezone from pathlib import Path from run_experiment_7_2 import ROOT, _git_revision, _sha256...
179
7,739
ai-agent-book
chapter1/learning-from-experience/test_experiment_7_2_evidence.py
.py
import json from types import SimpleNamespace from experiment import ExperimentRunner from game_environment import TreasureHuntGame from llm_agent import LLMAgent from run_experiment_7_2 import _write_json class _Usage: total_tokens = 17 def model_dump(self): return {"prompt_tokens": 10, "completion...
99
3,384
ai-agent-book
chapter1/learning-from-experience/run_experiment_7_2.py
.py
#!/usr/bin/env python3 """Run and retain the exact real Experiment 7-2 comparison. The manuscript compares 10,000 deterministic Q-learning episodes with Kimi K3's first attempt in the same treasure-hunt environment. A failed manuscript hypothesis is still a completed experiment; acceptance therefore verifies the proto...
256
9,687
ai-agent-book
chapter1/learning-from-experience/game_environment.py
.py
""" Text-based treasure hunt game with hidden mechanics. Inspired by Shunyu Yao's insights on reasoning and generalization in AI. """ import random from typing import Dict, List, Tuple, Optional, Set from dataclasses import dataclass, field from enum import Enum class ItemType(Enum): KEY = "key" WEAPON = "we...
517
21,119
ai-agent-book
chapter1/learning-from-experience/demo.py
.py
#!/usr/bin/env python3 """ Interactive demo to play the game manually or watch agents play. """ import os import sys from pathlib import Path from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() # Add parent directory to path for imports sys.path.append(str(Path(__file__).parent)...
218
6,670
ai-agent-book
chapter1/learning-from-experience/experiment.py
.py
""" Experiment runner to compare traditional RL vs LLM-based in-context learning. This replicates the key insights from "The Second Half" blog post. """ import os import json import time import random import argparse from datetime import datetime from typing import Dict, Any, List import numpy as np import matplotlib....
656
26,925
ai-agent-book
chapter1/learning-from-experience/rl_agent.py
.py
""" Traditional Reinforcement Learning Agent using Q-learning. This demonstrates the classical RL approach that requires extensive training. """ import numpy as np import pickle from collections import defaultdict from typing import Dict, List, Tuple, Any import random from game_environment import TreasureHuntGame c...
405
15,263
ai-agent-book
chapter1/learning-from-experience/tests/test_rl_agent_empty_victories.py
.py
""" Test suite locking out ZeroDivisionError in QLearningAgent.train when computing victory_rate on an empty episode_victories list. """ from rl_agent import QLearningAgent def test_q_learning_agent_train_empty_victories_snapshot(): """ Ensure checkpoint victory_rate calculation does not raise ZeroDivisionEr...
31
927