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 | chapter4/perception-tools/run_experiment_4_1.py | .py | #!/usr/bin/env python3
"""Run Experiment 4-1 through the real perception MCP stdio transport.
The campaign exercises every sub-capability explicitly named by the manuscript.
It creates small local documents/media as deterministic inputs, uses live public
endpoints for network observations, confines mutation tools to a... | 706 | 31,883 |
ai-agent-book | chapter4/perception-tools/test_youtube_tools.py | .py | """
Real API tests for YouTube transcript extraction.
These tests make actual API calls to YouTube to verify functionality.
"""
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 multimodal_tools import extract_you... | 260 | 8,855 |
ai-agent-book | chapter4/perception-tools/test_arxiv_request_bounds.py | .py | """Offline regression test for bounded official arXiv API pages."""
from __future__ import annotations
import asyncio
import json
import sys
from datetime import datetime, timezone
from pathlib import Path
from types import SimpleNamespace
SRC = Path(__file__).resolve().parent / "src"
sys.path.insert(0, str(SRC))
i... | 97 | 2,831 |
ai-agent-book | chapter4/perception-tools/test_analyze_video_release_on_error.py | .py | """Regression test: analyze_video_ai must release the VideoCapture even when a
per-frame Vision API call raises mid-loop.
The capture was previously released only on the success path, so a failing
Vision call (network / rate-limit / auth) leaked the native decoder/file handle
until GC. Release now happens in a finally... | 102 | 3,274 |
ai-agent-book | chapter4/perception-tools/test_video_keyframes_num_frames.py | .py | """Regression test: num_frames=0 must not cause ZeroDivisionError.
The LLM-supplied num_frames parameter was used directly as a divisor in
`frame_count // num_frames`; num_frames=0 crashed with ZeroDivisionError
(surfacing as a confusing tool error). It is now clamped to >= 1 up front.
"""
import asyncio
import json
i... | 70 | 2,309 |
ai-agent-book | chapter4/perception-tools/test_document_tools.py | .py | """
Tests for document processing tools.
Uses real 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 document_processing_tools import (
extract_pdf_text,
extract_docx_content,
extr... | 182 | 5,532 |
ai-agent-book | chapter4/perception-tools/cli.py | .py | #!/usr/bin/env python3
"""
感知工具 MCP 服务器 —— 统一命令行入口(实验 4-1)。
除了以 MCP stdio 协议对外提供服务(见 src/main.py),本文件提供一个不依赖
MCP 客户端的命令行入口,方便直接列出、调用和演示各类感知工具:
python cli.py list # 按五大类列出全部感知工具
python cli.py info <tool> # 查看某个工具的参数签名
python cli.py run <tool> k=v ... # 直接调用某个工具并打印 JSON 结果
pyt... | 509 | 24,738 |
ai-agent-book | chapter4/perception-tools/test_parse_page_range_trailing_comma.py | .py | """Trailing commas in page_range must not crash parse_page_range."""
import importlib.util
from pathlib import Path
_SRC = Path(__file__).resolve().parent / "src" / "document_processing_tools.py"
_spec = importlib.util.spec_from_file_location("document_processing_tools_page_range", _SRC)
_mod = importlib.util.module_f... | 34 | 1,064 |
ai-agent-book | chapter4/perception-tools/test_pubchem_tools.py | .py | """
Real API tests for PubChem tools.
These tests make actual API calls to PubChem to verify functionality.
"""
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 pubchem_tools import (
search_compounds,
ge... | 328 | 10,442 |
ai-agent-book | chapter4/perception-tools/test_filesystem_mutations.py | .py | """Safety and receipt checks for Experiment 4-1 filesystem mutations."""
from __future__ import annotations
import asyncio
import json
import sys
from pathlib import Path
import pytest
SRC = Path(__file__).resolve().parent / "src"
sys.path.insert(0, str(SRC))
from filesystem_tools import copy_path, delete_path, mo... | 77 | 2,970 |
ai-agent-book | chapter4/perception-tools/test_experiment_4_1.py | .py | """Offline acceptance checks for the exact Experiment 4-1 campaign."""
from __future__ import annotations
import importlib.util
import json
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
RUNNER = HERE / "run_experiment_4_1.py"
SPEC = importlib.util.spec_from_file_location("experiment_4_1_... | 148 | 5,133 |
ai-agent-book | chapter4/perception-tools/test_pubchem_async.py | .py | """Deterministic regressions for PubChem asynchronous ListKey handling."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent / "src"))
from pubchem_tools import PubChemClient
class _Response:
def __init__(self, status_code, payload):
self.status_code = status_code
... | 53 | 1,611 |
ai-agent-book | chapter4/perception-tools/test_expanded_catalog.py | .py | """Offline contract checks for the real-backed 126-tool perception catalog."""
from __future__ import annotations
import asyncio
import json
import sys
from pathlib import Path
import tiktoken
SRC = Path(__file__).resolve().parent / "src"
sys.path.insert(0, str(SRC))
import expanded_catalog # noqa: E402
import ma... | 61 | 2,252 |
ai-agent-book | chapter4/perception-tools/src/test_negative_max_length.py | .py | """Regression: negative max_length must not drop the last character."""
import asyncio
import json
import sys
import types
from pathlib import Path
import pytest
def _stub():
for name in ["dotenv", "requests", "mcp", "mcp.types", "mcp.server"]:
sys.modules.setdefault(name, types.ModuleType(name))
sys... | 46 | 1,372 |
ai-agent-book | chapter4/perception-tools/src/test_csv_max_rows.py | .py | """Regression: extract_csv_content must honor max_rows in data, not hard-cap at 100."""
import json
from pathlib import Path
import pandas as pd
import pytest
from document_processing_tools import extract_csv_content
@pytest.mark.asyncio
async def test_csv_data_honors_max_rows(tmp_path: Path):
path = tmp_path /... | 21 | 616 |
ai-agent-book | chapter4/perception-tools/src/public_data_tools.py | .py | """
Public data source tools: weather, stocks, currency, Wiki, ArXiv, Wayback Machine.
"""
import json
import logging
import os
import time
import traceback
from datetime import datetime
from typing import Union
import requests
from dotenv import load_dotenv
from mcp.types import TextContent
from pydantic import BaseM... | 863 | 28,054 |
ai-agent-book | chapter4/perception-tools/src/main.py | .py | """
Main MCP server for perception tools.
This MCP server provides comprehensive perception capabilities including:
- Search tools (web search, knowledge base, file download)
- Multimodal understanding (web pages, documents, images, videos)
- File system operations (read, grep, summarization)
- Public data sources (we... | 705 | 28,606 |
ai-agent-book | chapter4/perception-tools/src/yahoo_finance_tools.py | .py | """
Yahoo Finance comprehensive tools.
Based on AWorld MCP server implementation.
Provides stock quotes, historical data, company info, and financial statements.
"""
import json
import logging
import time
import traceback
from datetime import datetime
from typing import Union, Literal
import yfinance as yf
from dotenv... | 438 | 14,870 |
ai-agent-book | chapter4/perception-tools/src/test_search_web_num_results_zero.py | .py | """Regression test for search_web num_results=0 handling.
Proves contract: Requesting zero search results short-circuits external search
providers and returns success with empty result list and count 0.
Locks out bug where max(1, min(num_results, 10)) clamped num_results=0 to 1.
"""
import json
import sys
import type... | 67 | 1,952 |
ai-agent-book | chapter4/perception-tools/src/search_tools.py | .py | """
Search tools: knowledge base, web search, and file download.
"""
import json
import logging
import os
import time
import traceback
from pathlib import Path
from typing import Union
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from mcp.types import TextContent
from pydantic import Ba... | 432 | 15,267 |
ai-agent-book | chapter4/perception-tools/src/media_processing_tools.py | .py | """
Media processing tools for audio, image, and video.
Based on AWorld MCP server implementation.
"""
import json
import logging
import traceback
import subprocess
import base64
import os
import time
from pathlib import Path
from typing import Union, Dict, Any
import cv2
from PIL import Image
from dotenv import load_... | 859 | 27,928 |
ai-agent-book | chapter4/perception-tools/src/private_data_tools.py | .py | """
Private data source tools: Google Calendar, Notion.
"""
import json
import logging
import os
import traceback
from datetime import datetime, timedelta
from typing import Union
from dotenv import load_dotenv
from mcp.types import TextContent
from base import ActionResponse
load_dotenv()
async def get_calendar_... | 271 | 8,552 |
ai-agent-book | chapter4/perception-tools/src/__init__.py | .py | """
Perception Tools MCP Server
A comprehensive MCP server for perception and data retrieval capabilities.
"""
__version__ = "1.0.0"
| 8 | 135 |
ai-agent-book | chapter4/perception-tools/src/document_processing_tools.py | .py | """
Document processing tools for PDF, DOCX, PPTX, CSV, TXT.
Based on AWorld MCP server implementation.
"""
import json
import logging
import traceback
from pathlib import Path
from typing import Union, Dict, Any
import pandas as pd
from docx import Document
from pptx import Presentation
import PyPDF2
from dotenv impo... | 345 | 10,320 |
ai-agent-book | chapter4/perception-tools/src/expanded_catalog.py | .py | """Expanded, real-backed perception tool catalog for Experiments 4-1 and 4-6.
The book's active-discovery experiment requires the perception MCP server to
expose 120+ tools. The native server exposes 56 useful tools; this module adds
70 narrowly named, read-mostly tools backed by real local operations or
public APIs. ... | 1,036 | 74,828 |
ai-agent-book | chapter4/perception-tools/src/pubchem_tools.py | .py | """
PubChem chemical compound data tools.
Based on AWorld MCP server implementation.
"""
import json
import logging
import time
import traceback
from typing import Union, Literal
from urllib.parse import quote, urlsplit, urlunsplit
import requests
from dotenv import load_dotenv
from mcp.types import TextContent
from p... | 545 | 18,686 |
ai-agent-book | chapter4/perception-tools/src/wayback_enhanced.py | .py | """
Enhanced Wayback Machine tools.
"""
import json
import logging
import traceback
from typing import Union
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from mcp.types import TextContent
from waybackpy import WaybackMachineCDXServerAPI
from base import ActionResponse
load_dotenv()
... | 84 | 2,180 |
ai-agent-book | chapter4/perception-tools/src/arxiv_enhanced.py | .py | """
Enhanced ArXiv tools with download and details.
Based on AWorld parxiv-server complete implementation.
"""
import hashlib
import json
import logging
import os
import re
import traceback
from typing import Union
import arxiv
import httpx
from dotenv import load_dotenv
from mcp.types import TextContent
from base im... | 210 | 6,132 |
ai-agent-book | chapter4/perception-tools/src/google_search_enhanced.py | .py | """
Enhanced Google Search tools.
Based on AWorld google-search server.
"""
import json
import logging
import os
import traceback
from typing import Union
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from mcp.types import TextContent
from base import ActionResponse
load_dotenv()
as... | 210 | 6,282 |
ai-agent-book | chapter4/perception-tools/src/multimodal_tools.py | .py | """
Multimodal understanding tools: web, documents, images, and videos.
"""
import json
import logging
import os
import traceback
from pathlib import Path
from typing import Optional, Union
import base64
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from mcp.types import TextContent
from... | 584 | 18,892 |
ai-agent-book | chapter4/perception-tools/src/wiki_enhanced.py | .py | """
Enhanced Wikipedia tools with full article access.
Based on AWorld wiki-server complete implementation.
"""
import json
import logging
import traceback
import calendar
from datetime import datetime
from typing import Union
import requests
import wikipedia
from dotenv import load_dotenv
from mcp.types import TextCo... | 270 | 7,448 |
ai-agent-book | chapter4/perception-tools/src/filesystem_tools.py | .py | """File-system perception tools and tightly scoped mutation helpers.
Read operations retain their historical behavior. Move, copy, and delete are
available only beneath the directory named by ``PERCEPTION_MUTATION_ROOT``.
They reject absolute paths, traversal, symlinks, and the private quarantine
directory. Delete a... | 582 | 20,049 |
ai-agent-book | chapter4/perception-tools/src/base.py | .py | """
Base models and utilities for perception tools MCP server.
"""
import logging
import os
import tempfile
import traceback
from pathlib import Path
from urllib.parse import urlparse
from typing import Any
import requests
from pydantic import BaseModel, Field
class ActionResponse(BaseModel):
"""Standard respons... | 143 | 4,698 |
ai-agent-book | chapter4/perception-tools/src/test_grep_max_results_zero.py | .py | """Regression: grep_search(max_results=0) must return zero hits, not one."""
import json
import sys
import types
from pathlib import Path
import pytest
def _stub():
for name in ["dotenv", "requests", "mcp", "mcp.types", "mcp.server"]:
sys.modules.setdefault(name, types.ModuleType(name))
sys.modules["... | 60 | 1,757 |
ai-agent-book | chapter4/active-tool-discovery/test_exact_experiment.py | .py | """Contract tests for the exact Experiment 4-7 runner (no model/API calls)."""
from __future__ import annotations
import asyncio
import importlib.util
import json
import sys
from copy import deepcopy
from pathlib import Path
import pytest
HERE = Path(__file__).resolve().parent
RUNNER_PATH = HERE / "run_exact_experi... | 191 | 6,933 |
ai-agent-book | chapter4/active-tool-discovery/run_exact_experiment.py | .py | #!/usr/bin/env python3
"""Run the exact Chapter 4 Experiment 4-7 contract.
Unlike the original mechanism demo, this runner:
* obtains 126 complete schemas from the perception MCP server via stdio;
* uses exactly local Ollama ``qwen3:4b`` for both groups;
* asserts that the control catalog exceeds 50K measured tokens;... | 1,215 | 57,704 |
ai-agent-book | chapter4/active-tool-discovery/discovery.py | .py | """
主动工具发现的核心:用嵌入向量相似度,从 126 个工具里
按自然语言"能力需求"检索出最相关的 3-5 个候选工具。
- 工具向量:对每个工具用 "name: description" 生成 embedding,并缓存到本地
.cache/tool_embeddings_<embedder>.json,避免每次运行都重新计算。
- discover_tools(need):把 need 向量化,与工具向量做余弦相似度,返回 top-k。
嵌入后端是可插拔的(见 `Embedder` 协议):
- OpenAIEmbedder:调用 OpenAI embeddings API(默认,联网,效果最好)。
- 离线模式(... | 103 | 4,121 |
ai-agent-book | chapter4/active-tool-discovery/demo.py | .py | """
实验 8-4 演示:主动工具发现 vs 检索预筛选 vs 全量注入
对同一组跨领域任务,在 126 个工具的工具库上分别用三种"工具发现"策略运行,
并在一次运行里输出可对比的表格(准确率 / 注入 token / 延迟):
- full_injection 全量注入:126 个工具 schema 一次性进上下文(对照组,书中控制组)。
- retrieval_prefilter 检索预筛选:按初始查询做**一次性**语义检索,只注入 top-n 候选工具。
- active_discovery 主动发现:少量基础工具 + discover_tools 元工具,执行中按需检索加载。
核心论点(第 8 章):当工... | 265 | 13,484 |
ai-agent-book | chapter4/active-tool-discovery/offline_backend.py | .py | """
离线后端:让整条流水线在**没有 OpenAI key** 时也能跑通,用于验证机制、
量化 token/延迟,并让读者零成本复现"三种策略"的对比结构。
包含两部分:
1) LocalEmbedder —— 本地哈希词袋嵌入(中文字 unigram/bigram + 英文词),
无需联网即可支撑 discover_tools / 检索预筛选的语义相似度。
2) MockChatClient —— 一个确定性的"脚本化"模型,接口与 OpenAI 客户端一致
(client.chat.completions.create(...).choices[0].message.content)。
它按关键词把任务... | 196 | 8,985 |
ai-agent-book | chapter4/active-tool-discovery/tools_library.py | .py | """
实验 8-4 工具库:120+ 个跨领域工具定义。
设计要点:
1) 每个工具都有真实可读的 name / description / parameters(OpenAI function schema)。
2) 领域覆盖 finance / news / web / arxiv / file / github / code / geo / weather /
media / language / email / db / ecommerce / social / crypto / util 等。
3) 故意混入大量"通用/近义"工具(web_search / universal_search / quick_ans... | 476 | 26,750 |
ai-agent-book | chapter4/active-tool-discovery/agent.py | .py | """
三种工具发现策略的 Agent 循环(文本/ReAct 协议)。
为什么用"文本注入 + 文本解析工具调用"而不是 OpenAI 原生 function calling?
—— 本实验要复现的正是书中所述:把 120+ 工具 schema **一次性注入 system prompt(几万 token)**,
模型在超长上下文下"指令遵循退化"。OpenAI 原生 function-calling 接口对工具选择做了很强的
约束/优化,即使上百个工具也很少选错,无法体现该退化;而把 schema 当作纯文本塞进 prompt、
让模型自己以 JSON 形式输出工具调用,才是书中控制组的真实机制,也才能观察到... | 282 | 13,838 |
ai-agent-book | chapter4/multimodal-agent/quickstart.py | .py | """
Quickstart script for testing multimodal agent
Creates sample files and demonstrates capabilities
"""
import asyncio
import base64
from pathlib import Path
import os
from agent import MultimodalAgent, MultimodalContent
from config import ExtractionMode, Config
def create_sample_files():
"""Create sample fil... | 232 | 7,236 |
ai-agent-book | chapter4/multimodal-agent/main.py | .py | """
Main entry point for Multimodal Agent
Demonstrates different extraction modes and model capabilities
"""
import asyncio
import sys
import argparse
from pathlib import Path
from typing import Optional
from agent import MultimodalAgent, MultimodalContent
from config import ExtractionMode, Config
class _Tee:
"... | 308 | 11,732 |
ai-agent-book | chapter4/multimodal-agent/campaign.py | .py | #!/usr/bin/env python3
"""Live three-paradigm comparison for Chapter 4 Experiment 4-2.
The PNG chart and the PDF page containing that chart are each submitted to the
same two questions through native vision, local text extraction followed by a
text-only model, and an agent that decides whether to invoke a vision tool.... | 402 | 16,168 |
ai-agent-book | chapter4/multimodal-agent/test_execute_tool_robust.py | .py | """Regression tests: _execute_tool must return an error string to the model
instead of raising KeyError/JSONDecodeError on malformed LLM tool-call
arguments (missing required fields or truncated streamed JSON)."""
import asyncio
import json
import os
import sys
import types
sys.path.insert(0, os.path.dirname(os.path.a... | 69 | 2,112 |
ai-agent-book | chapter4/multimodal-agent/create_sample.py | .py | """
离线样例生成器 (Offline sample generator)
生成一个"含图表的报告"作为多模态样例,用于实验 4-2 对比三种提取范式。
产物同时包含:
- test_files/sample_chart.png 仅图表(图像模态)
- test_files/sample_report.pdf 图表 + 文字说明(文档模态,书中的"含图表的 PDF 报告")
关键设计:图表里的精确数值(如各季度营收)只出现在柱状图上,正文并未逐一写出。
这样在实验中:
- 原生多模态模式可以直接"看懂"柱子读出数值;
- 提取为文本模式若用通用描述器转写图像,往往丢失精确数值与空间关系;
从而让三种范式的... | 135 | 4,846 |
ai-agent-book | chapter4/multimodal-agent/test_multimodal.py | .py | """
Test script for multimodal agent functionality
"""
import asyncio
import unittest
from unittest.mock import Mock, patch, AsyncMock
from pathlib import Path
from agent import MultimodalAgent, MultimodalContent, MultimodalTools, Message
from config import ExtractionMode, Provider
class TestMultimodalContent(unitt... | 230 | 7,636 |
ai-agent-book | chapter4/multimodal-agent/test_interactive_tools_toggle.py | .py | """Regression tests for the interactive multimodal tools toggle."""
import asyncio
import os
import sys
from unittest.mock import patch
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from agent import MultimodalAgent, MultimodalTools
from main import interactive_chat
def _run_commands(agent, *comma... | 38 | 1,057 |
ai-agent-book | chapter4/multimodal-agent/demo.py | .py | """
Demo script showcasing different extraction techniques
"""
import argparse
import asyncio
import sys
from pathlib import Path
from typing import List, Optional, Tuple
from agent import MultimodalAgent, MultimodalContent
from config import ExtractionMode
class _Tee:
"""Duplicate stdout writes to a file so --... | 341 | 11,743 |
ai-agent-book | chapter4/multimodal-agent/config.py | .py | """
Configuration for Multimodal Agent
Supports multiple providers and extraction modes
"""
import os
from typing import Optional, Dict, Any
from dataclasses import dataclass
from enum import Enum
from dotenv import load_dotenv
load_dotenv()
def _openrouter_model_id(model) -> str:
"""Map a provider-native model ... | 168 | 6,607 |
ai-agent-book | chapter4/multimodal-agent/agent.py | .py | """
Multimodal Agent with Multiple Extraction Techniques
Supports native multimodality, extract to text, and multimodal tools
"""
import os
import sys
import json
import base64
import httpx
import asyncio
from typing import Dict, Any, List, Optional, Union, Generator, AsyncGenerator
from dataclasses import dataclass, ... | 1,135 | 46,173 |
ai-agent-book | chapter5/paper-to-ppt/renderer.py | .py | """
Slidev 渲染器:把 Proposer 生成的 slides.md 真正渲染成“每页一张 PNG”。
这是本实验的关键——Reviewer 之所以能看到 Proposer 看不到的“新信息”,
正是因为我们真的把代码跑起来、渲染出了像素级的截图。
实现:调用本地安装的 Slidev CLI
npx slidev export slides.md --format png --output <dir> --timeout 60000
Slidev 的 PNG 导出底层用 playwright-chromium 打开每一页并截图。
"""
import glob
import os
import shutil
i... | 102 | 2,808 |
ai-agent-book | chapter5/paper-to-ppt/paper_source.py | .py | """Pinned real-paper preparation for Experiment 5-4.
The canonical campaign uses the published PDF, extracts its text directly, and
renders three original paper figures from declared PDF page rectangles. The
resulting manifest makes it possible to prove that the images in the Slidev
deck came from the source PDF rath... | 157 | 5,858 |
ai-agent-book | chapter5/paper-to-ppt/agents.py | .py | """
提议者(Proposer)与审核者(Reviewer)两个 Agent,以及一个带 token 计量的 LLM 客户端。
设计要点(对应书中“提议者-审核者”机制):
- Proposer 只处理**文本**:论文正文 + 累积的结构化文字反馈;从不接收渲染图片。
- Reviewer 每一轮**只看最新一版的渲染截图**,且每轮都是一次全新的、无历史的调用。
- 单 Agent 自审对照组则相反:同一段对话里不断累积历次渲染的图片,上下文迅速膨胀。
所有对 OpenAI 的调用都经过 TokenMeter 统计 prompt / completion token,
用于最后的“单 Agent vs 双 Ag... | 508 | 23,886 |
ai-agent-book | chapter5/paper-to-ppt/test_page_contract.py | .py | import importlib.util
from pathlib import Path
spec = importlib.util.spec_from_file_location("paper_to_ppt_agents_real", Path(__file__).with_name("agents.py"))
agents = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(agents)
_slide_count = agents._slide_count
_slide_contra... | 72 | 2,554 |
ai-agent-book | chapter5/paper-to-ppt/make_figures.py | .py | """
从论文中的数据生成两张真实的图表 PNG,放进 Slidev 的 public/ 目录,
供 Proposer 生成的幻灯片直接引用(满足“至少 3 处原图表”的要求,同时
让 Reviewer 的 Vision 检查能真正评估“图片尺寸是否合适”)。
这些图是用 matplotlib 从论文正文里的数字画出来的,属于“论文原始图表”的
程序化复现,而非凭空捏造。
"""
import os
import matplotlib
matplotlib.use("Agg") # 无显示环境
import matplotlib.pyplot as plt
PUBLIC_DIR = os.path.join(os.path.... | 68 | 2,775 |
ai-agent-book | chapter5/paper-to-ppt/test_null_issues.py | .py | """Null review issues must summarize without TypeError."""
import sys
from unittest.mock import MagicMock
# demo.py imports heavy optional deps at module import time.
sys.modules.setdefault("dotenv", MagicMock())
sys.modules.setdefault("agents", MagicMock())
sys.modules.setdefault("make_figures", MagicMock())
sys.modu... | 33 | 1,178 |
ai-agent-book | chapter5/paper-to-ppt/demo.py | .py | """
实验 5-4:基于论文的 PPT 自动生成(提议者-审核者机制)
完整流程:
1. 从精简论文(paper/sample_paper.md)+ 程序化复现的图表出发;
2. 【双 Agent】Proposer 生成 slides.md → Slidev 渲染每页 PNG → Reviewer 用 Vision LLM
看图给出结构化建议 → Proposer 据反馈修订 → 迭代,直到 pass 或达最大轮数;
3. 【单 Agent 自审】同一个 Agent 生成 → 渲染 → 把自己的截图塞回**同一上下文**自审并修订 → 迭代;
4. 用同一位“独立评委”(Vision)给两种方案的最终 ... | 641 | 31,110 |
ai-agent-book | chapter5/agent-creator/creator.py | .py | """Experiment 5-13: an Agent that creates and validates another Agent."""
from __future__ import annotations
import json
import hashlib
import os
import re
import shutil
import time
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from typing import Any
from openai import OpenAI
from valida... | 1,984 | 88,598 |
ai-agent-book | chapter5/agent-creator/test_creator.py | .py | from __future__ import annotations
import json
from pathlib import Path
from types import SimpleNamespace
import pytest
from creator import (
AgentCreator,
ResolvedBackend,
SCRATCH_FILE_GROUPS,
_usage_cost,
load_protocol,
)
from validator import _audit_case, _structural_check
def response(paylo... | 361 | 12,397 |
ai-agent-book | chapter5/agent-creator/demo.py | .py | from __future__ import annotations
import argparse
import json
from pathlib import Path
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
from creator import DEFAULT_PROTOCOL, load_protocol, run_experiment
DEFAULT_REQUIREMENTS = load_protocol()[0]["requirements"]
def main() -... | 53 | 1,572 |
ai-agent-book | chapter5/agent-creator/validator.py | .py | """Fixed structural and real-run validation for Experiment 5-13."""
from __future__ import annotations
import ast
import json
import os
import re
import subprocess
import sys
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
REQUIRED_FILES = {
"agent.py... | 449 | 16,748 |
ai-agent-book | chapter5/agent-creator/reference_agent/main.py | .py | from __future__ import annotations
import argparse
import json
from agent import GeneratedAgent
def main() -> None:
parser = argparse.ArgumentParser(description="Run the generated Agent")
parser.add_argument("--task", required=True)
parser.add_argument("--model")
parser.add_argument("--history-json"... | 25 | 739 |
ai-agent-book | chapter5/agent-creator/reference_agent/domain_tools.py | .py | """Deterministic policy-record adapter configured by ``domain_spec.json``."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parent
def _spec() -> dict[str, Any]:
with (ROOT / "domain_spec.json").open(encoding="utf-8") as handle:
... | 89 | 3,199 |
ai-agent-book | chapter5/agent-creator/reference_agent/agent.py | .py | """A small production-shaped OpenAI-compatible Agent loop.
The creator preserves this loop in template mode and only specializes the
system prompt, tool schemas, and domain tool implementation.
"""
from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Any
from openai i... | 140 | 5,314 |
ai-agent-book | chapter5/agent-creator/reference_agent/tests/test_contract.py | .py | from __future__ import annotations
import json
import copy
import sys
from pathlib import Path
from types import SimpleNamespace
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from agent import GeneratedAgent
class FakeCompletions:
def __init__(self):
self.calls = []
def create(self,... | 75 | 2,614 |
ai-agent-book | chapter5/agent-creator/reference_agent/tests/test_domain_policy.py | .py | from __future__ import annotations
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from domain_tools import execute_tool
ROOT = Path(__file__).resolve().parents[1]
def load_spec():
return json.loads((ROOT / "domain_spec.json").read_text(encoding="u... | 64 | 1,971 |
ai-agent-book | chapter5/permission-embedded-data-objects/run_targeted_eval.py | .py | """Targeted cross-provider eval: 20 hand-picked adversarial prompts.
Tests the key claim: PE catches violations that raw SQL misses,
across Claude and GPT model families.
"""
import json
import os
import re
import time
import uuid
import signal
import sys
import traceback
sys.path.insert(0, os.path.dirname(__file__)... | 514 | 23,515 |
ai-agent-book | chapter5/permission-embedded-data-objects/demo.py | .py | #!/usr/bin/env python3
"""实验 5-12:动态生成软件的数据层权限边界。"""
from __future__ import annotations
import os
from pedo.core.models import AccessContext, DataObject
from pedo.core.store import (
ObjectStore,
PermissionDeniedError,
ValidationError,
)
from pedo.scenarios.hiring import register_hiring_types
def main(... | 92 | 2,592 |
ai-agent-book | chapter5/permission-embedded-data-objects/run_live_security_eval.py | .py | """Live Security Evaluation for Permission-Embedded Data Objects (PEDO).
Evaluates agent-generated queries and mutations against PEDO access control models:
- Row-level security (RLS) enforcement
- Field visibility boundaries
- Privilege escalation attempts
- Performance overhead metrics
"""
from __future__ import an... | 1,005 | 43,372 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/benchmark_safety_v2.py | .py | """Evaluation 5.3 (Strengthened): Safety Under Agent-Generated Code.
Adds:
- HARNESS condition: CSDD-style spec-guided generation with no data-layer enforcement
- Strengthened oracle: tracks state machine transitions (not just final values)
- More adversarial prompts targeting specific violation types
"""
impor... | 447 | 22,391 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/benchmark_safety.py | .py | """Evaluation 6.4: Safety Under Agent-Generated Code.
Centerpiece evaluation. Uses Gemini 3 Flash to generate business logic
functions operating on the hiring pipeline schema. Tests three conditions:
(a) Permission-embedded objects (PEDO)
(b) Traditional API with authorization checks
(c) Raw database access
Mea... | 752 | 32,145 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/enterprise_agent_scenarios.py | .py | """Enterprise Agent Sandbox: scenario runner.
Runs a sequence of "agent goes off the rails" operations through PE and
records which were caught. The agent's intent is irrelevant -- what matters
is whether the operation it attempted is structurally allowed by the slow
layer's rules.
Six scenarios, mapping to the failu... | 225 | 9,903 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/benchmark_spec_errors_v2.py | .py | """Evaluation 5.4 (v2): Specification Error Evaluation — Execution-Based.
Instead of keyword matching, this evaluation:
1. Generates permission rules + validators (schema spec) via LLM
2. Generates API authorization functions (business logic) via LLM
3. Runs both against a suite of test cases that exercise each requir... | 451 | 17,875 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/benchmark_application.py | .py | """End-to-End Application Benchmark: AI Agent Running a Hiring Pipeline.
A realistic scenario where an LLM agent performs a sequence of business
operations on a hiring pipeline: creating positions, adding candidates,
advancing them through the pipeline, scheduling interviews, writing
evaluations, and handling edge cas... | 534 | 25,038 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/benchmark_safety_final.py | .py | """Final Safety Evaluation — Fixed execution harness.
Fixes from v2:
- Better function calling: inspect signatures and pass correct args
- Better test data setup: use both recruiter and admin contexts
- Retry API calls on disconnect
- More robust oracle: check DB state after every execution regardless of errors
- Sepa... | 537 | 27,009 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/benchmark_overhead.py | .py | """Evaluation 6.3: Pipeline Overhead Benchmarks.
Measures the performance cost of the permission/validation pipeline.
Compares:
(a) Raw PostgreSQL writes (baseline)
(b) PostgreSQL with RLS
(c) Permission-embedded objects (our system)
Varies: rule count, hierarchy depth, validator count, cross-object fan-out.
Re... | 402 | 14,246 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/benchmark_comparisons.py | .py | """Comprehensive Comparison Benchmarks.
Implements five new evaluations:
1. RLS comparison: PostgreSQL RLS matching PEDO authorization
2. Fragmented DB: RLS + CHECK + FK + triggers covering all constraints
3. Scaling: 1K/10K/100K objects
4. Multi-model: Test with different temperature/model variants
5. Improved HARNES... | 830 | 40,346 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/case_studies.py | .py | """Cross-case-study evaluator.
For each new case study (banking, ecommerce, healthcare, forum), runs a small
set of representative scenarios under two conditions:
- raw: a typical handler that does NOT enforce the case's invariants
(this is the canonical LLM-generated handler shape -- it follows
th... | 673 | 29,707 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/regeneration_robustness.py | .py | """Regeneration Robustness study.
Tests the productivity claim "regenerate handlers without re-audit" by
literally regenerating each handler N times at high temperature and
measuring how often the resulting code preserves declared invariants.
Methodology:
- Pick K representative prompts from DataGuardBench (mix of ... | 351 | 13,297 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/benchmark_harness_focused.py | .py | """Improved HARNESS: Focused vs Naive Context Injection.
CSDD found that injecting 3-5 focused principles achieves 96% compliance
vs 78% for full injection. This test compares:
- Naive: All 8 constitutional principles in the prompt
- Focused: Only the 1-2 most relevant principles per task
Both generate code again... | 258 | 11,983 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/benchmark_spec_errors.py | .py | """Evaluation 5.4: Specification Error Evaluation.
Empirically measures specification error rates vs business logic error rates.
Given the same business requirements, uses Gemini 3 Flash to generate:
(a) Schema specifications (permission rules + validators)
(b) Business logic authorization code (API functions with... | 445 | 19,171 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/benchmark_reactions.py | .py | """Evaluation 6.5: Reaction System vs PostgreSQL Triggers.
Compares Tier 3 reactions with PostgreSQL AFTER triggers implementing
equivalent logic. Measures:
- Cascade depth observed
- Failure propagation behavior
- Trace completeness for debugging
- Execution time for consequence chains
"""
import json
import... | 475 | 18,558 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/benchmark_final_comprehensive.py | .py | """Final Comprehensive Evaluation — Publication Grade.
Fixes all identified issues:
1. PEDO harness: better system prompt with concrete examples
2. RLS: uses non-superuser role so RLS actually applies
3. Expanded prompt set: 30 prompts (18 benign + 12 adversarial)
4. Two models: gemini-3-flash-preview and gemini-2.5-f... | 697 | 37,223 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/dataguardbench/agentspec_wrap.py | .py | """Faithful AgentSpec wrapper for head-to-head empirical comparison.
This module provides:
1. `register_*_types_no_policy` — register hiring / pm types with PE rules and
validators stripped (relationships/reactions kept for structural integrity).
The store accepts every operation; AgentSpec rules below are... | 255 | 10,545 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/dataguardbench/holdout_prompts.py | .py | """Held-out adversarial prompts authored AFTER the schema was frozen.
Purpose: Address the reviewer concern that the "0/360" headline could be a
measurement artifact of prompts and schema being co-authored. These 20 prompts
target the SAME invariants (hiring and project_mgmt) but use:
- Different attack framings (s... | 227 | 10,619 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/dataguardbench/agentspec_baseline.py | .py | """AgentSpec-style agent-action enforcement baseline.
Implements an agent-action-level enforcement mechanism for head-to-head
comparison with data-layer enforcement. This mimics the approach of
AgentSpec (ICSE 2026): a DSL that intercepts agent actions at the boundary
and evaluates them against declarative rules befor... | 305 | 10,874 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/dataguardbench/metrics.py | .py | """DataGuardBench metrics computation.
Implements the Correct-and-Secure (C&S) metric framework following
SecureAgentBench's methodology, extended with CWE-mapped violation tracking.
Outcome categories (per prompt execution):
- NO_OUTPUT: LLM failed to generate code
- COMPILE_ERROR: Generated code has syn... | 214 | 9,197 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/dataguardbench/cwe_taxonomy.py | .py | """CWE taxonomy mapping for DataGuardBench.
Maps each violation type to its corresponding CWE entry, enabling comparison
with standard AI code security benchmarks (CyberSecEval, CWEval, SecCodePLT).
"""
from dataclasses import dataclass, field
@dataclass
class CWEEntry:
"""A CWE entry with its DataGuardBench vi... | 135 | 5,559 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/dataguardbench/prompts.py | .py | """DataGuardBench prompt suite.
120 prompts across 2 scenarios (hiring pipeline, project management),
3 categories (benign, adversarial, edge-case), mapped to CWE IDs.
Each prompt is a BenchmarkPrompt with:
- id: unique identifier (scenario.category.seq)
- scenario: "hiring" or "project_mgmt"
- category: "benig... | 850 | 57,734 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/dataguardbench/harness.py | .py | """DataGuardBench evaluation harness.
Multi-model benchmark runner supporting:
- Gemini (via google.genai)
- Claude (via anthropic)
- GPT (via openai)
- Open-source models (via openai-compatible API)
Conditions evaluated:
- raw: No enforcement, direct SQL
- api: LLM generates its own authoriza... | 818 | 32,875 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/baxbench_adapter/reference_impls.py | .py | """Reference handler implementations for the BaxBench-derived adapter.
These exist to:
1. Self-test the oracle and adapter wiring without LLM calls.
2. Provide ground truth for what a "secure" RAW implementation looks like
vs. the typical insecure RAW pattern LLMs produce.
For each scenario, three handler se... | 536 | 18,144 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/baxbench_adapter/__init__.py | .py | """BaxBench-derived adapter benchmark.
Translates a subset of BaxBench (arXiv:2502.11844, ETH Zurich) backend
scenarios into the function-level harness format used by DataGuardBench,
so the same security oracle can be applied to PEDO and RAW conditions.
This is an adapter — not official BaxBench numbers. The contract... | 18 | 831 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/baxbench_adapter/scenarios.py | .py | """PEDO scenarios that mirror BaxBench scenarios.
These are translations of BaxBench scenario API specs into PEDO object
schemas. Each scenario keeps the same endpoint surface (handler signatures)
so a single security oracle can run against either RAW or PEDO conditions.
Scenarios covered:
- SecretStorage (BaxBen... | 195 | 8,847 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/baxbench_adapter/oracle.py | .py | """BaxBench security oracle, in-process.
Reproduces the security tests from BaxBench scenarios without spinning up a
Docker'd HTTP server. The handler functions receive the same logical inputs
that the HTTP endpoints would; the oracle drives the same sequence of
exploit attempts.
Each oracle returns an OracleResult c... | 292 | 11,629 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/baxbench_adapter/prompts.py | .py | """Prompts for the BaxBench-derived adapter.
Each scenario produces handler-level prompts (one per endpoint) per
condition. Prompts mirror BaxBench's text spec but are scoped to the
function-level harness (no Docker / web framework).
"""
from __future__ import annotations
from dataclasses import dataclass
# ── Secr... | 80 | 3,401 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/eval/baxbench_adapter/harness.py | .py | """BaxBench-derived adapter harness.
Two modes:
--self-test Run reference impls (raw_secure, raw_insecure, pedo) for
every adapted scenario through their oracles. No model calls.
--models ... Run model-generated handler code (stub).
Usage:
python -m pedo.eval.baxbench_adapter.harness --s... | 193 | 6,281 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/scenarios/banking.py | .py | """Case study: Banking / transactions.
Architectural pattern demonstrated: **cross-object balance invariant**.
A transaction's validity depends on the sender account's current balance --
the validator must read related state (the sender account) and compare to the
proposed change. This pattern doesn't fit single-table... | 120 | 5,587 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/scenarios/enterprise_agents.py | .py | """Case study: Enterprise Agent Sandbox.
Architectural pattern demonstrated: **per-agent permissions for runtime AI actors**.
Multiple autonomous agents operate against the same data layer, each with its
own AccessContext and its own scoped role. Permission rules in the schema
declare what each agent role may do; the ... | 223 | 12,544 |
ai-agent-book | chapter5/permission-embedded-data-objects/pedo/scenarios/forum.py | .py | """Case study: Forum / community.
Architectural pattern demonstrated: **public-read + owner-edit + moderator override**.
Posts are publicly readable but only the author can edit them; moderators can
delete or lock any post regardless of authorship. Comments are owned by their
author. This pattern shows multiple-rule p... | 135 | 5,791 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.