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
chapter7/elo-leaderboard/tests/test_optimize_empty.py
.py
"""Regression: optimize_dataframe must tolerate empty object columns.""" import pandas as pd from parallel_processing import optimize_dataframe def test_optimize_empty_object_columns(): df = pd.DataFrame({ "model_a": pd.Series([], dtype=object), "model_b": pd.Series([], dtype=object), "win...
14
420
ai-agent-book
chapter7/elo-leaderboard/tests/test_load_battles_empty.py
.py
"""Empty battles JSON array [] must load as an empty battle frame.""" import json from pathlib import Path import cli def test_load_battles_empty_json_array(tmp_path): path = tmp_path / "battles.json" path.write_text("[]", encoding="utf-8") df = cli._load_battles(str(path)) assert list(df.columns) ==...
35
1,004
ai-agent-book
chapter7/elo-leaderboard/tests/test_elo.py
.py
""" Unit tests for Elo rating system """ import math import pytest from _bootstrap import bootstrap_experiment_root bootstrap_experiment_root() from elo_rating import EloRatingSystem def test_initial_rating(): """Test that models start with initial rating.""" elo = EloRatingSystem(initial_rating=1000.0) ...
171
5,154
ai-agent-book
chapter7/elo-leaderboard/tests/test_filter_data_parallel_small.py
.py
"""Regression: filter_data_parallel must tolerate n_jobs > len(df).""" from unittest.mock import MagicMock, patch import pandas as pd from parallel_processing import filter_data_parallel def test_n_jobs_larger_than_rows(): df = pd.DataFrame({"anony": [True, False, True], "turn": [1, 2, 1]}) def map_inline(...
22
656
ai-agent-book
chapter7/elo-leaderboard/tests/test_analyze_empty_history.py
.py
"""Empty rating history must not crash analyze_rating_changes / get_rating_history.""" import pandas as pd from animation import prepare_animation_data from leaderboard import ( analyze_rating_changes, build_historical_leaderboards, get_rating_history, ) def test_get_rating_history_empty_keeps_columns():...
40
1,396
ai-agent-book
chapter7/elo-leaderboard/tests/test_tie_bothbad.py
.py
""" Regression test for 'tie (bothbad)' handling in optimized_elo (实验 6-6 排行榜). Chatbot Arena battle data has four outcomes; 'tie (bothbad)' was missing from the outcome map, so Series.map produced NaN. NaN then propagated through the rating updates and spread to every model that later faced an affected one, leaving t...
50
1,709
ai-agent-book
chapter7/elo-leaderboard/tests/test_animation_empty_history.py
.py
"""Regression: prepare_animation_data must tolerate empty history.""" import pandas as pd from animation import prepare_animation_data def test_empty_history_returns_empty_frames(): df = pd.DataFrame(columns=["date", "model", "rating", "rank", "matches", "wins"]) data = prepare_animation_data(df) assert d...
12
415
ai-agent-book
chapter7/elo-leaderboard/tests/test_benchmark_zero_div.py
.py
""" Test suite locking out ZeroDivisionError in benchmark summary print logic when time_basic is 0.0 or df_sample is empty. """ def test_benchmark_pct_reduction_zero_division(): """ Ensure zero time_basic does not raise ZeroDivisionError during benchmark calculation. """ time_basic = 0.0 time_optim...
24
767
ai-agent-book
chapter7/elo-leaderboard/tests/test_zero_battles_bt.py
.py
"""Empty battle DataFrame must not crash Bradley-Terry LogisticRegression.""" import pandas as pd from bradley_terry import compute_bradley_terry_leaderboard, compute_mle_elo def test_compute_mle_elo_empty_battles(): df = pd.DataFrame(columns=["model_a", "model_b", "winner"]) ratings = compute_mle_elo(df) ...
33
1,101
ai-agent-book
chapter7/elo-leaderboard/tests/test_filter_empty.py
.py
""" Regression test for filter_data on empty input (实验 6-6 排行榜). An empty arena data file (e.g. a failed/truncated download saved as `[]`) used to crash with ZeroDivisionError at the "After filtering" percentage print. """ import pandas as pd import pytest from _bootstrap import bootstrap_experiment_root bootstrap_e...
38
1,139
ai-agent-book
chapter7/elo-leaderboard/tests/test_ch6_animation_string_date.py
.py
"""Regression test for prepare_animation_data with string or date objects in history_df.""" import pandas as pd from animation import prepare_animation_data def test_prepare_animation_data_string_date(): """prepare_animation_data must handle string dates without raising AttributeError.""" history = pd.DataFra...
33
1,039
ai-agent-book
chapter7/elo-leaderboard/tests/test_animation_tie_wins.py
.py
"""prepare_animation_data must keep fractional wins from Elo ties.""" import pandas as pd from animation import prepare_animation_data def test_tie_half_wins_are_not_truncated(): history = pd.DataFrame( { "date": pd.to_datetime(["2024-01-07", "2024-01-07"]), "model": ["A", "B"], ...
36
1,040
ai-agent-book
chapter7/elo-leaderboard/tests/test_validation_runner.py
.py
import json from pathlib import Path def test_canonical_manifest_is_hash_complete(): run_dir = Path(__file__).resolve().parents[1] / "validation" / "runs" / "exp6-6-arena-20260731-v1" manifest_path = run_dir / "manifest.json" assert manifest_path.exists() manifest = json.loads(manifest_path.read_text(...
21
705
ai-agent-book
chapter7/elo-leaderboard/tests/test_ch6_compare_win_rates_empty.py
.py
"""Regression test for compare_win_rates when comparisons list is empty.""" import numpy as np import pandas as pd from elo_rating import EloRatingSystem from leaderboard import compare_win_rates def test_compare_win_rates_empty_has_required_columns(): """compare_win_rates must return a DataFrame with required co...
18
794
ai-agent-book
chapter7/elo-leaderboard/tests/test_bootstrap_reproducibility.py
.py
import pandas as pd from bradley_terry import compute_mle_elo, get_bootstrap_result def test_bootstrap_is_reproducible(): battles = pd.DataFrame( [ {"model_a": "a", "model_b": "b", "winner": "model_a"}, {"model_a": "a", "model_b": "b", "winner": "model_b"}, {"model_a": ...
17
636
ai-agent-book
chapter7/elo-leaderboard/tests/_bootstrap.py
.py
"""Helpers for direct execution of tests moved under tests/.""" from pathlib import Path import sys def bootstrap_experiment_root() -> None: experiment_root = Path(__file__).resolve().parents[1] if str(experiment_root) not in sys.path: sys.path.insert(0, str(experiment_root))
11
296
ai-agent-book
chapter7/elo-leaderboard/tests/test_bt_tie_pivot.py
.py
"""Ties must contribute to Bradley-Terry weights (not be zeroed by pivot+T).""" import pandas as pd from bradley_terry import compute_mle_elo def test_all_ties_rates_models_instead_of_sample_weight_error(): df = pd.DataFrame( [ {"model_a": "A", "model_b": "B", "winner": "tie"}, {"...
42
1,413
ai-agent-book
chapter7/elo-leaderboard/tests/test_bt_small_sample.py
.py
"""Regression: compute_mle_elo must work on small Arena-shaped battle sets.""" import pandas as pd from battle_simulator import simulate_battles from bradley_terry import compute_mle_elo def test_small_two_model_sample(): df = pd.DataFrame(simulate_battles({"gpt-4": 1200.0, "llama-3": 1000.0}, 10, seed=1)) ra...
12
431
ai-agent-book
chapter7/elo-leaderboard/tests/test_time_slices_monthly_interval.py
.py
"""Regression: documented interval='M' must work on modern pandas.""" import pandas as pd from data_loader import get_time_slices def test_monthly_interval_alias(): df = pd.DataFrame({"tstamp": [1_700_000_000, 1_710_000_000]}) slices = get_time_slices(df, interval="M") assert len(slices) >= 1
10
308
ai-agent-book
chapter7/elo-leaderboard/tests/test_time_slices_short_span.py
.py
""" Regression: get_time_slices must not IndexError when the tstamp span is shorter than the requested interval (default weekly). Chatbot Arena samples, same-second dumps, and single-row demos all produce an empty pd.date_range for freq='W'; the old code then crashed on date_ranges[-1]. """ import pandas as pd from _...
56
1,713
ai-agent-book
chapter7/elo-leaderboard/tests/conftest.py
.py
"""Test import bootstrap for the elo-leaderboard 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
243
ai-agent-book
chapter7/elo-leaderboard/validation/validate_evidence.py
.py
"""Fail-closed verifier for a saved Experiment 6-6 run.""" from __future__ import annotations import argparse import hashlib import json from pathlib import Path def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while chunk := handle.read(8 * 1024 * 1024):...
67
2,378
ai-agent-book
chapter7/elo-leaderboard/validation/run_experiment.py
.py
"""Run the complete, evidence-producing Experiment 6-6 campaign. The public Arena file is deliberately not copied into git. A canonical run binds the exact input by URL, size, record count, and SHA-256, then retains all derived tables, visualizations, the D3 history animation, and a manifest that hashes every output ...
390
15,148
ai-agent-book
chapter7/public-health-reporting-eval/evaluator.py
.py
"""Objective structured scoring for public-health reporting agent traces.""" from __future__ import annotations import json import math from pathlib import Path from typing import Any MAX_SCORE = 6 def load_json(path: str | Path) -> Any: return json.loads(Path(path).read_text(encoding="utf-8")) def expected...
107
4,037
ai-agent-book
chapter7/public-health-reporting-eval/reporting_tools.py
.py
"""Deterministic tools over synthetic DHIS2-style aggregate reports.""" from __future__ import annotations import csv from pathlib import Path from typing import Any INTEGER_FIELDS = { "tests", "confirmed_cases", "deaths", "report_expected", "report_submitted", "stockout_days", } class Rep...
149
6,069
ai-agent-book
chapter7/public-health-reporting-eval/demo.py
.py
"""Run the deterministic reference agent or evaluate external structured predictions.""" from __future__ import annotations import argparse import json import os from pathlib import Path try: from dotenv import load_dotenv load_dotenv() except ImportError: pass from agent import DeterministicReportingAg...
65
2,001
ai-agent-book
chapter7/public-health-reporting-eval/agent.py
.py
"""A deterministic reference agent for the reporting evaluation environment.""" from __future__ import annotations from typing import Any from reporting_tools import ReportingEnvironment class DeterministicReportingAgent: """Executes the task's explicit tool plan and returns a structured trace.""" def __i...
27
892
ai-agent-book
chapter7/public-health-reporting-eval/tests/test_offline.py
.py
"""Offline regression tests; no model, API key or network access required.""" from __future__ import annotations from copy import deepcopy from pathlib import Path from agent import DeterministicReportingAgent from evaluator import MAX_SCORE, evaluate, expected_by_task, load_json, score_prediction from reporting_too...
69
2,655
ai-agent-book
chapter7/public-health-reporting-eval/tests/test_null_result.py
.py
"""score_prediction must tolerate result:null like missing/empty result.""" from __future__ import annotations from copy import deepcopy from pathlib import Path from agent import DeterministicReportingAgent from evaluator import MAX_SCORE, expected_by_task, load_json, score_prediction from reporting_tools import Re...
72
2,466
ai-agent-book
chapter7/public-health-reporting-eval/tests/test_blank_csv_int.py
.py
"""Blank integer CSV cells must load as 0, not ValueError from int('').""" import csv from pathlib import Path from reporting_tools import ReportingEnvironment def _write_csv(path: Path, tests_value: str) -> None: with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter( ...
77
2,316
ai-agent-book
chapter7/public-health-reporting-eval/tests/test_excel_float_int.py
.py
"""Excel-style whole floats in integer CSV cells must load (10.0 -> 10).""" import csv from pathlib import Path from reporting_tools import ReportingEnvironment def _write_csv(path: Path, tests_value: str) -> None: with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter( ...
72
2,022
ai-agent-book
chapter7/public-health-reporting-eval/tests/conftest.py
.py
"""Test import bootstrap for the public-health-reporting-eval 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
256
ai-agent-book
chapter7/model-action-threshold/experiment.py
.py
#!/usr/bin/env python3 """Controlled model action-threshold experiment for Chapter 6. The experiment holds the coding harness, prompt, tools, task repositories, and sampling order fixed while swapping only the model identifier. It measures how much evidence a model gathers before its first edit and whether acting ear...
719
28,581
ai-agent-book
chapter7/model-action-threshold/tasks/crosscutting_identity/repo/accounts/models.py
.py
from dataclasses import dataclass @dataclass(frozen=True) class Profile: username: str email: str password: str
9
126
ai-agent-book
chapter7/model-action-threshold/tasks/crosscutting_identity/repo/accounts/authentication.py
.py
def authenticate(store, username, password): profile = store.find(username.strip()) if profile is None or profile.password != password: return None return profile
6
183
ai-agent-book
chapter7/model-action-threshold/tasks/crosscutting_identity/repo/accounts/directory.py
.py
def lookup_profile(store, username): return store.find(username)
3
69
ai-agent-book
chapter7/model-action-threshold/tasks/crosscutting_identity/repo/accounts/store.py
.py
class AccountStore: def __init__(self): self._profiles = {} def save(self, key, profile): if key in self._profiles: raise ValueError("username already exists") self._profiles[key] = profile def find(self, key): return self._profiles.get(key)
12
300
ai-agent-book
chapter7/model-action-threshold/tasks/crosscutting_identity/repo/accounts/registration.py
.py
from accounts.models import Profile def register(store, username, email, password): display_name = username.strip() key = display_name.lower() profile = Profile(display_name, email, password) store.save(key, profile) return profile
10
254
ai-agent-book
chapter7/model-action-threshold/tasks/crosscutting_identity/repo/tests/test_accounts.py
.py
import unittest from accounts.authentication import authenticate from accounts.directory import lookup_profile from accounts.registration import register from accounts.store import AccountStore class AccountIdentityTests(unittest.TestCase): def setUp(self): self.store = AccountStore() def test_regis...
36
1,357
ai-agent-book
chapter7/model-action-threshold/tasks/cache_contract/repo/cachelib/catalog.py
.py
class Catalog: def __init__(self, cache, fetch_product): self.cache = cache self.fetch_product = fetch_product def product(self, product_id): return self.cache.get_or_load(product_id, self.fetch_product)
8
237
ai-agent-book
chapter7/model-action-threshold/tasks/cache_contract/repo/cachelib/__init__.py
.py
from cachelib.cache import Cache __all__ = ["Cache"]
4
54
ai-agent-book
chapter7/model-action-threshold/tasks/cache_contract/repo/cachelib/cache.py
.py
class Cache: def __init__(self): self._values = {} def get(self, key, default=None): return self._values.get(key, default) def put(self, key, value): self._values[key] = value def get_or_load(self, key, loader): cached = self.get(key) if cached is not None: ...
18
421
ai-agent-book
chapter7/model-action-threshold/tasks/cache_contract/repo/tests/test_cache.py
.py
import unittest from cachelib import Cache class CacheContractTests(unittest.TestCase): def test_negative_lookup_is_loaded_once(self): cache = Cache() calls = [] def loader(key): calls.append(key) return None self.assertIsNone(cache.get_or_load("missing",...
41
1,104
ai-agent-book
chapter7/model-action-threshold/tasks/localized_timeout/repo/tests/test_config.py
.py
import unittest from app.config import DEFAULT_TIMEOUT, resolve_timeout class ResolveTimeoutTests(unittest.TestCase): def test_explicit_value_wins_over_environment(self): self.assertEqual(resolve_timeout(12, {"AGENT_TIMEOUT": "45"}), 12) def test_environment_is_used_without_explicit_value(self): ...
21
695
ai-agent-book
chapter7/model-action-threshold/tasks/localized_timeout/repo/app/worker.py
.py
"""Worker construction kept separate from configuration parsing.""" from app.config import resolve_timeout def worker_options(timeout=None, env=None): return {"timeout": resolve_timeout(timeout, env), "retries": 2}
8
222
ai-agent-book
chapter7/model-action-threshold/tasks/localized_timeout/repo/app/config.py
.py
"""Runtime timeout configuration.""" DEFAULT_TIMEOUT = 30 def resolve_timeout(explicit=None, env=None): """Return a positive timeout using explicit > environment > default.""" env = env or {} raw = env.get("AGENT_TIMEOUT", explicit) try: value = int(raw) except (TypeError, ValueError): ...
15
400
ai-agent-book
chapter7/model-action-threshold/tests/test_experiment.py
.py
import importlib.util import sys import tempfile import unittest from pathlib import Path MODULE_PATH = Path(__file__).resolve().parents[1] / "experiment.py" SPEC = importlib.util.spec_from_file_location("action_threshold_experiment", MODULE_PATH) experiment = importlib.util.module_from_spec(SPEC) sys.modules[SPEC.na...
118
5,027
ai-agent-book
chapter7/tts-quality-eval/pipeline.py
.py
"""TTS 质量评估流水线的核心步骤。 一条评估链路: 合成(OpenAI TTS) -> 时长探测(ffprobe) -> 回译(Whisper) -> 计算 CER/字准确率 -> LLM Rubric 打分(gpt-5.6-luna) [可选: Gemini 音频评审 gemini-3.5-flash] 说明:TTS 合成与 Whisper 回译必须走 OpenAI 直连;文本 Rubric 与直接听音频的 多模态 Rubric 支持 Google Gemini、OpenRouter 与 Mistral Voxtral。每条路径都把 两段真实音频交给音频模型,不会退化成转写文本评审。 所有对外函数都做了...
826
33,722
ai-agent-book
chapter7/tts-quality-eval/test_minimax_t2a_refresh.py
.py
""" Regression tests for the Minimax t2a_v2 synthesis adapter (实验 6-5 TTS 质量评估). Locks in the refreshed contract: - the request targets the /v1/t2a_v2 endpoint with Bearer auth and no GroupId query parameter, on the global host by default and the mainland-China host when MINIMAX_REGION selects it; - the de...
110
3,963
ai-agent-book
chapter7/tts-quality-eval/demo.py
.py
"""实验 6-5:全自动 TTS 质量评估流水线 —— 一条命令跑通。 python demo.py # 默认 4 个 OpenAI 配置 x 4 条语料 python demo.py --providers openai,minimax # 跨服务商横向对比 python demo.py --text '一段话' # 自定义文本 python demo.py --gemini # 评审改用多模态模型直接听两段音频 python demo.py --quick # 只用前 2 条语料...
419
17,662
ai-agent-book
chapter7/tts-quality-eval/config.py
.py
"""实验 6-5:全自动 TTS 质量评估流水线 —— 配置与测试语料。 本模块集中管理: - 用到的 OpenAI 模型名与计费单价(仅供参考成本估算); - 多个 TTS「配置」(model / voice / speed 的组合,作为待对比的对象); - 一组带挑战性的参考文本(数字 / 多音字 / 长句 / 专有名词 + 情感)。 """ import os from dataclasses import dataclass, field from dotenv import load_dotenv load_dotenv() # ------------------------------------...
204
8,717
ai-agent-book
chapter7/tts-quality-eval/tests/test_resolve_gemini_model_null.py
.py
""" Test suite locking out TypeError in _resolve_gemini_model when API returns data with models: None or non-dict items. """ import json from unittest.mock import MagicMock from pipeline import _resolve_gemini_model, config def test_resolve_gemini_model_handles_null_models(): """ Ensure _resolve_gemini_mode...
26
798
ai-agent-book
chapter7/tts-quality-eval/tests/test_judge_robustness.py
.py
""" Regression tests for judge-response robustness (实验 6-5 TTS 质量评估). Covers two failure classes on LLM/Gemini judge responses: - judge_rubric: judge returns "score": null (or a bare null dimension) -> int(None) TypeError - judge_gemini_audio: safety-blocked Gemini responses have no candidates/content/parts ->...
255
10,164
ai-agent-book
chapter7/tts-quality-eval/tests/conftest.py
.py
"""Test import bootstrap for the tts-quality-eval 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
244
ai-agent-book
chapter3/memory_rag_campaign.py
.py
#!/usr/bin/env python3 """Shared canonical campaign for Experiments 3-9 and 3-11. Experiment 3-9 is the plain fixed-window, agent-searched arm. Experiment 3-11 replays the exact same live agent-generated queries against plain and live-contextualized indexes, then adds the live Advanced JSON Cards produced by Experime...
615
29,616
ai-agent-book
chapter3/experiment_utils.py
.py
"""Shared evidence helpers for the Chapter 3 experiment campaigns. The helpers deliberately never read or serialize credential values. Provider keys are supplied directly to SDK clients by each campaign; receipts contain only the provider name, endpoint, model, request payload, raw response, usage, and latency needed...
212
7,084
ai-agent-book
chapter3/user-memory-evaluation/evaluator.py
.py
"""LLM-based evaluator for agent responses.""" import json from typing import Dict, Any, Optional from tenacity import retry, stop_after_attempt, wait_exponential import openai from config import Config from models import ( TestCase, EvaluationResult, RubricDimensionResult, RubricGrade, Hallucinati...
448
19,291
ai-agent-book
chapter3/user-memory-evaluation/main.py
.py
"""Main script to run user memory evaluation tests.""" import argparse import json from typing import Dict, Optional from pathlib import Path from rich.console import Console from rich.prompt import Prompt, Confirm from framework import UserMemoryEvaluationFramework, TestCaseExporter from evaluator import LLMEvaluato...
472
19,376
ai-agent-book
chapter3/user-memory-evaluation/models.py
.py
"""Data models for the User Memory Evaluation Framework.""" from typing import List, Dict, Any, Optional from pydantic import BaseModel, Field from enum import Enum class MessageRole(str, Enum): """Message roles in conversation.""" USER = "user" ASSISTANT = "assistant" SYSTEM = "system" class Rubri...
151
6,184
ai-agent-book
chapter3/user-memory-evaluation/validate_rubric.py
.py
#!/usr/bin/env python3 """Run and persist a live Experiment 6-3 structured-rubric validation.""" import argparse import json import time from pathlib import Path from evaluator import LLMEvaluator from framework import UserMemoryEvaluationFramework def main() -> int: parser = argparse.ArgumentParser() parse...
56
2,135
ai-agent-book
chapter3/user-memory-evaluation/comparison.py
.py
"""Cross-system comparison for the User Memory Evaluation Framework. Experiment 3-1 evaluates *memory systems*: the same three-layer test suite is run against several memory configurations (e.g. Simple Notes vs. Advanced JSON Cards) and their scores are compared side by side. This module takes a mapping of {syste...
205
8,449
ai-agent-book
chapter3/user-memory-evaluation/__init__.py
.py
"""User Memory Evaluation Framework. The companion is intentionally executed from this directory (``python main.py``) because the historical directory name contains a hyphen. Keep this initializer free of eager relative imports so pytest and importlib can collect the directory without pretending it is a normally name...
10
356
ai-agent-book
chapter3/user-memory-evaluation/metrics.py
.py
"""Offline, deterministic metrics for the User Memory Evaluation Framework. The LLM-as-judge evaluator in ``evaluator.py`` requires an API key and network access. This module provides a complementary metric that runs fully offline on canned data, so the benchmark can produce a scored comparison across memory systems w...
125
4,643
ai-agent-book
chapter3/user-memory-evaluation/test_structured_rubric.py
.py
"""Deterministic acceptance tests for book Experiment 6-3.""" import json from evaluator import LLMEvaluator def evaluator_without_network(): evaluator = object.__new__(LLMEvaluator) return evaluator def response(*, hallucination=False): return json.dumps( { "dimensions": { ...
103
4,186
ai-agent-book
chapter3/user-memory-evaluation/generate_test_cases.py
.py
#!/usr/bin/env python3 """ Generate remaining test cases for the user memory evaluation framework. This script creates properly structured YAML test cases for layers 1, 2, and 3. """ import yaml import os from typing import Dict, List, Any # Layer 2 test case templates (disambiguation scenarios) LAYER2_TEMPLATES = [ ...
330
11,395
ai-agent-book
chapter3/user-memory-evaluation/config.py
.py
"""Configuration module for User Memory Evaluation Framework.""" import os from typing import Optional from dotenv import load_dotenv # Load environment variables load_dotenv() def _openrouter_model_id(model) -> str: """Map a provider-native model name to an OpenRouter model id, used by the universal OpenRo...
107
4,356
ai-agent-book
chapter3/user-memory-evaluation/framework.py
.py
"""Main framework for User Memory Evaluation.""" import os import yaml from typing import List, Dict, Optional, Any from pathlib import Path from rich.console import Console from rich.table import Table from rich.panel import Panel from rich import print as rprint from config import Config from models import ( Te...
429
16,534
ai-agent-book
chapter3/dense-embedding/quick_demo.py
.py
#!/usr/bin/env python3 """Quick demo script to showcase the vector similarity search service.""" import time import sys def print_section(title): """Print a formatted section header.""" print("\n" + "=" * 60) print(f" {title}") print("=" * 60) def main(): """Run a quick demo of the service."""...
134
3,764
ai-agent-book
chapter3/dense-embedding/logger.py
.py
"""Educational logging configuration with extensive debug information.""" import logging import sys import time from typing import Optional import colorlog from functools import wraps def setup_logger(name: str = "vector_search", level: str = "DEBUG") -> logging.Logger: """ Set up a colorful and informative ...
158
6,179
ai-agent-book
chapter3/dense-embedding/test_client.py
.py
"""Test client for the vector similarity search service.""" import requests import json import time from typing import List, Dict, Any class VectorSearchClient: """Client for testing the vector search service.""" def __init__(self, base_url: str = "http://localhost:8000"): """Initialize the clie...
253
9,852
ai-agent-book
chapter3/dense-embedding/main.py
.py
"""Main FastAPI application for vector similarity search service.""" import time import argparse from typing import List, Optional, Dict, Any from contextlib import asynccontextmanager import uvicorn from fastapi import FastAPI, HTTPException, Query from fastapi.middleware.cors import CORSMiddleware from pydantic impo...
437
13,327
ai-agent-book
chapter3/dense-embedding/indexing.py
.py
"""Vector index implementations using ANNOY and HNSW.""" from abc import ABC, abstractmethod from typing import List, Tuple, Dict, Optional import numpy as np import annoy import hnswlib import time from logger import VectorSearchLogger class VectorIndex(ABC): """Abstract base class for vector indexes.""" ...
391
14,977
ai-agent-book
chapter3/dense-embedding/embedding_service.py
.py
"""Embedding service using BGE-M3 model.""" import time import numpy as np from typing import List, Dict, Optional from FlagEmbedding import BGEM3FlagModel from logger import VectorSearchLogger, log_execution_time import logging class EmbeddingService: """Service for generating embeddings using BGE-M3 model.""" ...
219
8,191
ai-agent-book
chapter3/dense-embedding/benchmark.py
.py
#!/usr/bin/env python3 """Real-embedding ANNOY vs HNSW benchmark for Experiment 3-4.""" from __future__ import annotations import argparse import json import os import statistics import subprocess import sys import tempfile import time from pathlib import Path from typing import Any, Dict, List, Sequence import nump...
304
13,899
ai-agent-book
chapter3/dense-embedding/test_empty_batch_encode.py
.py
""" Test suite locking out ZeroDivisionError in EmbeddingService.encode_batch when an empty texts list is provided. """ import os import sys from unittest.mock import MagicMock # Mock third-party dependencies before importing embedding_service sys.modules['FlagEmbedding'] = MagicMock() sys.modules['colorlog'] = Magic...
35
981
ai-agent-book
chapter3/dense-embedding/docker_annoy_runner.py
.py
#!/usr/bin/env python3 """Linux-isolated ANNOY measurement used when the host ARM wheel is broken.""" import json import os import statistics import sys import tempfile import time import numpy as np from annoy import AnnoyIndex def latency_stats(values): return { "mean": statistics.mean(values), ...
88
2,980
ai-agent-book
chapter3/dense-embedding/cli.py
.py
#!/usr/bin/env python3 """ 稠密检索命令行工具(实验 3-4) 在一个小型示例语料上运行稠密嵌入检索,支持: - 自定义语料 / 查询 / top-k / 输出文件 - --eval:在带标注的小型评测集上计算 recall@k / precision@k / MRR, 直观展示"稠密嵌入读得懂同义表达"这一核心卖点 - --compare-ann:复现书中实验 3-4 的重点——对比 ANNOY 与 HNSW 两种 ANN 后端 相对精确暴力检索的召回率、建索引耗时与查询延迟(复用服务端 indexing.py) - --embedding...
453
22,866
ai-agent-book
chapter3/dense-embedding/config.py
.py
"""Configuration for the dense embedding service.""" import os from enum import Enum from dataclasses import dataclass, field from typing import Optional class IndexType(Enum): """Supported index types.""" ANNOY = "annoy" HNSW = "hnsw" @dataclass class ServiceConfig: """Service configuration.""" ...
59
1,646
ai-agent-book
chapter3/dense-embedding/document_store.py
.py
"""In-memory document store for managing documents.""" from typing import Dict, Optional, List from dataclasses import dataclass, field from datetime import datetime import uuid from logger import VectorSearchLogger @dataclass class Document: """Document data class.""" id: str text: str metadata: Dic...
194
5,746
ai-agent-book
chapter3/retrieval-pipeline/test_client.py
.py
"""Test client with educational test cases for dense vs sparse retrieval.""" import asyncio import httpx import json from typing import List, Dict, Any import logging from datetime import datetime logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class TestClient: """Test client for th...
498
18,816
ai-agent-book
chapter3/retrieval-pipeline/main.py
.py
"""FastAPI server for the retrieval pipeline.""" import logging import sys from typing import Dict, Any, Optional, List from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Field import uvicorn import as...
290
9,895
ai-agent-book
chapter3/retrieval-pipeline/retrieval_pipeline.py
.py
"""Main retrieval pipeline combining dense, sparse, and reranking.""" import asyncio import logging from typing import Dict, Any, List, Optional, Tuple from datetime import datetime import uuid from config import PipelineConfig, SearchMode from document_store import DocumentStore from retrieval_client import Retrieva...
422
16,288
ai-agent-book
chapter3/retrieval-pipeline/campaign.py
.py
#!/usr/bin/env python3 """Canonical real-model campaign for Chapter 3 Experiment 3-6.""" from __future__ import annotations import json import sys from pathlib import Path PROJECT_DIR = Path(__file__).resolve().parent CHAPTER_DIR = PROJECT_DIR.parent sys.path.insert(0, str(CHAPTER_DIR)) from experiment_utils import...
137
5,019
ai-agent-book
chapter3/retrieval-pipeline/stage_evaluator.py
.py
"""Stage-level evaluation for the hybrid retrieval pipeline. The book's 第3章「混合检索流水线」(experiment 3-6) chains four retrieval stages — dense retrieval, sparse retrieval, fusion of the two, and neural reranking — and judges the whole pipeline with aggregate metrics. What it does not provide is an *automated, stage-level* ...
418
17,194
ai-agent-book
chapter3/retrieval-pipeline/reranker.py
.py
"""Reranker module using BGE-Reranker-v2 model.""" import torch from typing import List, Tuple, Dict, Any, Optional from dataclasses import dataclass from FlagEmbedding import FlagReranker import logging import time import numpy as np import os import sys from pathlib import Path from huggingface_hub import snapshot_d...
268
9,960
ai-agent-book
chapter3/retrieval-pipeline/test_weighted_fusion_dedup.py
.py
import pytest from fusion import weighted_score_fusion def test_weighted_score_fusion_preserves_top_score_on_duplicate_doc_id(): """Verify weighted score fusion preserves top score when duplicate doc_ids exist in ranked list.""" ranked_lists = { "dense": [("doc1", 0.95), ("doc2", 0.80), ("doc1", 0.10)]...
16
541
ai-agent-book
chapter3/retrieval-pipeline/retrieval_client.py
.py
"""Client for communicating with dense and sparse embedding services.""" import httpx import asyncio from typing import Dict, Any, List, Optional, Tuple import logging from dataclasses import dataclass logger = logging.getLogger(__name__) @dataclass class SearchResult: """Unified search result from embedding ser...
202
9,004
ai-agent-book
chapter3/retrieval-pipeline/test_pipeline.py
.py
#!/usr/bin/env python3 """Test script for the retrieval pipeline with external doc_id support.""" import httpx import asyncio import json import logging from datetime import datetime # Set up logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger...
201
9,057
ai-agent-book
chapter3/retrieval-pipeline/evaluate.py
.py
"""混合检索流水线离线评测 CLI。 本脚本把整条检索流水线——分块(chunk) → 嵌入(embed) → 检索(retrieve) → 融合(fuse) → 重排(rerank)——完整地跑在**单进程、可离线**的环境里,并在一个带 标注答案的小型评测集上,逐阶段对比各方法的检索质量。它不依赖 dense/sparse 微服务 (4240/4241/4242 端口),因此可以脱离服务、直接用本地模型复现「每加一个阶段、指标如何 提升」这一核心结论。 各阶段使用的本地组件: - 稀疏检索(sparse) : BM25(纯 Python,rank_bm25,无需下载模型) - 稠密检索(dense) : 本地...
772
37,506
ai-agent-book
chapter3/retrieval-pipeline/demo.py
.py
"""Demo script showcasing dense vs sparse embedding strengths. Service Configuration: - Dense Embedding: http://localhost:4240 - Sparse Embedding: http://localhost:4241 - Retrieval Pipeline: http://localhost:4242 """ import asyncio import httpx from typing import Dict, List import json class RetrievalDemo: """...
282
11,260
ai-agent-book
chapter3/retrieval-pipeline/fusion.py
.py
"""Result fusion for hybrid retrieval. This module implements the *fusion* stage of the hybrid retrieval pipeline — the step that merges the separately-ranked dense and sparse candidate lists into a single, unified candidate pool before neural reranking. Two production-grade fusion strategies are provided, matching t...
152
5,718
ai-agent-book
chapter3/retrieval-pipeline/test_improvements.py
.py
#!/usr/bin/env python3 """Test script to verify the improvements made to the retrieval pipeline.""" import subprocess import time import requests import sys import signal def test_server_startup(): """Test that the server starts without deprecation warnings.""" print("=" * 60) print("Testing Server Startu...
81
2,561
ai-agent-book
chapter3/retrieval-pipeline/config.py
.py
"""Configuration for the retrieval pipeline.""" import os from dataclasses import dataclass, field from enum import Enum from typing import Optional class SearchMode(str, Enum): """Search mode for retrieval.""" DENSE = "dense" SPARSE = "sparse" HYBRID = "hybrid" # Both dense and sparse @dataclass cl...
71
2,593
ai-agent-book
chapter3/retrieval-pipeline/document_store.py
.py
"""Document store for the retrieval pipeline.""" from typing import Dict, Any, List, Optional from datetime import datetime import logging logger = logging.getLogger(__name__) class DocumentStore: """In-memory document store for educational purposes.""" def __init__(self): self.documents: Dict[s...
99
3,765
ai-agent-book
chapter3/contextual-retrieval-for-user-memory/quickstart.py
.py
#!/usr/bin/env python3 """Quick start script for Agentic RAG User Memory Evaluation This script provides a simple demo to get started with the system. """ import os import sys from pathlib import Path from rich.console import Console from rich.panel import Panel # Check for required environment variables console = C...
163
5,673
ai-agent-book
chapter3/contextual-retrieval-for-user-memory/evaluator.py
.py
"""Evaluation Framework Integration for User Memory RAG Agent This module integrates with the user-memory-evaluation framework to load test cases and evaluate the agent's performance. """ import os import sys import json import yaml import logging from typing import List, Dict, Any, Optional, Tuple from pathlib impor...
646
26,230
ai-agent-book
chapter3/contextual-retrieval-for-user-memory/contextual_indexer.py
.py
"""Contextual RAG Indexer with Advanced Memory Cards This module combines contextual chunking for conversation histories with advanced JSON cards for structured user memory. """ import os import json import logging import requests import time from datetime import datetime from typing import List, Dict, Any, Optional,...
673
29,137
ai-agent-book
chapter3/contextual-retrieval-for-user-memory/test_top_k.py
.py
#!/usr/bin/env python3 """Test that top_k parameter works correctly with the retrieval pipeline""" import os import logging # Set up logging logging.basicConfig(level=logging.INFO) # Set dummy API key os.environ["KIMI_API_KEY"] = "test-kimi-key" from config import IndexConfig from indexer import MemoryIndexer from ...
108
3,741
ai-agent-book
chapter3/contextual-retrieval-for-user-memory/indexer.py
.py
"""RAG Indexer for User Memory Conversations This module handles indexing of conversation chunks using the retrieval pipeline service. Interfaces with the existing retrieval pipeline on port 4242. """ import os import json import logging import requests from typing import List, Dict, Any, Optional, Tuple from datacla...
458
17,816
ai-agent-book
chapter3/contextual-retrieval-for-user-memory/main.py
.py
#!/usr/bin/env python3 """Main entry point for Contextual Retrieval + Advanced Memory Cards System This demonstrates the dual-layer memory system combining: 1. Contextual chunking for conversation history 2. Advanced JSON cards for structured facts """ import argparse import json import logging import sys from pathli...
895
36,092