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
chapter8/MiniMind-pretrain/validation/test_training_report_audit.py
.py
from __future__ import annotations import hashlib import json import shutil from pathlib import Path import pytest import run_training_report_audit as audit import validate_evidence as validator def digest(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() def write_json(path: Path, val...
136
5,821
ai-agent-book
chapter8/MiniMind-pretrain/validation/test_vlm_training_report_audit.py
.py
import hashlib import json import shutil import sys from pathlib import Path import pytest HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) import run_vlm_training_report_audit as audit import validate_vlm_evidence as validator RUN_DIR = HERE / "runs" / audit.DEFAULT_RUN_ID def write_json(path...
162
6,800
ai-agent-book
chapter8/exact-copy-sft/tokenizer_audit.py
.py
"""Audit byte-exact probes against several open tokenizer families.""" from __future__ import annotations import json from pathlib import Path from transformers import AutoTokenizer ROOT = Path(__file__).resolve().parent MODELS = [ "Qwen/Qwen3-8B", "Qwen/Qwen2.5-0.5B-Instruct", "mistralai/Mistral-7B-v0.1...
44
1,576
ai-agent-book
chapter8/exact-copy-sft/evaluate.py
.py
from __future__ import annotations import argparse, json from pathlib import Path import torch from peft import PeftModel from transformers import AutoModelForCausalLM, AutoTokenizer ROOT = Path(__file__).resolve().parent def load(path): return [json.loads(x) for x in Path(path).read_text(encoding="utf-8").splitlines(...
28
2,457
ai-agent-book
chapter8/exact-copy-sft/generate_data.py
.py
from __future__ import annotations import hashlib, json, random from pathlib import Path ROOT = Path(__file__).resolve().parent DATA = ROOT / "data" ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789_-+=:@" LANGUAGES = ["Python", "JavaScript", "Java", "Go", "Rust", "SQL", "Shell", "JSON", "Markdown"...
61
3,074
ai-agent-book
chapter8/exact-copy-sft/train_sft.py
.py
from __future__ import annotations import argparse, hashlib, json from datetime import datetime, timezone from pathlib import Path import torch from peft import LoraConfig, get_peft_model from transformers import AutoModelForCausalLM, AutoTokenizer ROOT = Path(__file__).resolve().parent def load(path): return [js...
61
4,912
ai-agent-book
chapter8/exact-copy-sft/tests/test_copy_pipeline.py
.py
import json from pathlib import Path ROOT = Path(__file__).parents[1] def test_splits_are_nonempty_and_structured(): for name in ("train", "eval", "boundary"): rows = [json.loads(x) for x in (ROOT / "data" / f"{name}.jsonl").read_text(encoding="utf-8").splitlines() if x.strip()] assert rows ...
51
2,388
ai-agent-book
chapter8/MultilingualReasoning/evaluate_multilingual.py
.py
"""Multilingual Reasoning Evaluator for AI Agent Book (Chapter 7). Evaluates LLM reasoning models across multiple languages (English, Spanish, French, Chinese, Japanese) measuring CoT language fidelity, task accuracy, token usage, and cross-lingual transfer efficiency. """ from __future__ import annotations import i...
588
24,223
ai-agent-book
chapter8/MultilingualReasoning/gpt_oss_20b_sft.py
.py
""" 多语言推理模型微调脚本 本脚本展示如何使用 Hugging Face 的 TRL 库对 OpenAI 的 gpt-oss-20b 模型进行微调, 使其能够在多种语言中进行有效推理。 基于 OpenAI Cookbook 教程: https://cookbook.openai.com/articles/gpt-oss/fine-tune-transfomers 作者: Edward Beeching, Quentin Gallouédec, Lewis Tunstall 修改: 适配为完整的 Python 脚本 ⚠️ 硬件要求(重要!): - GPU: H100(80GB 显存)或更高配置 - 训练时间: H100 ...
555
18,914
ai-agent-book
chapter8/Intuitor/evaluate_from_cache.py
.py
#!/usr/bin/env python3 """ 从 lighteval 缓存的 parquet 文件中提取答案并计算 GSM8K 准确率 支持 \\boxed{} 和 #### 两种答案格式 """ import re import pandas as pd import argparse from pathlib import Path from typing import Optional def extract_answer_from_boxed(text: str) -> Optional[str]: """从 \\boxed{} 格式中提取答案(同时支持 \\(\\boxed{}\\) 形式)""" ...
329
10,860
ai-agent-book
chapter8/Intuitor/test_normalize_negative_currency.py
.py
"""Regression: negative currency formats and negative fractions must preserve negative sign.""" from evaluate_from_cache import extract_answer_from_gsm8k_format from evaluate_from_cache import extract_and_normalize_answer, normalize_number def test_negative_dollar_amount(): assert normalize_number("-$42") == "-4...
32
1,018
ai-agent-book
chapter8/Intuitor/tests/test_normalize_frac_formatting.py
.py
"""Regression: LaTeX fractions and division with formatting/units must evaluate correctly.""" from evaluate_from_cache import extract_and_normalize_answer, normalize_number def test_frac_thin_space_evaluates(): assert normalize_number(r"\frac{1\,000}{2}") == "500" assert normalize_number(r"\dfrac{1\,500}{3}"...
27
995
ai-agent-book
chapter8/Intuitor/tests/test_normalize_frac.py
.py
"""Regression: \\frac{a}{b} and a/b must evaluate, not concatenate digit runs.""" from evaluate_from_cache import extract_and_normalize_answer, normalize_number def test_frac_six_over_two(): assert extract_and_normalize_answer(r"\boxed{\frac{6}{2}}") == "3" def test_plain_slash_six_over_two(): assert extra...
21
616
ai-agent-book
chapter8/Intuitor/tests/test_boxed_nested_braces.py
.py
"""Regression: nested braces inside \\boxed{} must not truncate.""" from evaluate_from_cache import extract_answer_from_boxed def test_boxed_nested_frac(): text = r"The answer is \boxed{\frac{1}{2}}" assert extract_answer_from_boxed(text) == r"\frac{1}{2}" def test_boxed_simple_integer(): text = r"Fina...
19
527
ai-agent-book
chapter8/Intuitor/tests/test_empty_text_list.py
.py
"""Regression: empty sample text list must not IndexError.""" def _extract_model_output(sample_data): text_field = sample_data.get('text', ['']) if isinstance(text_field, list): return text_field[0] if text_field else '' return text_field if text_field is not None else '' def test_empty_text_lis...
23
687
ai-agent-book
chapter8/Intuitor/tests/conftest.py
.py
"""Test import bootstrap for the Intuitor 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
236
ai-agent-book
chapter4/execution-tools/quickstart.py
.py
"""Quick start guide for the execution tools MCP server.""" import asyncio from llm_helper import LLMHelper from file_tools import FileTools from execution_tools import ExecutionTools async def quickstart(): """Quick demonstration of the execution tools.""" print("=== Execution Tools MCP Server - Quick Start...
96
2,888
ai-agent-book
chapter4/execution-tools/test_truncate_tail_lines_zero.py
.py
"""tail_lines=0 must keep no tail lines (Python lines[-0:] quirk).""" from execution_tools import truncate_and_persist def test_tail_lines_zero_keeps_only_head(): text = "\n".join(f"line{i}" for i in range(100)) out, path = truncate_and_persist( text, head_lines=3, tail_lines=0, max_lines=10, max_char...
37
1,316
ai-agent-book
chapter4/execution-tools/server.py
.py
"""MCP server for execution tools.""" import asyncio import json from typing import Any from mcp.server import Server, NotificationOptions from mcp.server.models import InitializationOptions import mcp.server.stdio import mcp.types as types from config import Config from llm_helper import LLMHelper from file_tools im...
364
13,978
ai-agent-book
chapter4/execution-tools/test_script.py
.py
def greet(name): print(f"Hello, {name}!") if __name__ == "__main__": greet("MCP Server")
6
98
ai-agent-book
chapter4/execution-tools/test_config_env.py
.py
"""Regression test: malformed numeric env vars must not crash config import. TEMPERATURE / MAX_TOKENS / MAX_OUTPUT_LENGTH were parsed with bare float()/int() at import time, so e.g. MAX_TOKENS=abc crashed every tool with ValueError. They now fall back to defaults with a warning. """ import importlib import os from pat...
49
1,774
ai-agent-book
chapter4/execution-tools/run_experiment_4_3.py
.py
#!/usr/bin/env python3 """Run the manuscript-scope Experiment 4-3 campaign over real MCP stdio.""" from __future__ import annotations import argparse import asyncio import hashlib import json import os import re import shutil import sys import time from datetime import datetime, timezone from pathlib import Path from...
279
14,890
ai-agent-book
chapter4/execution-tools/multilang_executor.py
.py
"""Multi-language code execution support inspired by SandboxFusion.""" import asyncio import subprocess import tempfile import os import shutil import time import base64 import psutil import shlex from typing import Dict, Any, Optional, List from enum import Enum import logging logger = logging.getLogger(__name__) ...
640
23,013
ai-agent-book
chapter4/execution-tools/test_multilang_output.py
.py
import asyncio import pytest from multilang_executor import get_all_output, LanguageExecutor, ExecutionStatus @pytest.mark.asyncio async def test_get_all_output_reads_full_payload(): class FakeStream: def __init__(self, data: bytes): self._data = data self._done = False as...
30
877
ai-agent-book
chapter4/execution-tools/test_filesystem_enhanced.py
.py
""" Real tests for enhanced filesystem tools. These tests perform actual file operations to verify functionality. """ import asyncio import json import pytest from pathlib import Path import sys # Add current directory to path sys.path.insert(0, str(Path(__file__).parent)) from config import Config from filesystem_en...
373
12,977
ai-agent-book
chapter4/execution-tools/test_edit_reject_empty_search.py
.py
"""Regression: edit_file must reject empty search text (not insert at start).""" import tempfile from pathlib import Path import pytest from llm_helper import LLMHelper from file_tools import FileTools @pytest.mark.asyncio async def test_empty_search_rejected(): with tempfile.TemporaryDirectory() as td: ...
40
1,295
ai-agent-book
chapter4/execution-tools/llm_helper.py
.py
"""LLM helper for safety checks, approval, and summarization.""" import json import datetime as dt import os import subprocess import time from pathlib import Path from typing import Optional, Dict, Any from openai import OpenAI from config import Config def _reasoning_safe_temperature(model, requested=1.0): """...
347
12,206
ai-agent-book
chapter4/execution-tools/extended_tools.py
.py
"""Real data, webhook, and browser execution tools for Experiment 4-3.""" from __future__ import annotations import hashlib import json import os import re import signal import shutil import subprocess import tempfile import time from pathlib import Path from typing import Any import httpx from config import Config ...
389
19,634
ai-agent-book
chapter4/execution-tools/test_github_idempotency.py
.py
"""Idempotency coverage for the Experiment 4-3 GitHub execution tool.""" from __future__ import annotations import asyncio from datetime import datetime, timezone from external_tools import ExternalTools class _Approval: def request_approval(self, _operation, _details): return True, "bounded test" cl...
63
1,634
ai-agent-book
chapter4/execution-tools/test_execution_tools.py
.py
"""Test execution tools.""" import asyncio from llm_helper import LLMHelper from execution_tools import ExecutionTools async def test_code_interpreter(): """Test code interpreter functionality.""" print("Testing code interpreter...") llm_helper = LLMHelper() execution_tools = ExecutionTools(llm_...
97
2,855
ai-agent-book
chapter4/execution-tools/hello.py
.py
#!/usr/bin/env python3 """A simple greeting script.""" def main(): name = "World" print(f"Hello, {name}!") if __name__ == "__main__": main()
10
155
ai-agent-book
chapter4/execution-tools/test_command_history_count_zero.py
.py
"""get_command_history(count=0) must return an empty list, not the full history.""" import pytest from config import Config from terminal_controller import TerminalController @pytest.fixture def tc(tmp_path, monkeypatch): monkeypatch.setattr(Config, "WORKSPACE_DIR", tmp_path) controller = TerminalController(...
32
961
ai-agent-book
chapter4/execution-tools/filesystem_enhanced.py
.py
""" Enhanced filesystem tools based on AWorld filesystem-server. Provides comprehensive file and directory operations with safety checks. """ import json import os import shutil import traceback from pathlib import Path from typing import Dict, Any, List from config import Config class FilesystemEnhanced: """Enh...
677
22,095
ai-agent-book
chapter4/execution-tools/terminal_controller.py
.py
""" Terminal Controller with integrated file operations. Based on AWorld terminal-controller implementation. Provides command execution with directory navigation and file editing. """ import os import subprocess import traceback from pathlib import Path from typing import Dict, Any from config import Config class Te...
505
15,579
ai-agent-book
chapter4/execution-tools/test_null_language.py
.py
"""Null optional language must default to python on public paths.""" import asyncio import tempfile from pathlib import Path from unittest.mock import MagicMock from multilang_executor import LanguageExecutor from execution_tools import ExecutionTools def test_null_language_executor_defaults_to_python(): le = La...
46
1,669
ai-agent-book
chapter4/execution-tools/external_tools.py
.py
"""External system integration tools: Google Calendar and GitHub.""" import os import json from typing import Dict, Any, Optional from datetime import datetime, timedelta from pathlib import Path from llm_helper import LLMHelper from config import Config # Google Calendar imports (optional) try: from google.oaut...
324
10,508
ai-agent-book
chapter4/execution-tools/execution_tools.py
.py
"""Generic execution tools: code interpreter and virtual terminal.""" import os import subprocess import sys import io import tempfile import traceback from typing import Dict, Any, Optional, Tuple from contextlib import redirect_stdout, redirect_stderr from llm_helper import LLMHelper from config import Config from m...
281
10,714
ai-agent-book
chapter4/execution-tools/examples.py
.py
"""Example usage of the execution tools MCP server.""" import asyncio from llm_helper import LLMHelper from file_tools import FileTools from execution_tools import ExecutionTools from external_tools import ExternalTools async def example_file_operations(): """Example: File operations with verification.""" pr...
161
4,332
ai-agent-book
chapter4/execution-tools/cli.py
.py
#!/usr/bin/env python3 """执行工具统一命令行入口(实验 4-3:执行工具 MCP 服务器)。 本文件提供一个 argparse 命令行界面,用于列出、单独调用每个执行工具,并运行 一个端到端的离线演示。它复用 server.py 背后的同一批工具实现,因此命令行的 行为与 MCP 服务器完全一致。 工具清单(与 server.py 一致): file_write 写文件(写入前自动做语法/linter 校验) file_edit 按“搜索-替换”编辑文件(带 diff 预览与校验) code_interpreter 多语言沙盒代码执行(危险操作审批、长输出截断...
411
18,081
ai-agent-book
chapter4/execution-tools/config.py
.py
"""Configuration management for the execution tools MCP server.""" import os import sys from pathlib import Path from typing import Optional from dotenv import load_dotenv # Load environment variables load_dotenv() def _env_int(name: str, default: int) -> int: """Read an integer env var; fall back to default (w...
188
6,837
ai-agent-book
chapter4/execution-tools/test_gui_tools.py
.py
"""Focused validation for Experiment 4-3 desktop/mobile execution tools.""" from __future__ import annotations import asyncio from extended_tools import ExtendedTools def test_virtual_desktop_rejects_non_https() -> None: result = asyncio.run(ExtendedTools().virtual_desktop_execute( "http://example.com"...
20
682
ai-agent-book
chapter4/execution-tools/test_file_tools.py
.py
"""Test file system tools.""" import asyncio import tempfile from pathlib import Path from llm_helper import LLMHelper from file_tools import FileTools from config import Config async def test_file_write(): """Test file write functionality.""" print("Testing file write...") llm_helper = LLMHelper() ...
107
2,835
ai-agent-book
chapter4/execution-tools/test_multilang.py
.py
"""Test multi-language code execution.""" import asyncio import sys from multilang_executor import LanguageExecutor, ExecutionStatus async def run_language_case(executor: LanguageExecutor, language: str, code: str, description: str): """Test a specific language.""" print(f"\n{'='*60}") print(f"Testing {l...
172
4,201
ai-agent-book
chapter4/execution-tools/test_external_tools.py
.py
"""Test external integration tools.""" import asyncio from llm_helper import LLMHelper from external_tools import ExternalTools async def test_google_calendar(): """Test Google Calendar integration.""" print("Testing Google Calendar...") llm_helper = LLMHelper() external_tools = ExternalTools(ll...
108
3,149
ai-agent-book
chapter4/execution-tools/file_tools.py
.py
"""File system tools with safety mechanisms.""" import itertools import os from pathlib import Path from typing import Dict, Any from llm_helper import LLMHelper from config import Config class FileTools: """File system tools with verification and safety checks.""" def __init__(self, llm_helper: LLMHelp...
211
7,296
ai-agent-book
chapter4/execution-tools/test_terminal_controller.py
.py
""" Tests for Terminal Controller. Tests command execution with directory navigation and file operations. """ import asyncio import json import pytest from config import Config from terminal_controller import TerminalController @pytest.fixture(scope="function") def tc(tmp_path, monkeypatch): """Create terminal c...
212
6,883
ai-agent-book
chapter4/execution-tools/validation/experiment_4_3/real_mcp_gui_20260802T093348Z/workspace/valid.py
.py
def add(a, b): return a - b
3
32
ai-agent-book
chapter4/collaboration-tools/quickstart.py
.py
"""Quick start demo for Collaboration Tools MCP Server. This script demonstrates how to use the MCP server as a client. """ import asyncio from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from mcp.types import TextContent import sys import json from result_parsing import...
166
6,255
ai-agent-book
chapter4/collaboration-tools/client_example.py
.py
"""Example client showing how to use Collaboration Tools MCP Server. This example demonstrates a real-world use case: monitoring a website and notifying administrators when changes are detected. """ import asyncio from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from mcp....
206
7,340
ai-agent-book
chapter4/collaboration-tools/test_config_env.py
.py
"""Regression test: malformed numeric env vars must not crash config load. BROWSER_TIMEOUT / SMTP_PORT / HITL_TIMEOUT_SECONDS (config.py) and OPENAI_TIMEOUT / OPENAI_MAX_RETRIES (subagent_tools.py) were parsed with bare int()/float(); malformed values crashed with ValueError at import/startup. They now fall back to de...
50
1,696
ai-agent-book
chapter4/collaboration-tools/test_timer_tools.py
.py
"""Offline regression tests for recurring timer persistence.""" import asyncio import json import os import sys import tempfile import types import unittest from datetime import datetime, timedelta from pathlib import Path from unittest.mock import AsyncMock, patch sys.path.insert(0, os.path.join(os.path.dirname(__fi...
172
5,753
ai-agent-book
chapter4/collaboration-tools/main.py
.py
#!/usr/bin/env python3 """协作工具 —— 统一命令行入口 (实验 4-4) 《深入理解 AI Agent》第 4 章 实验 4-4「协作工具 MCP 服务器」的命令行界面。 在不启动 MCP 服务器的前提下,直接列出、单独调用各协作工具,并运行端到端演示。 协作工具分三类(对应书中"协作工具"一节): 1. 子 Agent 管理:spawn_subagent / send_message_to_subagent / cancel_subagent (支持同步/异步两种模式,以及 minimal / llm_generated 两种上下文传递策略) 2. 人类协作(HITL):reque...
381
17,125
ai-agent-book
chapter4/collaboration-tools/test_intelligence_tools.py
.py
""" Tests for intelligence processing tools. Tests code generation, reasoning, and guarding capabilities. """ import asyncio import json import pytest import os from pathlib import Path import sys sys.path.insert(0, str(Path(__file__).parent / "src")) from intelligence_tools import ( generate_python_code, com...
144
4,835
ai-agent-book
chapter4/collaboration-tools/test_basic.py
.py
"""Basic tests for Collaboration Tools MCP Server. Run with: python test_basic.py """ import asyncio import sys import os # Add src to path sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src')) async def test_config(): """Test configuration loading.""" print("Testing configuration...") fro...
160
4,745
ai-agent-book
chapter4/collaboration-tools/test_excel_tools.py
.py
""" Tests for Excel operation tools. Uses real Excel files for testing. """ import asyncio import json import pytest import tempfile from pathlib import Path import sys sys.path.insert(0, str(Path(__file__).parent / "src")) from excel_tools import ( read_excel_data, write_excel_data, create_excel_workbook...
146
4,438
ai-agent-book
chapter4/collaboration-tools/test_load_expired_timer_callback.py
.py
import asyncio import json from datetime import datetime, timedelta from pathlib import Path import pytest import sys sys.path.insert(0, str(Path(__file__).parent / "src")) import timer_tools from config import config @pytest.mark.asyncio async def test_load_timers_expired_active_timer_triggers_callback(): stor...
59
1,715
ai-agent-book
chapter4/collaboration-tools/test_browser_title.py
.py
import os import sys from unittest.mock import AsyncMock, patch import pytest sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) @pytest.mark.asyncio async def test_browser_navigate_awaits_title(): mock_page = AsyncMock() mock_page.title.return_value = "Test Page Title" mock_page.url = "...
41
1,420
ai-agent-book
chapter4/collaboration-tools/test_result_parsing.py
.py
"""Tests for MCP result parsing.""" import unittest from result_parsing import parse_mapping class ParseMappingTests(unittest.TestCase): def test_parses_python_mapping_literal(self): text = ( "{'success': True, 'timer_id': 'abc', " "'metadata': {'attempt': None, 'tags': ['demo']}...
43
1,224
ai-agent-book
chapter4/collaboration-tools/test_recurring_max_occurrences_zero.py
.py
"""max_occurrences=0 must stop the recurring timer (not run forever).""" import asyncio import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent / "src")) import timer_tools as tt async def _run(): # Clear any leftover timers from other tests in this process. tt._active_tim...
48
1,339
ai-agent-book
chapter4/collaboration-tools/subagent_comparison.py
.py
"""Compare the two sub-agent context-passing strategies (实验 4-4「对比效果」). Spawns a sub-agent under BOTH `minimal` and `llm_generated` strategies on the SAME task and prints the difference (context tokens handed off, extra preparation cost, whether private data leaked, and each sub-agent's result). Run: export OPENA...
28
1,050
ai-agent-book
chapter4/collaboration-tools/run_experiment_4_4.py
.py
#!/usr/bin/env python3 """Run Experiment 4-4 through the collaboration MCP stdio server.""" from __future__ import annotations import argparse import ast import asyncio import hashlib import json import os import re import select import sys import time from datetime import datetime, timezone from pathlib import Path ...
516
25,006
ai-agent-book
chapter4/collaboration-tools/test_recurring_interval_positive.py
.py
"""Recurring timers with interval_seconds <= 0 must not busy-loop.""" import asyncio import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent / "src")) import timer_tools as t async def _probe(interval): t._active_timers.clear() t._timer_tasks.clear() result = await t.se...
47
1,331
ai-agent-book
chapter4/collaboration-tools/result_parsing.py
.py
"""Helpers for parsing text returned by collaboration tools.""" import ast from typing import Any def parse_mapping(text: str) -> dict[str, Any]: """Parse a Python dictionary literal without evaluating expressions.""" try: parsed = ast.literal_eval(text) except (SyntaxError, ValueError) as exc: ...
18
531
ai-agent-book
chapter4/collaboration-tools/test_run_experiment_4_4.py
.py
"""Focused tests for the Experiment 4-4 campaign controls.""" import json import os import sys import unittest from datetime import datetime from pathlib import Path from unittest.mock import patch sys.path.insert(0, str(Path(__file__).resolve().parent / "src")) import hitl_tools import subagent_tools from run_expe...
277
10,310
ai-agent-book
chapter4/collaboration-tools/validate_experiment_4_4.py
.py
#!/usr/bin/env python3 """Independently validate a retained Experiment 4-4 interactive campaign.""" from __future__ import annotations import argparse import hashlib import json import re from datetime import datetime from pathlib import Path EXPECTED_BLOCKERS = [ "real_email_notification", "real_im_notific...
144
5,469
ai-agent-book
chapter4/collaboration-tools/test_chess_tools.py
.py
""" Real tests for Chess game tools. These tests verify chess game logic without mocking. """ import asyncio import json import pytest from pathlib import Path import sys # Add src to path sys.path.insert(0, str(Path(__file__).parent / "src")) from chess_tools import ( new_game, load_fen, make_move, g...
503
15,913
ai-agent-book
chapter4/collaboration-tools/src/main.py
.py
"""Collaboration Tools MCP Server This MCP server provides tools for: - Browser automation (using browser-use) - Human-in-the-loop assistance requests - IM and email notifications - Timer/scheduling capabilities """ import asyncio import logging from typing import Dict, Any, List, Optional from mcp.server.fastmcp im...
570
21,878
ai-agent-book
chapter4/collaboration-tools/src/subagent_tools.py
.py
"""Sub-agent management tools for the Collaboration Tools MCP Server. Implements the 子 Agent 管理 primitives described in 实验 4-4: - spawn_subagent create a sub-agent (sync or async) - send_message_to_subagent send a follow-up message to a sub-agent - cancel_subagent cancel a running su...
638
27,021
ai-agent-book
chapter4/collaboration-tools/src/__init__.py
.py
"""Collaboration Tools MCP Server package.""" __version__ = "1.0.0"
4
69
ai-agent-book
chapter4/collaboration-tools/src/notification_tools.py
.py
"""Notification tools for email and instant messaging.""" import asyncio import json from typing import Optional, Dict, Any, List import logging import httpx logger = logging.getLogger(__name__) async def send_email( to_email: str, subject: str, body: str, html: bool = False, cc: Optional[List[s...
366
11,073
ai-agent-book
chapter4/collaboration-tools/src/notification_dispatcher.py
.py
"""Notification Dispatcher module for multi-channel notifications and Human-in-the-Loop decision timeout policy management.""" import asyncio from dataclasses import dataclass, field from datetime import datetime, timezone from enum import Enum import json import logging from typing import Any, Callable, Dict, List, O...
678
27,892
ai-agent-book
chapter4/collaboration-tools/src/timer_tools.py
.py
"""Timer and scheduling tools for delayed task execution.""" import asyncio import json import uuid from typing import Optional, Dict, Any, Callable from datetime import datetime, timedelta from pathlib import Path import logging logger = logging.getLogger(__name__) # Active timers storage _active_timers: Dict[str, ...
488
16,551
ai-agent-book
chapter4/collaboration-tools/src/test_excel_max_rows_all_sheets.py
.py
"""Regression: all-sheets read must honor max_rows (not a hard 100-row cap).""" import asyncio from pathlib import Path import pandas as pd import pytest from openpyxl import Workbook from excel_tools import read_excel_data def _workbook(path: Path, n_rows: int) -> None: wb = Workbook() ws = wb.active w...
48
1,299
ai-agent-book
chapter4/collaboration-tools/src/intelligence_tools.py
.py
""" Intelligence processing tools: Code generation, reasoning, and guarding. Based on AWorld intelligence-* servers. """ import json import logging import os from typing import Dict, Any, List from openai import OpenAI from dotenv import load_dotenv from llm_fallback import resolve_llm load_dotenv() logger = loggin...
219
6,757
ai-agent-book
chapter4/collaboration-tools/src/llm_fallback.py
.py
"""Universal OpenRouter fallback for the collaboration tools' LLM clients. Every LLM entry point in this experiment (sub-agent runs, intelligence tools, browser-use) speaks the OpenAI-compatible API. This helper centralizes the credential resolution so that: 1. When OPENAI_API_KEY is present, behavior is unchanged ...
94
3,711
ai-agent-book
chapter4/collaboration-tools/src/browser_tools.py
.py
"""Browser automation tools using browser-use library.""" import asyncio import json from typing import Optional, Dict, Any, List from pathlib import Path import logging logger = logging.getLogger(__name__) # Browser session singleton _browser_session = None async def init_browser(headless: bool = False, user_data...
284
8,299
ai-agent-book
chapter4/collaboration-tools/src/hitl_tools.py
.py
"""Human-in-the-loop (HITL) tools for requesting admin assistance.""" import asyncio import json import uuid from typing import Optional, Dict, Any, List from datetime import datetime, timedelta from pathlib import Path import logging logger = logging.getLogger(__name__) # Store pending requests _pending_requests: D...
344
11,060
ai-agent-book
chapter4/collaboration-tools/src/config.py
.py
"""Configuration management for Collaboration Tools MCP Server.""" import os import sys from pathlib import Path from typing import Optional from pydantic import BaseModel, Field from dotenv import load_dotenv # Load environment variables load_dotenv() def _env_int(name: str, default: int) -> int: """Read an in...
112
3,895
ai-agent-book
chapter4/collaboration-tools/src/chess_tools.py
.py
""" Chess game tools for game management and analysis. Based on AWorld MCP server implementation. """ import logging import traceback from typing import Dict, Any import chess from pydantic import BaseModel logger = logging.getLogger(__name__) class ChessBoardState(BaseModel): """Structured representation of t...
419
11,723
ai-agent-book
chapter4/collaboration-tools/src/excel_tools.py
.py
""" Excel operation tools based on AWorld excel server. Provides comprehensive Excel file manipulation capabilities. """ import json import logging from pathlib import Path from typing import Dict, Any, List import pandas as pd from openpyxl import load_workbook, Workbook from openpyxl.utils import get_column_letter ...
323
8,814
ai-agent-book
chapter4/active-tool-selection/quickstart.py
.py
""" Quick Start for Active Tool Selection. Run this script to see a basic demonstration of active tool discovery. """ from agent import ActiveToolAgent, PassiveToolAgent from tool_knowledge_base import create_tool_knowledge_base, calculate_total_tokens def main(): print(""" ╔════════════════════════════════════...
134
5,358
ai-agent-book
chapter4/active-tool-selection/demo_comparison.py
.py
""" Comparison Demo: Active vs Passive Tool Selection. Demonstrates the efficiency gains of active tool discovery compared to traditional passive tool injection approach. """ import argparse import json import time from tabulate import tabulate from agent import ActiveToolAgent, PassiveToolAgent, RetrievalToolAgent ...
536
21,803
ai-agent-book
chapter4/active-tool-selection/tool_knowledge_base.py
.py
""" Tool Knowledge Base - Simulates MCP servers with various tools. This module defines a comprehensive knowledge base of tools organized by domains (servers), similar to the MCP (Model Context Protocol) ecosystem. Each server represents a platform or service domain with specific tools. """ from typing import List, D...
625
26,770
ai-agent-book
chapter4/active-tool-selection/benchmark.py
.py
""" Tool-selection benchmark and offline evaluation. Provides a small labeled benchmark (task -> ground-truth tool) and utilities to quantify, *without any API calls*, the core claim of the chapter: when a tool ecosystem grows to hundreds of tools, retrieving the few relevant tools on demand keeps the right tool reach...
204
7,644
ai-agent-book
chapter4/active-tool-selection/semantic_router.py
.py
""" Hierarchical Semantic Routing for Tool Discovery. Implements a two-stage algorithm for matching tool requests to relevant tools: 1. Server-level routing: Filter candidate servers by domain/platform 2. Tool-level routing: Rank tools within selected servers by semantic similarity This approach reduces search comple...
293
11,186
ai-agent-book
chapter4/active-tool-selection/examples.py
.py
""" Example use cases demonstrating active tool selection. """ from agent import ActiveToolAgent from semantic_router import SemanticRouter from tool_knowledge_base import create_tool_knowledge_base def example_github_workflow(): """Example: GitHub development workflow.""" print("\n" + "=" * 70) print("E...
213
7,783
ai-agent-book
chapter4/active-tool-selection/config.py
.py
"""Configuration for Active Tool Selection Agent.""" import os from dotenv import load_dotenv load_dotenv() # LLM Configuration LLM_PROVIDER = os.getenv("LLM_PROVIDER", "openai").lower() LLM_PROVIDER = {"qwen": "dashscope", "bailian": "dashscope"}.get(LLM_PROVIDER, LLM_PROVIDER) if LLM_PROVIDER == "dashscope": OP...
57
2,196
ai-agent-book
chapter4/active-tool-selection/agent.py
.py
""" Active Tool Discovery Agent. Implements an LLM agent that actively requests tools on-demand rather than having all tool schemas injected into the prompt. Inspired by MCP-Zero. """ from typing import List, Dict, Any, Optional from openai import OpenAI from tool_knowledge_base import ToolDefinition, ServerDefiniti...
542
19,429
ai-agent-book
chapter4/active-tool-selection/tests/test_parse_request_closing_tag.py
.py
from semantic_router import StructuredRequestParser def test_parse_request_preceding_closing_tag_mention(): text = ( "Note: Do not format as </tool_request> without an opening tag.\n\n" "<tool_request>\n" "server: GitHub for repository operations\n" "tool: search repositories by ke...
20
748
ai-agent-book
chapter4/active-tool-selection/tests/test_basic.py
.py
""" Basic tests to verify the active tool selection system works correctly. Run without API key to test core functionality. """ from tool_knowledge_base import create_tool_knowledge_base, calculate_total_tokens, get_all_tools from semantic_router import SemanticRouter, StructuredRequestParser def test_knowledge_base...
220
8,395
ai-agent-book
chapter4/active-tool-selection/tests/test_usage_none.py
.py
"""Regression test: agent must tolerate providers that return usage=None. The OpenAI SDK response object always HAS a `usage` attribute (pydantic field), but it deserializes as None when the provider omits token accounting. The old `hasattr(response, 'usage')` guard was therefore ineffective and `response.usage.total_...
53
2,094
ai-agent-book
chapter4/active-tool-selection/tests/conftest.py
.py
"""Test import bootstrap for the active-tool-selection 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
249
ai-agent-book
chapter4/perception-tools/test_imports.py
.py
""" Test script to verify all imports and basic module loading. """ import sys from pathlib import Path # Add src to path sys.path.insert(0, str(Path(__file__).parent / "src")) print("Testing imports...") try: print("\n✓ Importing base module...") from base import ActionResponse, DocumentMetadata, is_url, va...
76
2,298
ai-agent-book
chapter4/perception-tools/quickstart.py
.py
""" Quick start script to test the perception tools MCP server. """ import asyncio import json import logging import sys from pathlib import Path # Add src to path sys.path.insert(0, str(Path(__file__).parent / "src")) from search_tools import search_web, download_file from multimodal_tools import read_webpage from f...
124
4,203
ai-agent-book
chapter4/perception-tools/test_real_experiment_4_1_evidence.py
.py
"""Validate the durable real-MCP evidence for Experiment 4-1.""" from __future__ import annotations import hashlib import json import os from pathlib import Path HERE = Path(__file__).resolve().parent CAMPAIGN = HERE / "validation" / "experiment_4_1" / "real_mcp_20260729T214721Z" def _json(path: Path) -> dict: ...
114
4,912
ai-agent-book
chapter4/perception-tools/test_wiki_article_history_date.py
.py
import asyncio import json import os import sys import types sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) # Optional runtime deps for importing the chapter module in unit tests. sys.modules.setdefault("wikipedia", types.ModuleType("wikipedia")) sys.modules.setdefault("dotenv", types.SimpleNamesp...
32
938
ai-agent-book
chapter4/perception-tools/smoke_test_mcp_v2.py
.py
#!/usr/bin/env python3 """Offline MCP v2 smoke test: start stdio, list tools, and call one tool.""" from __future__ import annotations import asyncio import os import sys from importlib.metadata import version from pathlib import Path from mcp import Client, StdioServerParameters from mcp.client.stdio import stdio_c...
57
1,813
ai-agent-book
chapter4/perception-tools/test_search_kb_negative_top_k.py
.py
import json from pathlib import Path import pytest import sys sys.path.insert(0, str(Path(__file__).parent / "src")) from search_tools import search_knowledge_base @pytest.mark.asyncio async def test_search_knowledge_base_negative_top_k(tmp_path: Path): (tmp_path / "doc1.txt").write_text("test content one", enco...
20
653
ai-agent-book
chapter4/perception-tools/test_new_tools.py
.py
""" Test script for new perception tools: crypto prices, location search, and POI search. """ import asyncio import json import logging import sys from pathlib import Path # Add src to path sys.path.insert(0, str(Path(__file__).parent / "src")) from public_data_tools import get_crypto_price, search_location, search_p...
130
4,485
ai-agent-book
chapter4/perception-tools/test_yahoo_finance_tools.py
.py
""" Real API tests for Yahoo Finance tools. These tests make actual API calls to Yahoo Finance to verify functionality. """ import asyncio import json import pytest from pathlib import Path import sys from datetime import datetime, timedelta # Add src to path sys.path.insert(0, str(Path(__file__).parent / "src")) fro...
390
13,371