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
chapter6/agent-with-event-trigger/server.py
.py
""" Event Server - FastAPI version with native async support for MCP tools """ import os import logging from datetime import datetime, timedelta from typing import Dict, Any, Optional from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException, BackgroundTasks from pydantic import BaseModel f...
468
15,159
ai-agent-book
chapter6/agent-with-event-trigger/example_with_mcp.py
.py
""" Example demonstrating the Event-Triggered Agent with MCP tools """ import os import asyncio from dotenv import load_dotenv from agent import EventTriggeredAgent, SystemHintConfig, resolve_provider_and_key from event_types import Event, EventType # Load environment variables load_dotenv() async def main(): "...
104
2,949
ai-agent-book
chapter6/agent-with-event-trigger/server_fastapi.py
.py
""" Event Server - FastAPI version with native async support for MCP tools """ import os import logging from datetime import datetime, timedelta from typing import Dict, Any, Optional from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException, BackgroundTasks from pydantic import BaseModel f...
417
12,895
ai-agent-book
chapter6/agent-with-event-trigger/unipile_mailbox_experiment.py
.py
#!/usr/bin/env python3 """Run Chapter 4 Experiment 4-5 against a real Unipile mailbox. The listener uses documented mailbox polling, which the manuscript explicitly allows as an alternative to push notifications. It never substitutes local mail files for provider objects. Missing/invalid credentials produce a durable ...
761
35,690
ai-agent-book
chapter6/agent-with-event-trigger/test_unipile_mailbox_experiment.py
.py
"""Offline contract tests; these are not substitutes for the live campaign receipt.""" from __future__ import annotations import importlib.util import json import sys from datetime import datetime, timezone from pathlib import Path import httpx import pytest HERE = Path(__file__).resolve().parent MODULE_PATH = HERE...
139
6,505
ai-agent-book
chapter6/agent-with-event-trigger/client.py
.py
""" Event Client - Send test events to the event-triggered agent """ import requests import json import time import argparse from datetime import datetime from event_types import EventType class EventClient: """Client to send events to the event-triggered agent server""" def __init__(self, server_url: s...
385
12,968
ai-agent-book
chapter6/agent-with-event-trigger/event_loop_demo.py
.py
""" event_loop_demo.py —— 事件驱动 Agent 的端到端演示(单进程、可离线运行) 本章"事件驱动的异步 Agent"一节指出:真正的"主动服务"不仅需要 Agent 能定时 检查世界,更需要世界能主动通知 Agent。本脚本用最小的代码把这一点跑起来—— 1. 注册若干"事件触发器"(trigger source),每个触发器在后台线程里运行, 在事件真正发生的那一刻把一个结构化 Event 推入统一的事件队列: - 一次性定时器 OneShotTimer —— 对应书中 set_timer 的"一次性定时器" - 循环定时器 Recurring...
398
17,593
ai-agent-book
chapter6/agent-with-event-trigger/event_types.py
.py
""" Event types for the event-triggered agent system """ from dataclasses import dataclass, field from datetime import datetime from enum import Enum from typing import Dict, Any, Optional class EventType(Enum): """Types of events that can trigger agent actions""" # External input events WEB_MESSAGE = "w...
100
3,875
ai-agent-book
chapter6/agent-with-event-trigger/agent.py
.py
""" Event-Triggered AI Agent with System Hints An agent that responds to events from various sources while maintaining all the system hint features from the original implementation. """ import json import os import sys import subprocess import platform import logging import concurrent.futures from typing import List, ...
1,305
56,892
ai-agent-book
chapter6/agent-with-event-trigger/tests/test_server_null_result_lists.py
.py
""" Test suite locking out TypeError in event server response formatting when handle_event returns a result dictionary with tool_calls or todo_list set to None. """ def test_server_result_formatting_handles_null_lists(): """ Ensure event response dictionary formats tool_calls_count and todo_items without TypeE...
31
1,006
ai-agent-book
chapter6/agent-with-event-trigger/tests/test_env_int.py
.py
"""Regression test: malformed AGENT_PORT must not crash server startup. Both server variants parsed AGENT_PORT with bare int() (one inside build_parser's default, one in main), so AGENT_PORT=abc crashed with an unhandled ValueError at startup. They now fall back to 8000 with a warning. """ import os import sys sys.pa...
37
1,179
ai-agent-book
chapter6/agent-with-event-trigger/tests/test_code_interpreter.py
.py
"""Regression tests for the code interpreter's execution namespace.""" import importlib.util import sys import types import unittest from pathlib import Path from unittest.mock import patch def _load_agent_module(): openai = types.ModuleType("openai") openai.OpenAI = type("OpenAI", (), {}) mcp = types.M...
74
2,128
ai-agent-book
chapter6/agent-with-event-trigger/tests/conftest.py
.py
"""Test import bootstrap for the agent-with-event-trigger experiment.""" from pathlib import Path import sys EXPERIMENT_ROOT = Path(__file__).resolve().parents[1] if str(EXPERIMENT_ROOT) not in sys.path: sys.path.insert(0, str(EXPERIMENT_ROOT))
10
252
ai-agent-book
chapter6/agent-with-event-trigger/tests/manual/demo.py
.py
""" Simple demo script to test the event-triggered agent locally without needing the server/client architecture """ import os import sys from pathlib import Path EXPERIMENT_ROOT = Path(__file__).resolve().parents[2] if str(EXPERIMENT_ROOT) not in sys.path: sys.path.insert(0, str(EXPERIMENT_ROOT)) from agent imp...
138
4,622
ai-agent-book
chapter6/controllable-tts/evaluate_audio_quality.py
.py
#!/usr/bin/env python3 """Run a blinded, position-balanced audio study for Experiment 9-5. The three clips already come from real Fish Audio S1 calls. This program asks a real audio-capable Gemini model to listen to them in three different orders, validates every returned score/evidence field, and writes a receipt wi...
483
21,769
ai-agent-book
chapter6/controllable-tts/validate_artifacts.py
.py
#!/usr/bin/env python3 """Validate real Fish S1 Experiment 9-5 media without making new API calls.""" from __future__ import annotations import hashlib import json import platform import subprocess from datetime import datetime, timezone from pathlib import Path from evaluate_audio_quality import validate_study HER...
165
7,745
ai-agent-book
chapter6/controllable-tts/test_fish_s1.py
.py
import json import subprocess import pytest from evaluate_audio_quality import DIMENSIONS, OUTPUTS, PERMUTATIONS, aggregate, validate_response from markup import parse from tts import concat_mp3, make_silence from voice_library import EMOTIONS, SPEEDS, STYLES, load_voice_library def test_native_s1_nonverbal_events_...
92
3,283
ai-agent-book
chapter6/controllable-tts/voice_library.py
.py
"""24-file Fish Audio S1 reference-voice library and its builder.""" from __future__ import annotations import hashlib import json import os import subprocess from itertools import product from pathlib import Path from typing import Any EMOTIONS = { "neutral": "calm", "happy": "happy", "frustrated": "fru...
127
5,158
ai-agent-book
chapter6/controllable-tts/demo.py
.py
#!/usr/bin/env python3 """Experiment 9-5: Fish Audio S1 + a 24-reference voice library.""" from __future__ import annotations import argparse import json import os import re import subprocess from datetime import datetime, timezone from pathlib import Path from dotenv import load_dotenv from markup import parse fro...
97
3,723
ai-agent-book
chapter6/controllable-tts/markup.py
.py
""" 控制标记解析器(Control Markup Parser) ======================================== 把带控制标记的文本解析成一串「片段」,每个片段要么是一段需要用某条参考语音 合成的语音(speech),要么是一段静音停顿(silence)。这一步对应书中「执行层 解析标记并映射到对应的参考语音」。 支持两类标记: 1) 状态标记(持续生效,直到被下一个同类标记改变) [EMO:neutral|happy|frustrated|thinking] 或 [情感=中性|高兴|沮丧|思考] [SPEED:normal|fast|slow] / [S...
225
9,579
ai-agent-book
chapter6/controllable-tts/build_reference_library.py
.py
#!/usr/bin/env python3 import argparse import os from pathlib import Path from dotenv import load_dotenv from voice_library import DEFAULT_LIBRARY_DIR, build_reference_library load_dotenv(Path(__file__).parent / ".env") parser = argparse.ArgumentParser(description="Build 24 real Fish Audio S1 reference clips") pars...
20
864
ai-agent-book
chapter6/controllable-tts/tts.py
.py
"""Fish Audio S1 zero-shot cloning execution layer.""" from __future__ import annotations import os import subprocess import tempfile from pathlib import Path from typing import Any from voice_library import DEFAULT_MANIFEST, load_voice_library, profile_key MODEL = "s1" def _session(): from fish_audio_sdk imp...
125
4,101
ai-agent-book
chapter6/controllable-tts/tests/conftest.py
.py
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))
8
169
ai-agent-book
chapter6/async-agent/runtime.py
.py
"""Flux 异步 Agent 运行时(实验 4-6 核心)。 实现设计文档第 5 节的事件处理循环,重点覆盖实验 4-6 的四个能力: 1. 异步工具执行:run_terminal_command 立即返回占位符,任务在后台跑。 2. 事件队列与批量处理:非紧急事件进 pending,异步结果到达时一次性批量追加。 3. 打断机制:用户"取消/停止"立即取消当前 turn + 所有异步工具,并留痕。 4. 并行工具的取消与状态查询:query_task / cancel_task 按 ID 操作; 异步完成后以"新事件"把真实结果注入对话。 架构(三个协程协作,全部基于 asyncio 单线程): ...
407
18,970
ai-agent-book
chapter6/async-agent/analysis_worker.py
.py
#!/usr/bin/env python3 """Bounded analysis executable used by the Experiment 4-6 task manager.""" from __future__ import annotations import argparse import hashlib import json import re import time from pathlib import Path def analyze(path: Path, job: str) -> dict: data = path.read_bytes() text = data.decod...
55
1,914
ai-agent-book
chapter6/async-agent/test_real_tasks.py
.py
"""Contract tests for real subprocess-backed Experiment 4-6 tasks.""" from __future__ import annotations import asyncio import hashlib import json import os import sys from pathlib import Path import pytest HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) import tasks def test_unapproved_comm...
83
2,796
ai-agent-book
chapter6/async-agent/test_checkpoint_robustness.py
.py
""" Test suite locking out TypeError and FileNotFoundError in AgentRuntime checkpointing when tasks is None, trajectory is None, or destination directory doesn't exist. """ import json import os import sys import tempfile from unittest.mock import MagicMock sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)...
101
3,597
ai-agent-book
chapter6/async-agent/demo.py
.py
"""实验 4-6 命令行入口:带并行执行、打断/取消与状态管理的异步 Agent。 本脚本提供两类演示,用子命令区分: 【离线演示】不需要任何 API key,直接测量异步运行时的底层行为—— python demo.py parallel 并行 vs 串行工具调用的墙钟时间对比(打印加速比) python demo.py interrupt 长任务运行中被打断/取消,随后系统恢复 python demo.py state Agent 状态检查点持久化 + 跨会话恢复并校验 python demo.py offline 依次运行上面全部...
272
12,014
ai-agent-book
chapter6/async-agent/run_real_experiment.py
.py
#!/usr/bin/env python3 """Run all four Experiment 4-6 scenarios with real child processes.""" from __future__ import annotations import argparse import asyncio import hashlib import json import re import time from datetime import datetime, timezone from pathlib import Path from typing import Any import tasks from ta...
424
18,973
ai-agent-book
chapter6/async-agent/async_demos.py
.py
"""离线演示:不依赖任何 LLM / API key,直接驱动异步运行时的底层原语。 `demo.py` 里的四个「场景」需要真实 LLM 做决策;本模块则把实验 4-6 的三项核心 异步能力单独拎出来,用可测量、可复现的方式演示,**无需联网、无需 API key**: - demo_parallel :并行 vs 串行工具调用的【墙钟时间】对比(真实测量,打印加速比)。 - demo_interrupt :长任务运行中被【打断/取消】,随后系统【恢复】并接受新任务。 - demo_state :Agent 状态【检查点持久化】到磁盘,再【跨会话恢复】并校验。 这三个演示共同回答「异步到底带来了什么」...
221
11,093
ai-agent-book
chapter6/async-agent/test_real_experiment.py
.py
"""Acceptance-ledger regression tests for the durable Experiment 4-6 run.""" from __future__ import annotations import copy import importlib.util import json import sys from pathlib import Path HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) PATH = HERE / "run_real_experiment.py" SPEC = importli...
104
4,412
ai-agent-book
chapter6/async-agent/tasks.py
.py
"""Real, bounded asynchronous terminal jobs for Experiment 4-6. Commands are parsed without a shell and resolved through an explicit allowlist to ``analysis_worker.py``. Each job is a real child process whose stdout drives progress. Cancellation terminates that OS process; completion returns metrics computed from a re...
283
11,699
ai-agent-book
chapter6/async-agent/events.py
.py
"""事件模型(对应设计文档中的 Event / Trajectory 概念)。 Flux 把 Agent 的一切经历都抽象成"事件",按时间顺序追加到轨迹(trajectory)里。 本文件定义事件类型、事件对象,以及"事件紧急度"的判定逻辑——这是实验 4-6 里 "批量处理 vs 立即打断"两种处理机制的分类依据。 """ from __future__ import annotations import time from dataclasses import dataclass, field from typing import Optional class EventType: """事件类型常量(对应...
92
4,135
ai-agent-book
chapter6/async-agent/tests/test_tasks_env.py
.py
"""回归测试:FLUX_TICK_REAL 等浮点环境变量非法时不得让模块导入崩溃。 tasks.py 原来在模块导入时用裸 float() 解析 FLUX_TICK_REAL, FLUX_TICK_REAL=abc 会让整个演示脚本以 ValueError 崩溃;现在回退到默认值并打印警告。 """ import importlib import os import sys sys.path.insert(0, os.path.dirname(__file__)) import tasks def test_env_float_falls_back_on_malformed(monkeypatch, capsys): ...
36
1,191
ai-agent-book
chapter6/async-agent/tests/conftest.py
.py
"""Test import bootstrap for the async-agent experiment.""" from pathlib import Path import sys EXPERIMENT_ROOT = Path(__file__).resolve().parents[1] if str(EXPERIMENT_ROOT) not in sys.path: sys.path.insert(0, str(EXPERIMENT_ROOT))
10
239
ai-agent-book
chapter6/gemini-xlerobot-navigation/xlerobot_tool_contract.py
.py
"""Book-local semantic tool contract for the optional RoboCrew/XLeRobot run. The pinned navigation checkout exposes base-motion helpers, not a stable semantic arm API. This module is therefore an explicit adapter boundary: the local GPU experiment validates the contract, while a hardware integrator must map each prim...
47
2,041
ai-agent-book
chapter6/gemini-xlerobot-navigation/validate_evidence.py
.py
#!/usr/bin/env python3 """Validate the local GPU desktop-planning evidence for Experiment 9-9.""" from __future__ import annotations import argparse import hashlib import json import sys from pathlib import Path from typing import Any EXPECTED_TOOL_NAMES = ["observe_scene", "pick", "place", "verify_state", "stop"] ...
97
5,076
ai-agent-book
chapter6/gemini-xlerobot-navigation/desktop_planner.py
.py
#!/usr/bin/env python3 """Experiment 9-9: desktop manipulation planning with a local GPU backend. The local run keeps the RoboCrew-style tool contract and the XLeRobot adapter boundary, but executes against a deterministic tabletop simulator. This makes planner, postcondition, retry and short-horizon world-model beha...
286
14,793
ai-agent-book
chapter6/gemini-xlerobot-navigation/test_validator.py
.py
import json import unittest from pathlib import Path from validate_evidence import validate class EvidenceGateTests(unittest.TestCase): def test_local_gpu_evidence_is_accepted(self): run = Path(__file__).parent / "validation" / "runs" / "local-gpu" / "evidence.json" if not run.is_file(): ...
33
1,713
ai-agent-book
chapter6/computer-use-open-model/evidence.py
.py
"""Small, dependency-free helpers for retaining Computer Use evidence.""" from __future__ import annotations import copy import hashlib import json import shutil from pathlib import Path from typing import Any def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: ...
75
2,768
ai-agent-book
chapter6/computer-use-open-model/main.py
.py
"""Run a visual Browser Use trajectory through an open-model API endpoint.""" from __future__ import annotations import argparse import asyncio import hashlib import importlib.metadata import json import os import sys import traceback from datetime import datetime, timezone from pathlib import Path from typing import...
274
9,580
ai-agent-book
chapter6/computer-use-open-model/validate_run.py
.py
"""Validate a retained open-model Computer Use run without another model call.""" from __future__ import annotations import argparse import json import re from pathlib import Path from typing import Any from evidence import sha256_file, write_json, write_manifest SECRET_PATTERNS = ( re.compile(r"sk-or-v1-[A-Za-...
229
8,345
ai-agent-book
chapter6/computer-use-open-model/config.py
.py
"""Configuration for the provider-neutral Computer Use companion.""" from __future__ import annotations from collections.abc import Mapping from dataclasses import dataclass from os import environ as process_environ from urllib.parse import urlparse DEFAULT_BASE_URL = "https://openrouter.ai/api/v1" DEFAULT_MODEL = "...
80
2,717
ai-agent-book
chapter6/computer-use-open-model/tests/test_evidence.py
.py
import json from pathlib import Path from evidence import retain_step_screenshots, sha256_file, write_json, write_manifest def test_screenshots_are_copied_and_history_is_rewritten(tmp_path: Path) -> None: temporary_screenshot = tmp_path / "temporary.png" temporary_screenshot.write_bytes(b"not-a-real-png-but-...
36
1,481
ai-agent-book
chapter6/computer-use-open-model/tests/test_config.py
.py
import pytest from config import DEFAULT_BASE_URL, DEFAULT_MODEL, ConfigError, resolve_endpoint def test_openrouter_reference_route() -> None: endpoint = resolve_endpoint({"OPENROUTER_API_KEY": "secret"}) assert endpoint.api_key == "secret" assert endpoint.api_key_env == "OPENROUTER_API_KEY" assert e...
44
1,567
ai-agent-book
chapter6/computer-use-open-model/tests/conftest.py
.py
import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
5
98
ai-agent-book
chapter6/end-to-end-speech/prepare_fixtures.py
.py
#!/usr/bin/env python3 """Regenerate the small synthetic WAV fixtures used by Experiment 9-4.""" from __future__ import annotations import shutil import subprocess from pathlib import Path HERE = Path(__file__).resolve().parent FIXTURES = HERE / "fixtures" UTTERANCES = { "boxes-79.wav": (145, 50, "A shop has t...
39
1,307
ai-agent-book
chapter6/end-to-end-speech/speech_model.py
.py
"""Native local MiniCPM-o 4.5 inference for Experiment 9-4.""" from __future__ import annotations import hashlib import time from dataclasses import asdict, dataclass from pathlib import Path from typing import Any MODEL_ID = "openbmb/MiniCPM-o-4_5" MODEL_REVISION = "1f761131fa83f5ed3cd6f2f22b225c4501d154fa" @dat...
215
7,250
ai-agent-book
chapter6/end-to-end-speech/validate_evidence.py
.py
#!/usr/bin/env python3 """Fail-closed validation for a retained Experiment 9-4 local run.""" from __future__ import annotations import argparse import json from pathlib import Path from speech_model import MODEL_ID, MODEL_REVISION, sha256_file HERE = Path(__file__).resolve().parent def validate(evidence_path: Pa...
68
2,717
ai-agent-book
chapter6/end-to-end-speech/demo.py
.py
#!/usr/bin/env python3 """Run the local MiniCPM-o 4.5 direct-vs-self-cascade campaign.""" from __future__ import annotations import argparse import json import platform import re import subprocess from datetime import datetime, timezone from pathlib import Path from typing import Any from speech_model import MODEL_I...
166
6,571
ai-agent-book
chapter6/end-to-end-speech/tests/test_speech_model.py
.py
from pathlib import Path import pytest from speech_model import MiniCPMOClient, sha256_file def test_sha256_file(tmp_path): path = tmp_path / "sample" path.write_bytes(b"abc") assert sha256_file(path) == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" def test_inference_requires_loa...
26
840
ai-agent-book
chapter6/end-to-end-speech/tests/test_demo.py
.py
import pytest from demo import load_cases, matches_expected def test_expected_match_uses_word_boundaries(): assert matches_expected("The answer is 79.", ["79"]) assert matches_expected("FAST", ["fast"]) assert not matches_expected("The answer is 179.", ["79"]) def test_case_manifest_validation(tmp_path...
17
485
ai-agent-book
chapter6/end-to-end-speech/tests/test_validate_evidence.py
.py
import json import wave from pathlib import Path from speech_model import MODEL_ID, MODEL_REVISION, sha256_file from validate_evidence import validate def test_complete_evidence_passes(tmp_path): wav = tmp_path / "answer.wav" with wave.open(str(wav), "wb") as handle: handle.setnchannels(1) ha...
54
1,700
ai-agent-book
chapter6/xlerobot-teleoperation/preflight.py
.py
#!/usr/bin/env python3 """Read-only preflight for the pinned Experiment 9-8 reproduction track.""" from __future__ import annotations import argparse import importlib.util import json import platform import subprocess from datetime import datetime, timezone from pathlib import Path COMMIT = "3d14695e40c9c68229c0aacf...
78
3,741
ai-agent-book
chapter6/xlerobot-teleoperation/validate_evidence.py
.py
#!/usr/bin/env python3 """Validate the honest local GPU evidence for Experiment 9-8.""" from __future__ import annotations import argparse import hashlib import json import sys from pathlib import Path from typing import Any def file_sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") ...
77
3,222
ai-agent-book
chapter6/xlerobot-teleoperation/teleop.py
.py
#!/usr/bin/env python3 """Experiment 9-8: local GPU expert-control upper-bound benchmark. This is the reproducible, non-actuating companion for the chapter. It uses a small batched tabletop simulator to measure what a perfect teleoperator-like controller can do. The pinned XLeRobot hardware path remains an optional,...
147
7,095
ai-agent-book
chapter6/xlerobot-teleoperation/test_validator.py
.py
import json import subprocess import sys import unittest from pathlib import Path from validate_evidence import validate class EvidenceGateTests(unittest.TestCase): def test_local_gpu_evidence_is_accepted(self): run = Path(__file__).parent / "validation" / "runs" / "local-gpu" / "evidence.json" i...
39
1,479
ai-agent-book
chapter6/streaming-speech/test_streaming.py
.py
import numpy as np from qwen2_streaming import parse_response from whisper_baseline import energy_vad_endpoints, energy_vad_events def test_qwen_json_and_native_event_token_parsing(): transcript, events = parse_response('{"transcript":"你好","acoustic_events":["noise", "<|laughter|>"]}') assert transcript == "...
27
979
ai-agent-book
chapter6/streaming-speech/test_official_experiment.py
.py
import hashlib import json import re from pathlib import Path ROOT = Path(__file__).resolve().parent RUN = ROOT / "validation" / "runs" / "exp9-3-qwen2audio-whisper-provenance-20260730-v3" def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while chunk := ha...
82
3,642
ai-agent-book
chapter6/streaming-speech/prepare_scenarios.py
.py
#!/usr/bin/env python3 """Create normal, long-pause and background-noise variants from one WAV.""" import argparse import subprocess from pathlib import Path parser = argparse.ArgumentParser() parser.add_argument("source", type=Path) parser.add_argument("output_dir", type=Path) args = parser.parse_args() args.output_...
41
1,525
ai-agent-book
chapter6/streaming-speech/run_official_experiment.py
.py
#!/usr/bin/env python3 """Run Experiment 9-3 unchanged and bind local-model/audio/source provenance.""" from __future__ import annotations import argparse import hashlib import json import os import re import subprocess import sys import time from datetime import datetime, timezone from pathlib import Path from typin...
312
11,780
ai-agent-book
chapter6/streaming-speech/test_whisper_baseline.py
.py
import sys from pathlib import Path import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "chapter9" / "streaming-speech")) from whisper_baseline import energy_vad_events def test_energy_vad_events_handles_empty_audio_array(): """Empty or zero-length audio array must return an empt...
16
486
ai-agent-book
chapter6/streaming-speech/interruption_manager.py
.py
"""Duplex Interruption Manager for Real-Time Streaming Speech Systems. Monitors real-time Voice Activity Detection (VAD) energy signals during active TTS audio playback, enabling instant audio stream cancellation upon user barge-in, dialogue context truncation, and re-planning trigger generation. """ from __future__ ...
386
16,095
ai-agent-book
chapter6/streaming-speech/whisper_baseline.py
.py
"""VAD + Whisper comparison baseline for Experiment 9-3.""" from __future__ import annotations import time from dataclasses import asdict, dataclass from pathlib import Path try: import librosa import soundfile as sf except ImportError: librosa = None sf = None import numpy as np @dataclass class B...
142
5,331
ai-agent-book
chapter6/streaming-speech/demo.py
.py
#!/usr/bin/env python3 """Run Qwen2-Audio growing-prefix perception against VAD + Whisper.""" from __future__ import annotations import argparse import hashlib import importlib.metadata import json import os import platform import subprocess import unicodedata from datetime import datetime, timezone from pathlib impo...
221
9,733
ai-agent-book
chapter6/streaming-speech/qwen2_streaming.py
.py
"""Qwen2-Audio growing-prefix inference for Experiment 9-3.""" from __future__ import annotations import json import ast import re import time from dataclasses import asdict, dataclass from pathlib import Path from typing import Any, Callable import librosa EVENT_ALIASES = { "noise": "<|noise|>", "backgrou...
188
6,995
ai-agent-book
chapter6/rgb-sim2real-grasping/pipeline.py
.py
#!/usr/bin/env python3 """Experiment 9-10: RGB domain-transfer benchmark on the local GPU. The benchmark is intentionally self-contained. It trains a small RGB policy on a source visual domain and evaluates it on a shifted target domain, with and without domain randomization. It is a production-grade local proxy for...
215
12,439
ai-agent-book
chapter6/rgb-sim2real-grasping/preflight.py
.py
#!/usr/bin/env python3 """Read-only, stage-aware preflight for Experiment 9-10.""" from __future__ import annotations import argparse import importlib.util import json import platform import shutil import subprocess from datetime import datetime, timezone from pathlib import Path COMMIT = "87d6c1d969f6e0ca4dc5697940...
96
5,331
ai-agent-book
chapter6/rgb-sim2real-grasping/validate_evidence.py
.py
#!/usr/bin/env python3 """Validate local GPU RGB domain-transfer evidence for Experiment 9-10.""" from __future__ import annotations import argparse import hashlib import json import sys from pathlib import Path from typing import Any def file_sha256(path: Path) -> str: digest = hashlib.sha256() with path.o...
82
3,722
ai-agent-book
chapter6/rgb-sim2real-grasping/test_validator.py
.py
import json import unittest from pathlib import Path from validate_evidence import validate class EvidenceGateTests(unittest.TestCase): def test_local_gpu_evidence_is_accepted(self): run = Path(__file__).parent / "validation" / "runs" / "local-gpu" / "evidence.json" if not run.is_file(): ...
23
1,259
ai-agent-book
book-hu/gen_ch2_figs.py
.py
#!/usr/bin/env python3 """Generate Hungarian Chapter 2 SVGs from the Chinese golden layouts. The Chinese edition owns the diagram geometry and figure numbering. Hungarian prose is explicit here instead of being assembled by the generic word-level figure localizer. Figure 2-7 is redrawn as vector artwork because the ...
536
22,622
ai-agent-book
book-hu/make_epub.py
.py
#! /usr/bin/env python3 """Generate EPUB from the Hungarian introduction.md - simpler approach""" import os import re from ebooklib import epub, ITEM_IMAGE import markdown book_dir = os.path.dirname(os.path.abspath(__file__)) # Read the markdown md_path = os.path.join(book_dir, "introduction.md") with open(md_path, ...
97
3,463
ai-agent-book
book-hu/fix_bold_to_quotes.py
.py
#! /usr/bin/env python3 """ Replace short **bold** formatting (used for terminology/keywords) with "quotes" in Hungarian translated chapters. Longer bold text (statements, formulas) stays bold. Rules: - **text** where text is 1-6 words and <= 60 chars → "text" - Longer **text** stays as **text** (formulas, emphasized ...
91
2,804
ai-agent-book
book-hu/make_full_epub.py
.py
#!/usr/bin/env python3 """Build and validate the complete Hungarian EPUB 3 edition.""" from pathlib import Path import shutil import subprocess import sys BOOK_DIR = Path(__file__).resolve().parent ROOT = BOOK_DIR.parent OUTPUT = BOOK_DIR / "AI-Agent-Book_HU.epub" CHAPTERS = [ "introduction.md", *(f"chapter{...
80
2,170
ai-agent-book
book-hu/convert_svg_to_png.py
.py
#! /usr/bin/env python3 """Convert all SVG images to PNG for better e-book reader compatibility""" import os import re book_dir = os.path.dirname(os.path.abspath(__file__)) img_dir = os.path.join(book_dir, "images") # Convert SVG files to PNG import cairosvg converted = 0 for fname in sorted(os.listdir(img_dir)): ...
61
1,861
ai-agent-book
book-hu/upload_epub.py
.py
#! /usr/bin/env python3 """Upload EPUB to GitHub fork""" import json, base64, sys, requests sys.stdout.reconfigure(line_buffering=True) TOKEN = "ghp_jy…4OXJ" OWNER = "barmivalami0-ux" REPO = "ai-agent-book" FILE = "/home/leno/.openclaw/workspace/book-hu/AI-Agent-Book_HU.epub" HEADERS = {"Authorization": f"token {TOKEN...
85
2,861
ai-agent-book
chapter10/voice-werewolf/test_user_simulator.py
.py
import json import sys from types import SimpleNamespace from unittest.mock import patch import pytest import demo from werewolf import agent as agent_module from werewolf.game import Judge, create_players from werewolf.roles import Role from werewolf.agent import PlayerAgent from werewolf.simulator import SimulatedU...
222
9,108
ai-agent-book
chapter10/voice-werewolf/test_exp108_validation_evidence.py
.py
import hashlib import json from pathlib import Path ROOT = Path(__file__).parent / "validation" def test_persisted_acceptance_status_does_not_claim_unrun_human_audio(): status = json.loads((ROOT / "acceptance_status_2026-07-29.json").read_text()) assert status["safety"]["phone_calls_placed"] == 0 assert...
125
6,163
ai-agent-book
chapter10/voice-werewolf/validate_simulator_run.py
.py
#!/usr/bin/env python3 """Independently recompute the simulated-user audio/action boundary from a report.""" from __future__ import annotations import argparse import hashlib import json import re from pathlib import Path from werewolf.human import HumanPlayerAgent def validate(report_path: Path) -> dict: raw ...
168
7,871
ai-agent-book
chapter10/voice-werewolf/test_witch_killed_no_poison.py
.py
import pytest from werewolf.game import Judge from werewolf.agent import PlayerAgent from werewolf.roles import Role, Faction def test_witch_killed_by_wolves_cannot_use_poison_in_same_night(): """Contract proved: Judge._witch_act prevents a Witch who was killed by wolves at night and not saved from using poison i...
30
1,184
ai-agent-book
chapter10/voice-werewolf/test_live_human.py
.py
import json import sys from types import SimpleNamespace from unittest.mock import patch import numpy as np import pytest import demo from werewolf.agent import PlayerAgent from werewolf.game import Judge, create_players from werewolf.human import HumanPlayerAgent, LiveVoiceSession from werewolf.roles import Faction,...
288
11,031
ai-agent-book
chapter10/voice-werewolf/evaluate_audio_run.py
.py
#!/usr/bin/env python3 """Direct-audio independent evaluation of simulator utterances through OpenRouter.""" from __future__ import annotations import argparse import base64 import hashlib import json import os import re import time from pathlib import Path from typing import Any from openai import OpenAI WORDS = ...
196
7,929
ai-agent-book
chapter10/voice-werewolf/demo.py
.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """实验 10-6:1 名真人通过实时 ASR/TTS 与 5-7 个 AI Agent 玩狼人杀。 配套《深入理解 AI Agent》第 10 章「实验 10-6:语音狼人杀 Agent 系统」。 本 demo 演示三件事(对应书中架构设计): 1. **多 Agent**:每个玩家 = 一个独立 LLM Agent(OpenAI,默认 gpt-5.6-luna)。 2. **信息权限控制**:法官按角色把信息投递进各 Agent 的私有上下文——狼人才知道 队友、预言家才知道查验结果、公开发言进所有人。游戏后打印审计表 + ...
497
25,761
ai-agent-book
chapter10/voice-werewolf/test_simultaneous_deaths_consensus.py
.py
import pytest from werewolf.game import Judge from werewolf.agent import PlayerAgent from werewolf.roles import Role, Faction def test_simultaneous_deaths_returns_undecided_faction(): """Contract proved: Judge._check_winner returns Faction.UNDECIDED when all wolves and good players die simultaneously. Bug lock...
21
869
ai-agent-book
chapter10/voice-werewolf/werewolf/human.py
.py
# -*- coding: utf-8 -*- """Real human player and low-latency microphone/ASR/TTS voice session.""" from __future__ import annotations import json import os import re import subprocess import tempfile import time import wave from pathlib import Path from typing import List, Optional from .agent import PlayerAgent from...
229
10,017
ai-agent-book
chapter10/voice-werewolf/werewolf/audit.py
.py
# -*- coding: utf-8 -*- """信息可见性审计(Information Visibility Audit)。 这是本实验「信息权限控制可验证」的核心工具:法官每向某个(或某些)玩家的 上下文投递一条信息时,都会在这里登记一条记录——这条信息属于哪个类别、内容 摘要是什么、**进入了谁的上下文**。游戏结束后打印这张审计表,即可客观证明 信息隔离是否正确(例如「狼人队友身份」只进狼人上下文、「预言家查验结果」只进 预言家本人上下文、「公开发言」进所有人上下文)。 """ from dataclasses import dataclass, field from typing import List @da...
44
2,014
ai-agent-book
chapter10/voice-werewolf/werewolf/simulator.py
.py
# -*- coding: utf-8 -*- """LLM-driven user simulator with a real speech round trip. The simulator is deliberately not an ordinary all-AI player. It occupies the same protected user seat as ``HumanPlayerAgent`` and receives only that seat's memory. For each turn a real LLM must call the one legal user tool. The sele...
459
19,993
ai-agent-book
chapter10/voice-werewolf/werewolf/game.py
.py
# -*- coding: utf-8 -*- """法官(主持人)Agent:代码驱动的游戏编排与信息权限控制中枢。 法官不是 LLM——它是**确定性的编排器**,负责: 1. 维护中心化游戏状态(身份、阵营、生死、阶段、历史)。 2. **信息权限控制**:决定每条信息投递给哪些玩家 Agent 的私有上下文 (狼人才知道队友、预言家才知道查验结果、公开发言进所有人),并登记审计。 3. 编排昼夜循环:夜晚(狼人刀人 → 预言家查验 → 女巫用药)→ 白天(公布死讯 → 依次发言 → 投票放逐)→ 结算胜负。 """ import random from collections import Counter f...
472
22,941
ai-agent-book
chapter10/voice-werewolf/werewolf/__init__.py
.py
# -*- coding: utf-8 -*- """实验 10-6:语音狼人杀 Agent 系统(多 Agent + 信息权限控制 + 法官编排)。"""
3
127
ai-agent-book
chapter10/voice-werewolf/werewolf/roles.py
.py
# -*- coding: utf-8 -*- """角色定义、阵营、以及每个角色的策略提示词。 狼人杀的核心是**信息不对称**:不同角色天生知道不同的信息,且拥有不同的 夜间行动能力。这里集中定义角色的元数据与提示词,供 agent.py 构造每个玩家 Agent 的 system prompt。 """ from enum import Enum class Role(str, Enum): """游戏中的四种角色。""" WEREWOLF = "狼人" SEER = "预言家" WITCH = "女巫" VILLAGER = "村民" class Faction(str, ...
71
3,427
ai-agent-book
chapter10/voice-werewolf/werewolf/strategy_audit.py
.py
"""Post-game, evidence-based acceptance audit for role strategy.""" from __future__ import annotations import json import os REQUIRED_CRITERIA = ( "werewolf_concealment", "seer_timing_and_evidence", "villager_logical_reasoning", "role_consistency", ) VALID_STATUSES = {"pass", "fail", "insufficient"}...
165
7,331
ai-agent-book
chapter10/voice-werewolf/werewolf/agent.py
.py
# -*- coding: utf-8 -*- """玩家 Agent:每个玩家 = 一个独立的 LLM Agent,拥有**严格隔离的私有上下文**。 信息隔离的实现要点: - 每个 PlayerAgent 只维护自己的 `memory`(一串它「观察到 / 被告知」的事件)。 - 法官(judge.py)决定把哪条信息推给哪个 Agent 的 memory——狼人才会收到「队友 身份」,预言家才会收到「查验结果」,公开发言才会推给所有人。 - Agent 每次思考(发言 / 投票 / 用技能)时,只能看到自己 memory 里的内容, 因此不可能「偷看」到本不该看到的信息。这就是信息权限控制的落点。 离线(--off...
332
17,461
ai-agent-book
chapter10/voice-werewolf/werewolf/tts.py
.py
# -*- coding: utf-8 -*- """可选的语音合成(TTS)——把玩家公开发言合成为语音。 语音是本实验的**可选增强**,不是跑通的必需:默认文本模式即可完整跑完一局并 验证信息隔离。加 --voice 时才启用,用 OpenAI tts-1 把每条公开发言合成 mp3, 存到 audio/ 目录;在 macOS 上可用 afplay 顺带播放(--play)。 """ import os import subprocess from .agent import get_client # 给不同玩家分配不同音色,便于区分 _VOICES = ["alloy", "echo", "fable", "ony...
40
1,540
ai-agent-book
chapter10/autonomous-phone-registration/voice.py
.py
"""Live microphone/ASR/TTS channel and a deterministic test channel.""" from __future__ import annotations import asyncio import os import subprocess import tempfile import time import wave from pathlib import Path from typing import Dict, List, Protocol class PhoneChannel(Protocol): async def say(self, text: s...
145
5,564
ai-agent-book
chapter10/autonomous-phone-registration/twilio_channel.py
.py
"""Real PSTN transport for the Experiment 10-3 Phone Agent. Twilio places one outbound call. Its speech ``Gather`` provides ASR and ``Say`` provides TTS; the call stays open while the Phone and Computer Agents work. """ from __future__ import annotations import asyncio import os from typing import List class Twili...
147
5,981
ai-agent-book
chapter10/autonomous-phone-registration/models.py
.py
"""Shared contracts for Experiment 10-3. The contracts are deliberately serialisable: every Computer/Phone Agent exchange is also written to the timing trace, so a run can prove what was decided and when. """ from __future__ import annotations import re from dataclasses import asdict, dataclass, field from datetime ...
97
3,330
ai-agent-book
chapter10/autonomous-phone-registration/test_orchestration.py
.py
import asyncio from unittest.mock import AsyncMock, patch import pytest import demo from browser import RecoverableFillError from bus import MessageBus from models import DecisionRecord, FieldSpec from orchestration import ( ComputerAgent, initiate_phone_call_agent, run_parallel, timing_evidence, ) fr...
336
11,443
ai-agent-book
chapter10/autonomous-phone-registration/validate_acceptance.py
.py
#!/usr/bin/env python3 """Fail-closed validator for retained historical 10-5 evidence of current Experiment 10-3.""" from __future__ import annotations import argparse import hashlib import json import re from pathlib import Path from typing import Any TOOL_NAME = "initiate_phone_call_agent" ARK_PROVIDER = "Volcengi...
349
13,513
ai-agent-book
chapter10/autonomous-phone-registration/orchestration.py
.py
"""Phone and Computer Agents plus the autonomous tool dispatcher.""" from __future__ import annotations import asyncio import json import os from dataclasses import dataclass from typing import Dict, List, Optional from browser import RecoverableFillError, RegistrationBrowser from bus import MessageBus from models i...
462
19,446
ai-agent-book
chapter10/autonomous-phone-registration/demo.py
.py
#!/usr/bin/env python3 """Experiment 10-3: autonomously spawn Phone Agent during real browser use.""" from __future__ import annotations import argparse import asyncio import json import time from pathlib import Path try: from dotenv import load_dotenv except ImportError: load_dotenv = None else: load_do...
399
16,309