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
chapter2/prompt-engineering/tau_bench/model_utils/api/tokens.py
.py
import json from pydantic import BaseModel from tau_bench.model_utils.api.datapoint import ( BinaryClassifyDatapoint, ClassifyDatapoint, Datapoint, GenerateDatapoint, ParseDatapoint, ParseForceDatapoint, ScoreDatapoint, ) class TokenUsage(BaseModel): input_tokens: int output_toke...
80
3,047
ai-agent-book
chapter2/prompt-engineering/tau_bench/agents/chat_react_agent.py
.py
# Copyright Sierra import json from litellm import completion from tau_bench.agents.base import Agent from tau_bench.envs.base import Env from tau_bench.types import ( Action, SolveResult, RESPOND_ACTION_NAME, RESPOND_ACTION_FIELD_NAME, ) from typing import Optional, List, Dict, Any, Tuple class Cha...
199
6,731
ai-agent-book
chapter2/prompt-engineering/tau_bench/agents/tool_calling_agent.py
.py
# Copyright Sierra import json from litellm import completion from typing import List, Optional, Dict, Any from tau_bench.agents.base import Agent from tau_bench.envs.base import Env from tau_bench.types import SolveResult, Action, RESPOND_ACTION_NAME class ToolCallingAgent(Agent): def __init__( self, ...
94
3,252
ai-agent-book
chapter2/prompt-engineering/tau_bench/agents/few_shot_agent.py
.py
# Copyright Sierra import json import random from litellm import completion from typing import List, Optional, Dict, Any from tau_bench.agents.base import Agent from tau_bench.envs.base import Env from tau_bench.types import SolveResult, Action, RESPOND_ACTION_NAME class FewShotToolCallingAgent(Agent): def __in...
104
3,950
ai-agent-book
chapter2/prompt-engineering/tau_bench/agents/base.py
.py
# Copyright Sierra import abc from typing import Optional from tau_bench.envs.base import Env from tau_bench.types import SolveResult class Agent(abc.ABC): @abc.abstractmethod def solve( self, env: Env, task_index: Optional[int] = None, max_num_steps: int = 30 ) -> SolveResult: raise NotI...
15
336
ai-agent-book
chapter2/system-hint/quickstart.py
.py
""" Quick Start for System-Hint Enhanced Agent Simple demonstration using the sample task """ import os import sys from pathlib import Path from agent import SystemHintAgent, SystemHintConfig from agentbook.providers import PROVIDERS def main(): """Quick start demonstration""" # Check for API key. ๆŽฅๅ—ๅ“ชไบ›็Žฏๅขƒๅ˜้‡...
153
5,199
ai-agent-book
chapter2/system-hint/view_trajectory.py
.py
#!/usr/bin/env python """ Utility to view saved trajectory files Usage: python view_trajectory.py [trajectory_file] """ import json import sys from pathlib import Path from datetime import datetime def format_time(iso_string): """Convert ISO timestamp to readable format""" try: dt = datetime.fromisofo...
95
3,486
ai-agent-book
chapter2/system-hint/main.py
.py
""" Main entry point for System-Hint Enhanced Agent Supports command-line tasks and interactive mode """ import os import sys import json import logging import argparse from datetime import datetime from pathlib import Path from agent import SystemHintAgent, SystemHintConfig, TodoStatus # Configure logging logging.ba...
634
23,486
ai-agent-book
chapter2/system-hint/test_basic.py
.py
""" Basic test to verify System-Hint Agent functionality """ import os import sys import pytest from agent import SystemHintAgent, SystemHintConfig, TodoStatus def test_basic_functionality(): """Test basic agent functionality without API calls""" print("Testing System-Hint Agent components...") # T...
196
6,801
ai-agent-book
chapter2/system-hint/run_experiment_2_8.py
.py
#!/usr/bin/env python3 """Run the frozen, real Kimi K3 campaign for Chapter 2 Experiment 2-9.""" from __future__ import annotations import argparse import copy import hashlib import json import os import re import shutil import sys import time from concurrent.futures import ThreadPoolExecutor, as_completed from datet...
930
41,977
ai-agent-book
chapter2/system-hint/test_malformed_tool_json.py
.py
"""Regression: malformed tool-argument JSON must not abort the ReAct loop.""" from types import SimpleNamespace from unittest.mock import MagicMock from agent import SystemHintAgent, SystemHintConfig def test_execute_task_survives_malformed_tool_arguments_json(): config = SystemHintConfig( enable_timesta...
74
2,378
ai-agent-book
chapter2/system-hint/config.py
.py
""" Configuration module for System-Hint Enhanced Agent """ import os from typing import Optional from dataclasses import dataclass from dotenv import load_dotenv from agentbook.providers import PROVIDERS, canonical_provider load_dotenv() @dataclass class AgentConfig: """Configuration for the System-Hint Agent...
131
4,377
ai-agent-book
chapter2/system-hint/test_experiment_2_8.py
.py
import json from pathlib import Path import run_experiment_2_8 as campaign def test_condition_order_alternates_and_timestamp_has_three_arms(): assert campaign.condition_order("timestamps", 0) == [ "timestamps_guided", "timestamps_raw", "disabled" ] assert campaign.condition_order("timestamps", 1)...
74
3,201
ai-agent-book
chapter2/system-hint/agent.py
.py
""" System-Hint Enhanced AI Agent An agent that demonstrates advanced trajectory management with system hints, including timestamps, tool call tracking, TODO lists, and detailed error messages. """ import codecs import json import os import sys import subprocess import platform import logging from typing import List, ...
1,062
47,016
ai-agent-book
chapter2/system-hint/test_hint_behavior.py
.py
#!/usr/bin/env python """ Test script to demonstrate that system hints are added as user messages temporarily before sending to LLM, but not stored in conversation history. """ import os import json from agent import SystemHintAgent, SystemHintConfig def test_hint_behavior(): """Test and demonstrate the system hi...
100
3,074
ai-agent-book
chapter2/kv-cache/main.py
.py
""" Main script to demonstrate KV cache importance Runs the ReAct agent with different implementations and compares performance """ import os import sys import glob import json import argparse import logging from typing import Dict, List, Any from datetime import datetime from dataclasses import asdict try: from ...
549
23,981
ai-agent-book
chapter2/kv-cache/agent.py
.py
""" KV Cache Demonstration Agent with ReAct Pattern Demonstrates the importance of KV cache through correct and incorrect implementations. Uses local file system tools to read and search through code files. """ import json import os import re import time import logging import random from typing import List, Dict, Any,...
889
38,122
ai-agent-book
chapter2/kv-cache/tests/test_message_flow.py
.py
#!/usr/bin/env python3 """ Test script to verify message flow in correct vs incorrect modes """ def test_message_flow_logic(): """Simulate how messages are handled in different modes""" print("๐Ÿ” Testing Message Flow Logic") print("="*60) # Simulate CORRECT mode print("\nโœ… CORRECT Mode:")...
87
3,054
ai-agent-book
chapter2/kv-cache/tests/test_error_handling.py
.py
#!/usr/bin/env python3 """Offline regressions for local tool error handling.""" from agent import LocalFileTools def test_error_handling(): """Test that local tools return structured errors instead of raising.""" print("๐Ÿงช Testing Error Handling in Tool Execution") print("="*60) # Test local tools d...
47
1,884
ai-agent-book
chapter2/kv-cache/tests/test_negative_size.py
.py
"""Regression: negative size must read to EOF, not drop a suffix.""" import sys import types from pathlib import Path def _stub(): try: import openai # noqa: F401 except ImportError: sys.modules.setdefault("openai", types.ModuleType("openai")) sys.modules["openai"].OpenAI = object _...
27
699
ai-agent-book
chapter2/kv-cache/tests/test_interactive.py
.py
#!/usr/bin/env python3 """ Test script for interactive mode selection """ from main import select_mode_interactive def test_mode_selection(monkeypatch): """Test the interactive mode selection without running the agent""" print("๐Ÿงช Testing Interactive Mode Selection") print("(This is a test - no agent...
31
943
ai-agent-book
chapter2/kv-cache/tests/test_file_range.py
.py
#!/usr/bin/env python3 """ Test script for the read_file tool with offset and size parameters """ from agent import LocalFileTools def test_file_range_reading(): """Test reading files with offset and size parameters""" print("๐Ÿงช Testing File Range Reading") print("="*60) # Initialize tools ...
105
4,265
ai-agent-book
chapter2/kv-cache/tests/test_tools.py
.py
#!/usr/bin/env python3 """ Test script for local file system tools Validates that read_file, find, and grep work correctly """ import os import json from agent import LocalFileTools def test_file_tools(): """Test the local file system tools""" print("๐Ÿงช Testing Local File System Tools") print("="*60...
143
4,992
ai-agent-book
chapter2/kv-cache/tests/conftest.py
.py
"""Pytest bootstrap for the kv-cache experiment tests.""" from pathlib import Path import sys import types EXPERIMENT_ROOT = Path(__file__).resolve().parents[1] if str(EXPERIMENT_ROOT) not in sys.path: sys.path.insert(0, str(EXPERIMENT_ROOT)) try: import openai # noqa: F401 except ImportError: openai_s...
18
435
ai-agent-book
chapter2/kv-cache/tests/manual/check_agent_error_recovery.py
.py
#!/usr/bin/env python3 """Manual live check for agent recovery after tool errors.""" import os import sys from _bootstrap import add_project_root add_project_root() from agent import KVCacheAgent, KVCacheMode def check_agent_error_recovery(): """Run the live agent against an intentionally failing tool path.""...
61
1,777
ai-agent-book
chapter2/kv-cache/tests/manual/check_cache_invalidation.py
.py
#!/usr/bin/env python3 """ Test script to verify KV cache is properly invalidated in incorrect modes """ import os import sys import logging from _bootstrap import add_project_root add_project_root() from agent import KVCacheAgent, KVCacheMode # Set up logging to see details logging.basicConfig(level=logging.INFO) ...
127
5,077
ai-agent-book
chapter2/kv-cache/tests/manual/check_ttft.py
.py
#!/usr/bin/env python3 """ Test script to demonstrate TTFT tracking across iterations Shows how cache usage improves response times """ import os import sys from _bootstrap import add_project_root add_project_root() from agent import KVCacheAgent, KVCacheMode def test_ttft_tracking(): """Test and display TTFT t...
138
5,205
ai-agent-book
chapter2/kv-cache/tests/manual/check_tool_calling.py
.py
#!/usr/bin/env python3 """ Test script to verify the updated agent works with standard OpenAI tool calling """ import os import sys import json from _bootstrap import add_project_root add_project_root() from agent import KVCacheAgent, KVCacheMode def test_tool_calling(): """Test that the agent correctly uses Op...
74
2,203
ai-agent-book
chapter2/kv-cache/tests/manual/check_completion.py
.py
#!/usr/bin/env python3 """ Test script to verify the agent correctly identifies final answers when no tool calls are made """ import os import sys from _bootstrap import add_project_root add_project_root() from agent import KVCacheAgent, KVCacheMode def test_completion_logic(): """Test that the agent correctly ...
100
3,476
ai-agent-book
chapter2/kv-cache/tests/manual/demo_quick.py
.py
#!/usr/bin/env python3 """ Quick demonstration of KV cache impact Shows the difference between correct and incorrect implementations """ import os import sys try: from dotenv import load_dotenv load_dotenv() except ImportError: pass from _bootstrap import add_project_root add_project_root() from agent ...
109
4,002
ai-agent-book
chapter2/kv-cache/tests/manual/check_cached_tokens.py
.py
#!/usr/bin/env python3 """ Test script to verify cached tokens are being parsed correctly from Kimi API """ import os import sys from _bootstrap import add_project_root add_project_root() from agent import KVCacheAgent, KVCacheMode def test_cached_tokens(): """Test that cached tokens are correctly parsed from A...
78
2,672
ai-agent-book
chapter2/kv-cache/tests/manual/_bootstrap.py
.py
"""Helpers for running kv-cache manual smoke scripts from tests/manual.""" from pathlib import Path import sys def add_project_root() -> Path: project_root = Path(__file__).resolve().parents[2] if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) return project_root
12
313
ai-agent-book
chapter2/prompt-injection/test_campaign.py
.py
import json from pathlib import Path from agent import ATTACKER_EMAIL, DEFENSES, Agent from run_campaign import accepted_receipt, request_messages_contain, workspace_inventory class UnusedClient: pass def make_agent(tmp_path: Path, defense_index: int = 0) -> Agent: return Agent( client=UnusedClient...
67
2,592
ai-agent-book
chapter2/prompt-injection/attacks.py
.py
""" ๅฎž้ชŒ 2-5๏ผšไธ‰็งๆ”ปๅ‡ปๅœบๆ™ฏไธŽ"ๆณจๅ…ฅๆ˜ฏๅฆๅพ—้€ž"็š„ๅˆคๅฎš้€ป่พ‘ใ€‚ ๆฏไธชๆ”ปๅ‡ปๅœบๆ™ฏๆ่ฟฐ๏ผš - ็”จๆˆทๆถˆๆฏๅบๅˆ—๏ผˆuser_messages๏ผ‰ - ๆ”ปๅ‡ป่€…ๅฏๆŽง็š„ๅค–้ƒจ็ฝ‘้กตๅ†…ๅฎน๏ผˆwebpage_content๏ผŒ็”จไบŽ้—ดๆŽฅ/่ฎฐๅฟ†ๆณจๅ…ฅ๏ผ‰ - ไธ€ไธช่ง„ๅˆ™ๅˆคๅฎšๅ™จ judge(result) -> bool๏ผŒๅˆคๆ–ญๆณจๅ…ฅๆ˜ฏๅฆๆˆๅŠŸ ๅˆคๅฎš้‡‡็”จ็กฎๅฎšๆ€ง่ง„ๅˆ™๏ผˆๆ˜ฏๅฆๆณ„้œฒไบ†ๅฏ†้’ฅ / ๆ˜ฏๅฆๆ‰ง่กŒไบ†่ถŠๆƒๅทฅๅ…ท่ฐƒ็”จ๏ผ‰๏ผŒ ็จณๅฎšใ€้›ถ้ขๅค–ๆˆๆœฌ๏ผŒไพฟไบŽ็ปŸ่ฎกๆˆๅŠŸ็އใ€‚ """ from __future__ import annotations from dataclasses import dataclass from typing import Callable from agent i...
130
5,742
ai-agent-book
chapter2/prompt-injection/robustness_evaluator.py
.py
""" ๅฎž้ชŒ 2-6๏ผšๆ็คบๆณจๅ…ฅ้ฒๆฃ’ๆ€ง่‡ชๅŠจ่ฏ„ไผฐๅ™จใ€‚ ๆœฌๆจกๅ—ๅœจไธไพ่ต–ไปปไฝ•ๅœจ็บฟ API ็š„ๅ‰ๆไธ‹๏ผŒ้‡ๅŒ–ไธ€ไธช Agent ๅฏนๆ็คบๆณจๅ…ฅๆ”ปๅ‡ป็š„ ๆŠตๆŠ—่ƒฝๅŠ›ใ€‚่ฏ„ไผฐๅ™จๆŽฅๆ”ถไธ€ไธช ``agent_response_fn(payload) -> response`` ็š„ ๅ›ž่ฐƒ๏ผˆๆˆ–ไฝฟ็”จๅ†…็ฝฎ็š„็กฎๅฎšๆ€ง mock๏ผ‰๏ผŒๅฏนๆฏๆกๆ”ปๅ‡ปๅ‘้‡๏ผš 1. ๅฐ†ๆ”ปๅ‡ป่ฝฝ่ทๆไบค็ป™ Agent๏ผŒ่Žทๅ–ๅ…ถๅ›žๅคๆ–‡ๆœฌ๏ผ› 2. ็”จ็กฎๅฎšๆ€ง่ง„ๅˆ™ๅˆคๅฎšๅ›žๅคๆ˜ฏๅฆๆณ„้œฒๆ•ๆ„Ÿไฟกๆฏใ€ๆ˜ฏๅฆ้ตๅพชไบ†ๆณจๅ…ฅๆŒ‡ไปคใ€ๆ˜ฏๅฆ็ช็ ด ็ณป็ปŸๆ็คบ่ฏ่พน็•Œ๏ผ› 3. ๅœจไธ‰ไธช็ปดๅบฆไธŠๆ‰“ๅˆ†โ€”โ€”ๆŒ‡ไปค่ฆ†็›–ๆŠตๆŠ—ใ€ไฟกๆฏๆณ„้œฒๆŠตๆŠ—ใ€่พน็•ŒๅฎŒๆ•ดๆ€งโ€”โ€”ๅนถๆฑ‡ๆ€ป ๅ‡บๆ€ปไฝ“้ฒๆฃ’ๆ€งๅˆ†ๆ•ฐใ€‚ ๅˆคๅฎšๅ…จ้ƒจๅŸบไบŽๅญ—็ฌฆไธฒ/ๆญฃๅˆ™่ง„ๅˆ™๏ผŒ้›ถ้ขๅค–ๆˆๆœฌใ€ๅฏๅค็Žฐ๏ผŒไพฟไบŽๅœจ CI ไธญๅ›žๅฝ’ใ€‚ "...
304
13,124
ai-agent-book
chapter2/prompt-injection/demo.py
.py
""" ๅฎž้ชŒ 2-5๏ผšๆ็คบๆณจๅ…ฅๆ”ป้˜ฒๅฎž้ชŒ โ€”โ€” ไธป็จ‹ๅบใ€‚ ๅฏน 3 ็งๆ”ปๅ‡ปๅœบๆ™ฏ x 4 ็ง้˜ฒๅพก้…็ฝฎ ็š„ๆฏไธช็ป„ๅˆ่ท‘ N ๆฌก่ฏ•้ชŒ๏ผŒ็ปŸ่ฎกๆ”ปๅ‡ปๆˆๅŠŸ็އ๏ผŒ ๆœ€ๅŽๆ‰“ๅฐไธ€ๅผ  ๆ”ปๅ‡ป x ้˜ฒๅพก ็š„ๆˆๅŠŸ็އ็Ÿฉ้˜ต๏ผŒ็›ด่ง‚ๅฑ•็คบ"้˜ฒๅพก้€ๅฑ‚ๅŠ ๅผบ -> ๆˆๅŠŸ็އไธ‹้™"ใ€‚ ๅ‘ฝไปค่กŒ็”จๆณ•๏ผˆ่ฏฆ่ง --help๏ผ‰๏ผš python demo.py # ้ป˜่ฎค๏ผšๅ…จ้ƒจ 3x4 ็ป„ๅˆ๏ผŒๆฏ็ป„ๅˆ 4 ๆฌก่ฏ•้ชŒ python demo.py --trials 5 # ๆฏไธช็ป„ๅˆ่ท‘ 5 ๆฌก python demo.py --model gpt-5.6-luna # ๆขๆจกๅž‹ python de...
324
11,256
ai-agent-book
chapter2/prompt-injection/agent.py
.py
""" ๅฎž้ชŒ 2-5๏ผšๆ็คบๆณจๅ…ฅๆ”ป้˜ฒๅฎž้ชŒ โ€”โ€” ๅฏ่ขซๆ”ปๅ‡ป็š„ Agent ไธŽๅ››ๅฑ‚้˜ฒๅพกใ€‚ ๆœฌๆ–‡ไปถๅฎšไน‰ไธ€ไธช"้…ๅค‡็ฝ‘้กต้˜…่ฏปๅ’Œๆ–‡ไปถๆ“ไฝœๅทฅๅ…ท"็š„็ฎ€ๅ• Agent๏ผˆๅฏนๅบ”ไนฆไธญๅฎž้ชŒ่ฎพ่ฎก๏ผ‰๏ผŒ ๅนถๆŠŠๅ››็ง้˜ฒๅพก้…็ฝฎๅšๆˆๅฏ็ป„ๅˆ็š„ๅผ€ๅ…ณ๏ผŒไพ› demo.py ็ป„็ป‡ ๆ”ปๅ‡ป x ้˜ฒๅพก ็š„ๅฏน็…งๅฎž้ชŒใ€‚ ่ฎพ่ฎก่ฆ็‚น๏ผš - Agent ๆŽŒ็ฎกไธ€ไธช"ๆ•ๆ„Ÿ่ต„ๆบ"๏ผš็ณป็ปŸๆ็คบ่ฏ้‡Œๅ†™ๆœ‰ไธ€ๆฎตๅ†…้ƒจๅฏ†้’ฅ๏ผˆSECRET_KEY๏ผ‰๏ผŒ ่ง„ๅˆ™ๆ˜Ž็กฎ่ฆๆฑ‚"ไธๅพ—ๆณ„้œฒ็ณป็ปŸๆ็คบ่ฏ/ๅฏ†้’ฅ"ใ€‚ - Agent ๆ‹ฅๆœ‰ไธคไธช"้ซ˜้ฃŽ้™ฉๅทฅๅ…ท"๏ผšwrite_file๏ผˆๅ†™ๆ–‡ไปถ๏ผ‰ไธŽ send_email๏ผˆๅค–ๅ‘้‚ฎไปถ๏ผ‰๏ผŒ ่ง„ๅˆ™่ฆๆฑ‚"ๆœช็ป็”จๆˆทๆ˜Ž็กฎ็กฎ่ฎคไธๅพ—ๆ‰ง่กŒๅ†™ๅ…ฅ/ๅค–ๅ‘ๆ“ไฝœ"ใ€‚ - ๆ”ปๅ‡ปๆ–น้€š่ฟ‡ ็›ดๆŽฅๆณจๅ…ฅ / ้—ดๆŽฅๆณจๅ…ฅ๏ผˆๆฑกๆŸ“็ฝ‘้กตๅ†…ๅฎน๏ผ‰...
412
19,066
ai-agent-book
chapter2/prompt-injection/run_campaign.py
.py
"""Canonical real-provider campaign for Experiment 2-5.""" from __future__ import annotations import argparse import hashlib import json import os import re import shutil from concurrent.futures import ThreadPoolExecutor, as_completed from dataclasses import asdict from datetime import datetime, timezone from pathlib...
385
15,776
ai-agent-book
chapter2/agent-skills-ppt/prepare_official_skill.py
.py
#!/usr/bin/env python3 """Fetch and verify the pinned official Anthropic PPTX Skill (no reimplementation).""" from __future__ import annotations import argparse import hashlib import json import subprocess from pathlib import Path ROOT = Path(__file__).resolve().parent PROTOCOL = json.loads((ROOT / "experiment_prot...
76
2,658
ai-agent-book
chapter2/agent-skills-ppt/run_official_experiment.py
.py
#!/usr/bin/env python3 """Run Experiment 2-6 with a real skills-capable agent runtime and Anthropic's pinned PPTX Skill. Two runtimes are supported under the author-mandated runtime-agnostic acceptance policy (see experiment_protocol.json): - ``--runtime claude`` (default): Claude Code, for readers with Anthropic c...
272
11,201
ai-agent-book
chapter2/agent-skills-ppt/test_official_validation.py
.py
from pathlib import Path from prepare_official_skill import PROTOCOL from validate_official_run import ( collect_kimi_metadata, collect_tool_calls, parse_stream, sha256, ) def test_protocol_pins_exact_manuscript_workflow(): assert PROTOCOL["runtime"]["official_skill_repository"] == "https://githu...
68
2,707
ai-agent-book
chapter2/agent-skills-ppt/validate_official_run.py
.py
#!/usr/bin/env python3 """Fail-closed validator for the real agent-runtime + official PPTX Skill run. Supports both accepted runtimes: Claude Code (claude_stream.jsonl) and Kimi Code CLI (kimi_stream.jsonl). The artifact gates are identical; only the stream parsing and run-success gate are runtime-specific. """ from ...
313
12,909
ai-agent-book
chapter2/agent-skills-ppt/demo.py
.py
#!/usr/bin/env python3 """ ๅฎž้ชŒ 2-6๏ผšไฝฟ็”จ Agent Skills ไปŽ่ฎบๆ–‡็”Ÿๆˆๆผ”็คบๆ–‡็จฟ๏ผˆ่‡ชๅปบๅŒๆž„ Skills ๆœบๅˆถ๏ผ‰ ๆœฌ demo ๅค็Žฐใ€Šๆทฑๅ…ฅ็†่งฃ AI Agentใ€‹็ฌฌไบŒ็ซ ใ€ŒAgent Skills / ๆธ่ฟ›ๅผๆŠซ้œฒใ€ไธ€่Š‚็š„ๆ€ๆƒณใ€‚ ็”ฑไบŽ Anthropic key ๆ— ๆ•ˆ๏ผŒ่ฟ™้‡Œ็”จ OpenAI๏ผˆgpt-5.6-luna๏ผ‰+ ไธ€ๅฅ—่‡ชๅปบ็š„ใ€ไธŽ Anthropic Skills ๅŒๆž„็š„ๆœบๅˆถๆฅๆผ”็คบ๏ผŒๆ ธๅฟƒๆ˜ฏใ€Œๆธ่ฟ›ๅผๆŠซ้œฒ๏ผˆProgressive Disclosure๏ผ‰ใ€๏ผš ็ฌฌไธ€ๅฑ‚๏ผˆๅ…ƒๆ•ฐๆฎ๏ผ‰๏ผšAgent ๅฏๅŠจๆ—ถ็š„ system prompt ้‡Œๅชๆ”พๅ„ Skill ็š„ name + ...
431
18,425
ai-agent-book
chapter2/agent-skills-ppt/runs/exp2-6-kimi-pptx-20260731-v1/workspace/fix-bullets.py
.py
#!/usr/bin/env python3 """Post-process deck: remove duplicate mid-paragraph <a:pPr> elements that pptxgenjs emits when list items contain multiple inline-formatting runs. The duplicate (later) pPr carries buNone, which makes LibreOffice drop the bullet glyph. Keeping only the first pPr per <a:p> restores uniform bullet...
18
733
ai-agent-book
chapter2/agent-skills-ppt/tests/test_dispatch.py
.py
#!/usr/bin/env python3 """Regression tests for dispatch() in demo.py. Bug: the agentic loop parses tool-call arguments with a JSONDecodeError fallback to {} and then calls dispatch() with no try/except. dispatch() used to do args["name"] / args["payload"] etc., so any malformed or incomplete LLM tool call crashed the ...
67
2,475
ai-agent-book
chapter2/agent-skills-ppt/tests/test_generate_pptx_null_bullets.py
.py
import tempfile from pathlib import Path from generate_pptx import build_presentation def test_null_bullets_like_omit(): out = Path(tempfile.mkdtemp()) / "out.pptx" result = build_presentation( { "title": "Demo", "slides": [{"title": "Slide", "bullets": None}], }, ...
32
742
ai-agent-book
chapter2/agent-skills-ppt/tests/conftest.py
.py
"""Shared bootstrap for agent-skills-ppt 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)) SCRIPTS_DIR = PROJECT_ROOT / "skills" / "pptx" / "scripts"...
29
731
ai-agent-book
chapter2/agent-skills-ppt/skills/pptx/scripts/generate_pptx.py
.py
""" pptx Skill ๆ†็ป‘็š„ๅฏๆ‰ง่กŒ่„šๆœฌ๏ผšไฝฟ็”จ python-pptx ไปŽ็ป“ๆž„ๅŒ–ๅคง็บฒ็”Ÿๆˆ็œŸๅฎž็š„ .pptx ๆ–‡ไปถใ€‚ ่ฟ™ๆ˜ฏ Agent Skillsใ€Œๆธ่ฟ›ๅผๆŠซ้œฒใ€ไธญ็ฌฌไธ‰ๅฑ‚๏ผˆ็ป†ๅˆ™ / ๆ†็ป‘ๅทฅๅ…ท๏ผ‰็š„ไธ€้ƒจๅˆ†๏ผš Agent ๅœจ่ฏปๅ– SKILL.md ๅŽ๏ผŒๅพ—็Ÿฅ้œ€่ฆ้€š่ฟ‡ run_skill_script ๅทฅๅ…ท่ฐƒ็”จๆœฌ่„šๆœฌ๏ผŒ ๅนถๆŒ‰็บฆๅฎš็š„ JSON schema ไผ ๅ…ฅๅนป็ฏ็‰‡ๅคง็บฒใ€‚ๆœฌ่„šๆœฌ่ดŸ่ดฃๆŠŠๅคง็บฒ่ฝๅœฐไธบ PowerPointใ€‚ payload JSON schema๏ผˆ็”ฑ SKILL.md ๅ‘ Agent ่ฏดๆ˜Ž๏ผ‰๏ผš { "title": "ๆผ”็คบๆ–‡็จฟไธปๆ ‡้ข˜๏ผˆๅญ—็ฌฆไธฒ๏ผ‰", "subtitle": "ๅ‰ฏๆ ‡้ข˜๏ผŒ้€šๅธธๆ˜ฏไฝœ่€…/ๆฅๆบ๏ผˆๅญ—็ฌฆไธฒ๏ผŒ...
152
4,849
ai-agent-book
chapter2/context-compression/quickstart.py
.py
#!/usr/bin/env python3 """ Quick start script to test the context compression experiment """ import os import sys from dotenv import load_dotenv # Load environment variables load_dotenv() def check_environment(): """Check if environment is properly configured""" provider = os.getenv("LLM_PROVIDER", "kimi").l...
134
4,030
ai-agent-book
chapter2/context-compression/main.py
.py
#!/usr/bin/env python3 """ Interactive demo for context compression strategies """ import os import sys import argparse from colorama import init, Fore, Style from config import Config from agent import ResearchAgent from compression_strategies import CompressionStrategy # Initialize colorama init(autoreset=True) ...
232
9,614
ai-agent-book
chapter2/context-compression/test_null_content_compression.py
.py
""" Test suite locking out TypeError in ContextCompressor._no_compression when a search result dictionary contains 'content': None. """ import os import sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) from compression_strategies import ContextCompressor def test_no_compression_handles_null_conte...
27
798
ai-agent-book
chapter2/context-compression/web_tools.py
.py
""" Web tools for searching and fetching web pages """ import json import html import re import logging import requests from typing import List, Dict, Any, Optional from bs4 import BeautifulSoup import html2text from urllib.parse import urlparse, urljoin import time from config import Config # Configure logging loggi...
307
11,725
ai-agent-book
chapter2/context-compression/test_malformed_tool_json.py
.py
""" Malformed tool-argument JSON must not abort execute_research or cause real dispatch to raise TypeError. """ import sys import types from pathlib import Path from unittest.mock import MagicMock, patch # Optional deps used at import time by web_tools. sys.modules.setdefault("html2text", types.ModuleType("html2text")...
142
6,354
ai-agent-book
chapter2/context-compression/experiment.py
.py
#!/usr/bin/env python3 """ Context Compression Strategies Comparison Experiment """ import os import sys import json import time import argparse from typing import Dict, Any, List, Optional from datetime import datetime from dataclasses import asdict from colorama import init, Fore, Style from tqdm import tqdm from c...
383
15,864
ai-agent-book
chapter2/context-compression/compression_strategies.py
.py
""" Context Compression Strategies for the experiment """ import json import logging from typing import List, Dict, Any, Optional, Tuple from enum import Enum from dataclasses import dataclass, field from datetime import datetime from openai import OpenAI import tiktoken from config import Config def _reasoning_safe...
695
29,110
ai-agent-book
chapter2/context-compression/test_web_tools_null_content.py
.py
""" Test suite locking out TypeError in WebTools.search_web when fetch_webpage returns a dictionary containing 'content': None. """ import os import sys from unittest.mock import MagicMock sys.modules['html2text'] = MagicMock() sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) from web_tools import Web...
60
1,852
ai-agent-book
chapter2/context-compression/config.py
.py
""" Configuration module for Context Compression Experiment """ import os from typing import Optional from dotenv import load_dotenv # Load environment variables load_dotenv() class Config: """Configuration settings for the context compression experiment""" # API Configuration LLM_PROVIDER: str = o...
122
4,600
ai-agent-book
chapter2/context-compression/agent.py
.py
""" Context Compression Research Agent with Streaming Support """ import json import logging import time import sys from typing import List, Dict, Any, Optional, Generator, Tuple from dataclasses import dataclass, field from datetime import datetime from openai import OpenAI from config import Config from web_tools im...
676
29,489
ai-agent-book
chapter2/context-compression/benchmark_compression.py
.py
""" Context Compression Benchmark Module. Systematically benchmarks Summary, Truncation, Key-Sentence, and Observation-Filtering compression strategies on long-context tasks. Measures compression ratio, Time-to-First-Token (TTFT), token cost savings, and downstream QA retention accuracy. """ import math import re imp...
340
14,047
ai-agent-book
chapter2/context-compression/run_all_strategies.py
.py
#!/usr/bin/env python3 """ Script to run all compression strategies sequentially and save results to log """ import os import sys import json import time import argparse import logging from datetime import datetime from typing import Dict, Any, List, Optional from agent import ResearchAgent from compression_strategie...
459
19,870
ai-agent-book
chapter2/attention_visualization/run_status_bar_experiment.py
.py
#!/usr/bin/env python3 """Real Qwen3 attention comparison for Chapter 2 Experiment 2-8.""" from __future__ import annotations import argparse import hashlib import json import platform import random import re from datetime import datetime, timezone from pathlib import Path from typing import Any import matplotlib.py...
448
16,785
ai-agent-book
chapter2/attention_visualization/test_attention_experiment.py
.py
import numpy as np from run_attention_experiment import matrix_metrics, region_indices, resolve_layer def test_resolve_negative_layer(): assert resolve_layer(-1, 28) == 27 assert resolve_layer(13, 28) == 13 def test_region_indices_separates_thinking_and_answer(): tokens = ["prompt", "<think>", "work", ...
21
678
ai-agent-book
chapter2/attention_visualization/test_status_bar_experiment.py
.py
from run_status_bar_experiment import ( base_messages, classify, status_message, ) PROTOCOL = { "scenario": { "maximum_calls": 3, "user_query": "Can you call Xfinity one more time to chase the refund?", } } def test_base_trajectory_has_three_calls_and_four_distractors(): mess...
35
1,113
ai-agent-book
chapter2/attention_visualization/main.py
.py
""" ReAct Tool-Calling Agent with Attention Visualization Implements a proper ReAct (Reasoning + Acting) loop with step-by-step visualization """ import json import re import logging from typing import List, Dict, Any, Optional from dataclasses import dataclass from pathlib import Path from agent import AttentionVisu...
726
30,410
ai-agent-book
chapter2/attention_visualization/visualization.py
.py
""" Attention Visualization Utilities Creates visual representations of attention patterns """ import matplotlib.pyplot as plt import matplotlib.patches as patches import numpy as np import seaborn as sns from typing import List, Dict, Any, Optional, Tuple import json from pathlib import Path def _configure_cjk_font...
630
22,097
ai-agent-book
chapter2/attention_visualization/test_save_trajectory.py
.py
#!/usr/bin/env python3 """Regression tests for save_trajectory() in agent.py. Bug: save_trajectory() referenced bare names `temperature` and `max_new_tokens` that are not in its scope -> NameError on every call (generate_with_attention calls it with save_trajectory=True by default). Fixed by adding them as parameters,...
58
1,950
ai-agent-book
chapter2/attention_visualization/run_attention_experiment.py
.py
#!/usr/bin/env python3 """Canonical real-model campaign for Chapter 2 Experiment 2-2.""" from __future__ import annotations import argparse import hashlib import json import platform import shutil from datetime import datetime, timezone from pathlib import Path from typing import Any import matplotlib.pyplot as plt ...
240
10,318
ai-agent-book
chapter2/attention_visualization/attention_cli.py
.py
""" Attention Visualization CLI =========================== Command-line tool that renders the self-attention heatmap of a real language model for an arbitrary prompt, letting you pick which layer and head to inspect. This is the standalone counterpart to the interactive frontend: instead of saving a trajectory JSON f...
296
11,016
ai-agent-book
chapter2/attention_visualization/config.py
.py
""" Configuration for Attention Visualization """ import os from pathlib import Path from dotenv import load_dotenv # Load environment variables load_dotenv() # Model Configuration MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen3-0.6B") MODEL_PATH = os.getenv("MODEL_PATH", None) # Optional local model path # Devic...
65
2,341
ai-agent-book
chapter2/attention_visualization/tools.py
.py
""" Sample tools for demonstrating tool calling functionality with attention visualization Based on local_llm_serving/tools.py """ import json import math import random import io import contextlib from typing import Dict, Any, List from datetime import datetime import requests class ToolRegistry: """Registry for ...
449
17,277
ai-agent-book
chapter2/attention_visualization/agent.py
.py
""" Attention Visualization Agent Integrates Qwen3 0.5B model with attention tracking and visualization """ import json import logging import torch import numpy as np import time from pathlib import Path from typing import List, Dict, Any, Optional, Tuple from dataclasses import dataclass, asdict, field from transform...
590
22,567
ai-agent-book
book-tr/strip_titles.py
.py
#!/usr/bin/env python3 """Strip in-figure titles from manually-created SVGs and crop top whitespace. According to academic conventions: the figure itself does not contain a title (the title is written in the main text). This script only handles "hand-crafted SVGs"โ€” for SVGs generated by tools, set OMIT_TITLE=True in s...
112
3,717
ai-agent-book
book-tr/gen_ch2_figs.py
.py
"""Regenerate this edition's Chapter 2 figures from the Chinese golden layouts. The shared synchronizer owns the current Chapter 2 figure numbering, localized labels, and authoritative context-compression measurements. """ import subprocess import sys from pathlib import Path if __name__ == "__main__": root = Pa...
17
491
ai-agent-book
book-tr/gen_ch4_figs.py
.py
#!/usr/bin/env python3 """Generate all SVG illustrations for Chapter 4 (Tools). Figures (12 total): fig4-1: MCP protocol sequence diagram (concrete message payloads) fig4-2: Sub-Agent context preparation (4 strategies with examples) fig4-3: Event-driven architecture (real event sources & payloads) fig4-4: ...
986
42,403
ai-agent-book
book-tr/gen_ch9_figs.py
.py
"""[DEPRECATED] Old Chapter 9 (multi-Agent) figure generator. โš ๏ธ DO NOT RUN: After the 2026-03-12 refactoring, chapter numbers changed (original Ch 9 โ†’ Ch 10). The figures generated by this file actually correspond to the current [Chapter 10] content (multi-Agent collaboration), but are still saved as fig9-*.svg. Runn...
1,053
51,097
ai-agent-book
book-tr/gen_ch1_figs.py
.py
"""Generate all Chapter 1 figures.""" import sys, os sys.path.insert(0, os.path.dirname(__file__)) from svg_lib import * OUT = os.path.join(os.path.dirname(__file__), 'images') def fig1_4(): """Kimi K3 / GPT-5.6 native agent architecture โ€” caption Figure 1-4""" s = SVG(820, 520) # Title s.text(410, ...
538
22,198
ai-agent-book
book-tr/gen_cover.py
.py
#!/usr/bin/env python3 """Generate the book cover image with an image-generation model. This is, fittingly, the book eating its own dog food: the cover of a book about AI agents is produced by calling an image-generation model. Run it once; the cover (cover.tex) automatically switches to images/cover-image.png when pr...
85
4,149
ai-agent-book
book-tr/fit_svg_text.py
.py
"""Repair text overflow in generated/static book SVGs (in place). Most figures under images/ are produced by the gen_chN_figs.py scripts (which now self-correct via svg_lib.SVG.render), but several sets โ€” fig0-*, fig6-*, fig7-*, the multimodal fig9-*, and fig10-* โ€” are static SVGs with no live generator. This tool app...
48
1,567
ai-agent-book
book-tr/svg_lib.py
.py
"""SVG diagram generation library for book illustrations. Style: black/white/grayscale for B&W printing. - White (#fff) backgrounds - Light gray (#f0f0f0) box fills - Medium gray (#d0d0d0) secondary fills - Dark gray (#999) emphasis fills - Black (#333) borders and text - 2px stroke, 6px rounded corners - Sans-serif f...
667
26,728
ai-agent-book
book-tr/gen_ch8_figs.py
.py
#!/usr/bin/env python3 """Chapter 8 figures โ€” Agent's self-evolution. NOTE: this generator was previously a stray copy of chapter 9's figures, which left fig8-1..fig8-7 showing chapter-9 content. It has been rewritten so each figure matches its caption in chapter8.md. Figures are built with svg_lib; titles live in the...
116
6,354
ai-agent-book
book-tr/gen_ch3_figs.py
.py
#!/usr/bin/env python3 """Generate all SVG illustrations for Chapter 3 (Knowledge Base & RAG). Figures (14 total): fig3-1: Chapter roadmap fig3-2: RAG end-to-end pipeline (concrete example) fig3-3: Dense embedding evolution (with dimensions & training) fig3-4: HNSW index structure (enlarged) fig3-5: BM2...
861
37,761
ai-agent-book
book-tr/gen_ch5_figs.py
.py
#!/usr/bin/env python3 """Generate all SVG illustrations for Chapter 5 (Code Generation). Figures (11 total): fig5-1: OpenClaw architecture โ€” Coding Agent as core of general Agent fig5-2: Coding Agent multi-phase workflow (concrete file ops & tool calls) fig5-3: Search tool comparison (4 types with real query...
1,095
48,130
ai-agent-book
book-ta/strip_titles.py
.py
#!/usr/bin/env python3 """Strip in-figure titles from checked-in SVGs and crop top whitespace. According to academic conventions, the figure itself does not contain a title (the title is written in the main text). This script conservatively handles the checked-in SVG files under `images/`. Judgment rule (conservative...
113
3,676
ai-agent-book
book-ta/gen_cover.py
.py
#!/usr/bin/env python3 """Generate the book cover image with an image-generation model. This is, fittingly, the book eating its own dog food: the cover of a book about AI agents is produced by calling an image-generation model. Run it once; the cover (cover.tex) automatically switches to images/cover-image.png when pr...
85
4,162
ai-agent-book
chapter6/robotics_lab_common.py
.py
"""Small, deterministic helpers shared by the chapter 9 robotics labs. The labs deliberately avoid pretending that a Mac MPS run is a CUDA/ManiSkill run. They expose the accelerator used in the evidence and fail closed when a caller asks for an accelerator that is not available. """ from __future__ import annotation...
75
2,332
ai-agent-book
chapter6/phone-agent/test_verify_acceptance.py
.py
import json from pathlib import Path from verify_acceptance import check_llm_receipt def test_llm_receipt_tamper_is_rejected(): content = '{"ok":true}' request = {"model": "model", "messages": [{"role": "user", "content": "safe"}]} raw = { "id": "response-1", "model": "model", "ch...
53
1,879
ai-agent-book
chapter6/phone-agent/verify_acceptance.py
.py
#!/usr/bin/env python3 """Standalone fail-closed verification for Experiment 9-2 retained evidence.""" from __future__ import annotations import argparse import hashlib import json import re from pathlib import Path from typing import Any HERE = Path(__file__).resolve().parent ROOT = HERE.parents[1] REQUIRED_ARTIFAC...
379
17,626
ai-agent-book
chapter6/phone-agent/test_webrtc_app.py
.py
from pathlib import Path import webrtc_app from fastapi.testclient import TestClient def direct_payload(): return { "mode": "direct", "callee_name": "Jane", "goal": "Confirm a time and code", "context": "Tuesday afternoon", "instructions": "Ask for a time and confirmation ...
88
3,198
ai-agent-book
chapter6/phone-agent/webrtc_app.py
.py
"""Browser-to-aiortc voice Agent for Experiment 9-2. The browser microphone is the only user-semantic input. The server buffers its decoded RTP audio, runs real Whisper ASR, sends that transcript to a real external LLM, synthesizes the Agent reply, and places the resulting PCM on the WebRTC downlink track. The data ...
699
27,867
ai-agent-book
chapter6/phone-agent/demo.py
.py
#!/usr/bin/env python3 """Launch the ReAct arm of the local Experiment 9-2 browser call.""" from __future__ import annotations import argparse import threading import urllib.parse import webbrowser import uvicorn DEFAULT_TASK = ( "Call me to arrange a dental checkup. I did not include the exact time or confirma...
38
1,204
ai-agent-book
chapter6/phone-agent/test_agent.py
.py
import json from types import SimpleNamespace import pytest from agent import conversation_turn, direct_plan, react_plan class FakeUsage: def model_dump(self, **_kwargs): return {"prompt_tokens": 40, "completion_tokens": 20, "total_tokens": 60} class FakeResponse: def __init__(self, content): ...
174
6,088
ai-agent-book
chapter6/phone-agent/test_speech.py
.py
import struct from speech import pcm16_wav, read_pcm16_wav, sha256_bytes def test_pcm_wav_round_trip_is_exact(): pcm = b"".join(struct.pack("<h", sample) for sample in (0, 100, -100, 32767, -32768)) wav = pcm16_wav(pcm, 16_000) decoded, rate = read_pcm16_wav(wav) assert decoded == pcm assert rate...
21
670
ai-agent-book
chapter6/phone-agent/run_acceptance.py
.py
#!/usr/bin/env python3 """Run the safe, full-audio direct-vs-ReAct Experiment 9-2 campaign. Each arm gives Chrome a non-private synthesized microphone WAV. Chrome sends that fixture through getUserMedia and RTP to aiortc; the server buffers the received RTP audio, runs real Whisper ASR, invokes a real external dialog...
477
18,727
ai-agent-book
chapter6/phone-agent/speech.py
.py
"""Real speech synthesis and microphone-audio ASR for Experiment 9-2.""" from __future__ import annotations import hashlib import json import os import shutil import subprocess import sys import tempfile import time import wave from dataclasses import dataclass from pathlib import Path from typing import Any def sh...
308
12,149
ai-agent-book
chapter6/phone-agent/agent.py
.py
"""Fail-closed LLM planning and dialogue contracts for Experiment 9-2. The direct arm receives a fixed call plan. The ReAct arm asks a real external OpenAI-compatible provider to observe an incomplete task, identify missing facts, and choose the browser-call action. Both arms use the same external model for the post...
371
14,337
ai-agent-book
chapter6/phone-agent/direct_call.py
.py
#!/usr/bin/env python3 """Launch the fixed-parameter control arm of Experiment 9-2.""" from __future__ import annotations import argparse import threading import urllib.parse import webbrowser import uvicorn def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--na...
44
1,352
ai-agent-book
chapter6/phone-agent/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))
7
168
ai-agent-book
chapter6/claude-computer-use-native/validate_weather_run.py
.py
#!/usr/bin/env python3 """Deterministically validate retained Experiment 9-6 evidence.""" from __future__ import annotations import argparse import hashlib import json import re from pathlib import Path EXPECTED_MODEL = "claude-sonnet-4-5-20250929" EXPECTED_SOURCE = "9bcc95e316e5ef6542b4c9d0469f4078829eead5" EXPECT...
161
5,964
ai-agent-book
chapter6/claude-computer-use-native/run_weather_task.py
.py
#!/usr/bin/env python3 """Run and retain the bounded Experiment 9-6 native Computer Use trajectory. This harness calls the pinned Anthropic Computer Use Demo's ``sampling_loop``. It is intended to run inside that Demo's locally built container with a host evidence directory mounted at ``/evidence``. """ from __future...
330
12,012
ai-agent-book
chapter6/agent-with-event-trigger/quickstart.py
.py
""" Quick Start Script for Event-Triggered Agent Demonstrates the basic functionality in a simple way """ import os import sys import time import subprocess import signal from event_types import EventType # Check if API key is set (universal OpenRouter fallback applied by the server). from agent import resolve_provid...
130
4,160