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 | chapter3/contextual-retrieval-for-user-memory/test_logging.py | .py | #!/usr/bin/env python3
"""Test script to verify tool logging and full content retrieval"""
import os
import json
from rich.console import Console
from chunker import ConversationChunker, ConversationChunk, ConversationMessage
from indexer import MemoryIndexer
from tools import MemoryTools
from config import Config
# ... | 263 | 9,524 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/test_fixes.py | .py | #!/usr/bin/env python3
"""Test script to verify all fixes are working"""
import logging
from config import Config
from contextual_evaluator import ContextualMemoryEvaluator
# Set up detailed logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
def t... | 74 | 2,479 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/campaign.py | .py | #!/usr/bin/env python3
"""Entry point for the shared Experiment 3-9/3-11 controlled campaign."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from memory_rag_campaign import main
if __name__ == "__main__":
raise SystemExit(main())
| 13 | 294 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/test_startup.py | .py | #!/usr/bin/env python3
"""Simple startup test to verify the system can initialize"""
import os
# Set a dummy API key for testing initialization
os.environ["KIMI_API_KEY"] = "test_key"
from rich.console import Console
console = Console()
def test_imports():
"""Test all imports work"""
try:
from confi... | 68 | 2,315 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/contextual_chunking.py | .py | """Contextual Chunking for User Memory Conversations
This module implements Anthropic's Contextual Retrieval approach specifically
for conversation histories. Each conversation chunk gets contextualized with
information about its position and meaning within the full conversation.
"""
import json
import hashlib
import... | 365 | 15,034 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/demo_ui_improvements.py | .py | #!/usr/bin/env python3
"""Demonstration of UI improvements for test case selection"""
import os
import sys
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
# Mock environment for demo
os.environ["KIMI_API_KEY"] = "demo_key"
console = Console()
def demo_single_test_selectio... | 151 | 5,729 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/advanced_memory_manager.py | .py | """Advanced Memory Manager with JSON Cards for User Memory System
This module implements the Advanced JSON Cards approach from week2/user-memory,
which stores structured, summarized core facts about users.
"""
import json
import os
import uuid
import logging
from datetime import datetime
from typing import Dict, List... | 468 | 17,118 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/test_llm_evaluation.py | .py | #!/usr/bin/env python3
"""Test script to demonstrate LLM evaluation integration"""
import os
import logging
from pathlib import Path
from rich.console import Console
from rich.panel import Panel
# Set up logging to see evaluation logs
logging.basicConfig(
level=logging.INFO,
format='%(levelname)s:%(name)s:%(m... | 203 | 7,708 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/chunker.py | .py | """Conversation Chunker for User Memory RAG System
This module handles chunking of conversation histories into manageable segments
for indexing into the RAG database.
"""
import json
import logging
from typing import List, Dict, Any, Optional, Tuple
from dataclasses import dataclass, field, asdict
from datetime impor... | 350 | 13,034 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/test_pipeline.py | .py | #!/usr/bin/env python3
"""Test script to verify the retrieval pipeline integration"""
import requests
import json
from rich.console import Console
console = Console()
def test_retrieval_pipeline():
"""Test if retrieval pipeline is available and working"""
console.print("[bold]Testing Retrieval Pipeline ... | 163 | 6,058 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/test_quick.py | .py | #!/usr/bin/env python3
"""Quick test to verify the fixes work"""
from config import Config
from contextual_evaluator import ContextualMemoryEvaluator
# Test configuration loading
config = Config.from_env()
print(f"✓ Config loaded successfully")
print(f" - EvaluationConfig.use_llm_judge: {config.evaluation.use_llm_ju... | 38 | 1,201 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/contextual_compare.py | .py | """离线对比:上下文化记忆块 vs 原始记忆块对『用户事实召回』的影响(实验 3-11)。
本模块是一个**完全离线、无需 API/外部服务**的对照实验,用于量化本章核心论点:
在把对话记忆块送入索引/嵌入之前,先为每个块生成一段『上下文前缀』(情境锚定),
能显著提升脱离上下文的孤立片段(如『好的,就订这个吧』)被正确召回的概率。
方法说明(诚实边界):
- 生产管线用 LLM 逐块生成 context、并用神经嵌入 + 检索服务做稠密/混合检索(需 API Key)。
- 这里用**确定性的 BM25 词法检索**作为无需 API 的代理:对同一份 context,
分别度量『不拼接(plain)』与『拼接后再索引(... | 246 | 9,741 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/contextual_agent.py | .py | """Contextual RAG Agent with Advanced Memory Cards
This agent combines:
1. Advanced Memory Cards (structured facts) - always in context
2. Contextual RAG for searching conversation history
"""
import json
import logging
import time
from typing import List, Dict, Any, Optional, Generator
from dataclasses import datacl... | 493 | 21,195 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/config.py | .py | """Configuration for Agentic RAG User Memory Evaluation System"""
import os
from dataclasses import dataclass, field
from typing import Optional, Dict, Any, List
from enum import Enum
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
def _reasoning_safe_temperature(model, requested=1.0):
"""... | 308 | 11,391 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/tools.py | .py | """Tool definitions for the User Memory RAG Agent
This module provides tool definitions and implementations for searching
and retrieving information from indexed conversation memories.
"""
import json
import logging
from typing import Dict, Any, List, Optional
from dataclasses import dataclass
from indexer import Me... | 321 | 11,406 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/verify_test_loading.py | .py | #!/usr/bin/env python3
"""Verify test case loading with correct field mapping"""
import os
import sys
from pathlib import Path
# Set dummy API key
os.environ["KIMI_API_KEY"] = os.getenv("KIMI_API_KEY", "test-kimi-key")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "test-openai-key")
from config import C... | 49 | 1,788 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/test_fallback_search_empty_query.py | .py | """Regression test: the fallback local search in search_with_context must not
raise ZeroDivisionError on an empty query or on chunks whose contextualized_text
is empty (e.g. loaded from disk with a missing field)."""
import os
import sys
import types
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from... | 50 | 1,776 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/contextual_evaluator.py | .py | """Contextual Memory Evaluator with Dual Memory System
This evaluator tests the combined system of:
1. Contextual RAG for conversation chunks
2. Advanced JSON cards for structured facts
"""
import os
import json
import logging
import time
import uuid
import sys
from pathlib import Path
from typing import Dict, List, ... | 763 | 33,108 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/demo_agent_logging.py | .py | #!/usr/bin/env python3
"""Demonstration of agent tool logging with full content"""
import os
import json
import logging
from rich.console import Console
from chunker import ConversationChunker, ConversationChunk, ConversationMessage
from indexer import MemoryIndexer
from agent import UserMemoryRAGAgent
from config imp... | 142 | 5,655 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/test_proactive_service.py | .py | #!/usr/bin/env python3
"""Test script to demonstrate the agent's proactive service (主动服务) capabilities"""
import logging
from datetime import datetime, timedelta
from contextual_indexer import ContextualMemoryIndexer
from contextual_agent import ContextualUserMemoryAgent
from advanced_memory_manager import AdvancedMem... | 180 | 6,934 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/agent.py | .py | """Agentic RAG Agent for User Memory Evaluation
This agent uses RAG-indexed conversation memories to answer questions
about user interactions, following the ReAct pattern.
"""
import json
import logging
from typing import List, Dict, Any, Optional, Generator
from dataclasses import dataclass, field
from datetime impo... | 379 | 15,432 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/test_contextual_system.py | .py | #!/usr/bin/env python3
"""Test script for the Contextual Retrieval + Advanced Memory Cards System"""
import logging
from config import Config
from contextual_evaluator import ContextualMemoryEvaluator
from contextual_indexer import ContextualMemoryIndexer
from contextual_agent import ContextualUserMemoryAgent
from adv... | 199 | 7,122 |
ai-agent-book | chapter3/contextual-retrieval-for-user-memory/test_enhanced_logging.py | .py | #!/usr/bin/env python3
"""Test enhanced logging of LLM responses"""
import os
import sys
import logging
# Set up logging to see all messages
logging.basicConfig(
level=logging.INFO,
format='%(levelname)s:%(name)s:%(message)s'
)
# Ensure we have API keys
if not os.getenv("KIMI_API_KEY"):
print("Please set... | 64 | 1,784 |
ai-agent-book | chapter3/mem0/quickstart.py | .py | """Quick start example for Mem0 agent with Kimi K3."""
import asyncio
import os
from dotenv import load_dotenv
from rich.console import Console
from agent import Mem0Agent
from config import Config
# Load environment variables
load_dotenv()
console = Console()
async def basic_example():
"""Basic example of u... | 306 | 11,064 |
ai-agent-book | chapter3/mem0/main.py | .py | """Main entry point for the Mem0 agent with Kimi K3."""
import asyncio
import argparse
import json
import os
from pathlib import Path
from typing import Optional
import sys
from rich.console import Console
from rich.prompt import Prompt, Confirm
from rich.panel import Panel
from rich.markdown import Markdown
from ag... | 399 | 15,925 |
ai-agent-book | chapter3/mem0/experiment.py | .py | """LOCOMO benchmark experiment runner for Mem0 agent."""
import asyncio
import json
import random
import time
from pathlib import Path
from typing import List, Dict, Any, Tuple
from datetime import datetime
import argparse
import numpy as np
import pandas as pd
from rich.console import Console
from rich.progress impo... | 447 | 20,401 |
ai-agent-book | chapter3/mem0/test_simple.py | .py | """Simple test to verify the Mem0 agent setup."""
import os
import asyncio
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
def test_imports():
"""Test that all modules can be imported."""
print("Testing imports...")
try:
from agent import Mem0Agent, AgentContext, KimiK3... | 181 | 5,344 |
ai-agent-book | chapter3/mem0/config.py | .py | """Configuration module for Mem0 agent with Kimi K3 integration."""
import os
from pathlib import Path
from typing import Optional, Dict, Any
from dataclasses import dataclass, field
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
def _reasoning_safe_temperature(model, requested=1.0):
... | 219 | 9,059 |
ai-agent-book | chapter3/mem0/test_agent_v3.py | .py | """Contract tests for the Mem0 v3 companion helpers."""
from agent import MemoryClient, Mem0Agent, _extract_added_memories, _memory_filters
class FakeMemory:
def __init__(self):
self.calls = []
def search(self, **kwargs):
self.calls.append(("search", kwargs))
return {"results": [{"id... | 80 | 2,199 |
ai-agent-book | chapter3/mem0/agent.py | .py | """Mem0-powered agent with Kimi K3 integration for LOCOMO benchmark."""
import json
import logging
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass, field
from datetime import datetime
import asyncio
from collections import defaultdict
from mem0 import Memory, MemoryClient
from op... | 525 | 21,410 |
ai-agent-book | chapter3/structured-knowledge-extraction/campaign.py | .py | #!/usr/bin/env python3
"""Canonical official-CAIL2018 campaign for Experiment 3-12."""
from __future__ import annotations
import argparse
import concurrent.futures
import hashlib
import json
import math
import os
import random
import re
import statistics
import sys
import time
import zipfile
from collections import C... | 746 | 38,712 |
ai-agent-book | chapter3/structured-knowledge-extraction/test_extraction_coverage.py | .py | from campaign import missing_extraction_rows
def test_missing_extraction_rows_finds_omissions_across_batches():
rows = [{"id": "case-a"}, {"id": "case-b"}, {"id": "case-c"}]
outputs = [
{"cases": [{"id": "case-a"}]},
{"cases": [{"id": "case-c"}]},
]
assert missing_extraction_rows(rows... | 19 | 578 |
ai-agent-book | chapter3/structured-knowledge-extraction/advisor_agent.py | .py | """
阶段 4:对话式量刑建议 Agent。
把「案件原型 + 层次因子重要性」当决策逻辑来用:
1. 从用户口语描述里抽取已知因子(复用抽取器,含罪名判定);
2. 按**全局因子重要性顺序**,找出仍缺失、但很重要的因子,生成引导性追问;
3. 信息补全后,把案件**匹配到最近的案件原型**;
4. 用 LLM 把该原型的统计数据(典型刑期区间、定义性关键因子)组织成一段
有判例支持、可解释的中文建议(附法律免责声明)。
所有刑期数字都来自原型统计,LLM 只负责"把数字讲清楚",不自行编造。
"""
from config import MODEL, get_client
from archet... | 107 | 5,134 |
ai-agent-book | chapter3/structured-knowledge-extraction/archetypes.py | .py | """
阶段 3:聚类 + 层次重要性 —— 从结构化因子里发现「案件原型」与「因子重要性层次」。
不做刑期回归(那会得到一个说不清理由的黑箱),而是:
1. 把每条案例的因子翻译成数值特征向量:
- 罪名 / 分类因子(如伤害等级) 用 one-hot 开关位(不用 1/2/3,避免暗示大小关系);
- 数值因子(金额/人数)取 ln 压缩量纲;是非情节取 0/1。
(某因子若同时落在 core 与某罪名扩展里,按 key 去重,特征列不重复。)
2. 标准化后用 KMeans 聚类,k 由轮廓系数(silhouette)自动挑选,得到若干「案件原型」;
3. 计算两级重要性:
... | 233 | 10,189 |
ai-agent-book | chapter3/structured-knowledge-extraction/extractor.py | .py | """
阶段 2:结构化抽取 —— 用发现出来的 schema 从判例文本抽取结构化因子。
流程:
1. 先判定案件罪名(从 schema 已知的罪名里选);
2. 按「核心通用因子 + 该罪名扩展因子」逐项抽取,输出结构化 JSON;
3. 文本未提及的因子返回 null(供对话 Agent 判断"还缺什么信息");
4. 带磁盘缓存(data/extracted.jsonl),一次性抽取后重跑几乎免费。
输出统一为 {"charge": <罪名>, <factor_key>: <值|null>, ...}。
"""
import json
import os
from config import MODEL... | 145 | 5,746 |
ai-agent-book | chapter3/structured-knowledge-extraction/test_normalize_numeric.py | .py | """Regression tests: _normalize must coerce non-scalar LLM-provided JSON values
(e.g. lists/dicts for a numeric factor) to None instead of raising TypeError."""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from extractor import _normalize
FACTORS = [{"key": "amount", "kind": "n... | 36 | 1,087 |
ai-agent-book | chapter3/structured-knowledge-extraction/discovery.py | .py | """
阶段 1:自下而上的因子发现(bottom-up factor discovery)。
不预先定义任何僵化的数据模式,而是:
1. 把判例文本分批喂给 LLM,让它**自由列出**每一批案例中所有可能影响判决的因素;
2. 汇总各批发现的原始因子,再用一次 LLM 调用做**归并与规范化**,产出一个
「模块化数据模式」:
- core —— 适用于所有罪名的通用因子(自首、赔偿、认罪、前科……);
- extensions —— 各罪名特有的扩展因子(盗窃→涉案金额/入户;伤害→伤害等级……)。
产出的 schema 落盘到 data/schema.js... | 142 | 6,749 |
ai-agent-book | chapter3/structured-knowledge-extraction/generate_data.py | .py | """
合成一个小样本、多罪名的刑事判例数据集。
CAIL2018(真实目标数据集)体量太大(数百万条),不便随仓库分发;本实验自带一个
可离线运行的小样本,覆盖三类罪名:盗窃罪、故意伤害罪、诈骗罪。
每条案例包含:
- `charge` 罪名(生成时已知,仅作参考;抽取阶段会由 LLM 自行判定);
- `fact` 一段自然语言判决书事实描述;
- `gold` 生成时使用的因子真值(仅供人工核对,抽取不依赖它);
- `label_months` 刑期(月),由一个「已知」的量刑公式加噪声生成。
关键点:**因子在生成时被"写进"案情文本,发现阶段再从文本里把它们"读"回来**。
生成用的字... | 176 | 8,923 |
ai-agent-book | chapter3/structured-knowledge-extraction/demo.py | .py | """
实验 3-12 全流程演示:从司法判例中提取隐性知识。
运行:
python demo.py
依次执行四个阶段:
阶段 1 自下而上因子发现:让 LLM 自由归纳因子,归并成模块化 schema(核心+各罪名扩展);
阶段 2 结构化抽取:用发现的 schema 从每条判例抽取因子(带缓存);
阶段 3 聚类 + 层次重要性:把因子向量聚成「案件原型」,算全局与原型内因子重要性;
阶段 4 对话式建议 Agent:把新案情匹配到最近原型,按重要性追问缺失因子,给出建议。
"""
import json
import os
import sys
import archetypes
impo... | 90 | 3,487 |
ai-agent-book | chapter3/structured-knowledge-extraction/config.py | .py | """
全局配置:加载环境变量、提供 OpenAI 客户端与默认模型名。
只依赖官方 OpenAI SDK,读取 OPENAI_API_KEY。
默认模型 gpt-5.6-luna(便宜、够用于因子发现、结构化抽取与文案生成)。
"""
import os
from openai import OpenAI
try:
# 可选:如果安装了 python-dotenv,则自动加载同目录 .env
from dotenv import load_dotenv
load_dotenv()
except Exception: # pragma: no cover - dotenv 是可选依赖
pas... | 94 | 3,750 |
ai-agent-book | chapter3/structured-knowledge-extraction/test_archetypes_small_charge.py | .py | """Regression: fit must not unpack None when a charge has fewer than 3 samples."""
import sys
import types
import numpy as np
def _stub():
for name in ["sklearn", "sklearn.preprocessing", "sklearn.cluster", "sklearn.metrics"]:
sys.modules.setdefault(name, types.ModuleType(name))
# Minimal stubs so im... | 35 | 949 |
ai-agent-book | chapter3/structured-knowledge-extraction/test_advise_zero_archetypes.py | .py | """advise() must not TypeError-unpack when the model has zero archetypes."""
import sys
import types
import pytest
# Stub openai/config client so LegalAdvisorAgent can be constructed offline.
import config as cfg
cfg.get_client = lambda: object()
from advisor_agent import LegalAdvisorAgent # noqa: E402
from archet... | 36 | 1,146 |
ai-agent-book | chapter3/sparse-embedding/quickstart.py | .py | #!/usr/bin/env python3
"""
Quick start script for the Educational Sparse Vector Search Engine
Demonstrates basic usage in a simple, interactive way
"""
import logging
from bm25_engine import SparseSearchEngine
# Configure logging to show educational information
logging.basicConfig(
level=logging.INFO,
format=... | 185 | 7,554 |
ai-agent-book | chapter3/sparse-embedding/bm25_engine.py | .py | """
BM25 Sparse Vector Search Engine
An educational implementation of BM25 algorithm with inverted index
"""
import math
import re
import logging
from collections import defaultdict, Counter
from typing import List, Dict, Set, Tuple, Optional
# Configure logging for educational purposes
logging.basicConfig(
level... | 530 | 20,749 |
ai-agent-book | chapter3/sparse-embedding/server.py | .py | """
HTTP API Server for Sparse Vector Search Engine
Educational server with extensive logging and visualization
"""
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field
from typing import List, Dict, Optional
import uvicorn
import logging
im... | 504 | 18,238 |
ai-agent-book | chapter3/sparse-embedding/test_engine.py | .py | """
Test script for the Educational Sparse Vector Search Engine
Tests core functionality and demonstrates educational aspects
"""
import logging
from bm25_engine import TextProcessor, InvertedIndex, BM25, SparseSearchEngine
# Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(... | 322 | 11,962 |
ai-agent-book | chapter3/sparse-embedding/benchmark.py | .py | #!/usr/bin/env python3
"""Acceptance campaign for Chapter 3 Experiments 3-5.
This intentionally exercises the repository's from-scratch inverted index and
BM25 implementation. It checks one score against an independent, explicit
calculation and then measures the exact-keyword/synonym contrast on a labelled
corpus. N... | 192 | 7,038 |
ai-agent-book | chapter3/sparse-embedding/demo.py | .py | """
Demo script for the Educational Sparse Vector Search Engine
Shows how to use the engine with sample documents and queries
"""
import requests
import json
import time
import logging
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = lo... | 287 | 11,737 |
ai-agent-book | chapter3/sparse-embedding/test_bm25_empty_term.py | .py | import pytest
from bm25_engine import InvertedIndex, BM25, TextProcessor
def test_bm25_search_empty_term_in_query_terms_no_index_error():
index = InvertedIndex()
index.add_document(1, "hello world")
bm25 = BM25(index)
orig_tokenize = TextProcessor.tokenize
try:
TextProcessor.tokenize = la... | 18 | 541 |
ai-agent-book | chapter3/sparse-embedding/cli.py | .py | #!/usr/bin/env python3
"""
稀疏检索命令行工具(实验 3-5)
在一个小型示例语料上运行 BM25 稀疏检索,支持:
- 自定义语料 / 查询 / top-k / 输出文件
- --explain 复现书中"逐词 IDF / TF / BM25 贡献"的日志
- --eval 在带标注的小型评测集上计算 recall@k / precision@k / MRR
- --method splade 学习型稀疏检索(需要下载模型,离线环境会给出提示)
不带任何参数运行时,等价于书中实验 3-5 的默认演示(查询"model distillation")。
"""
import argpar... | 342 | 16,004 |
ai-agent-book | chapter3/sparse-embedding/config.py | .py | """Configuration for the sparse embedding service."""
import os
# Server configuration
SPARSE_PORT = int(os.getenv("SPARSE_PORT", "4241")) # Port 4241 to avoid conflicts
SPARSE_HOST = os.getenv("SPARSE_HOST", "0.0.0.0")
# Logging
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
| 11 | 277 |
ai-agent-book | chapter3/sparse-embedding/test_tokenize_apostrophes.py | .py | import pytest
from bm25_engine import TextProcessor
def test_tokenize_preserves_apostrophe_contractions():
processor = TextProcessor()
tokens = processor.tokenize("don't user's it's text")
assert "don't" in tokens
assert "user's" in tokens
assert "it's" in tokens
| 11 | 286 |
ai-agent-book | chapter3/log-sanitization/samples.py | .py | """
用于日志脱敏演示的代表性样本
这些样本模拟真实 Agent 运行时最容易泄露敏感信息的几种场景:
工具调用的 HTTP 请求/响应、客服对话、数据库连接报错、CI/Git 日志、
以及配置转储。它们混合了密钥类(API Key、令牌、私钥)与 PII 类
(身份证、手机号、信用卡、邮箱)敏感信息,便于展示脱敏的覆盖面。
注意:以下所有密钥、卡号、证件号均为虚构,仅用于演示,不对应任何真实账户。
"""
OPENAI_STYLE_SAMPLE_KEY = "sk" + "-proj-ABCD1234efgh5678IJKL9012mnop3456qrst"
GOOGLE_SAMPLE_KEY = "AI" + "zaSy... | 66 | 2,726 |
ai-agent-book | chapter3/log-sanitization/main.py | .py | #!/usr/bin/env python3
"""
Main script for Log Sanitization using Local LLM
"""
import argparse
import sys
from collections import Counter
from pathlib import Path
from typing import Optional
from config import OUTPUT_DIR, OLLAMA_MODEL
import regex_sanitizer
from samples import SAMPLES
def main(test_id: Optional[st... | 301 | 10,602 |
ai-agent-book | chapter3/log-sanitization/campaign.py | .py | #!/usr/bin/env python3
"""Real local-model benchmark for Experiment 3-3.
Compares the existing regex engine, local Qwen3 through Ollama, and a hybrid
regex-first/LLM-second path on labeled logs. Gold values are intentionally
fictional. Metrics are exact-span precision/recall, residual leakage, utility,
and latency; ... | 270 | 12,375 |
ai-agent-book | chapter3/log-sanitization/test_loader.py | .py | """
Test Case Loader for User Memory Evaluation Framework
"""
import sys
import json
import subprocess
from pathlib import Path
from typing import Dict, List, Optional, Any
from config import EVAL_FRAMEWORK_PATH
class TestCaseLoader:
"""Load test cases from user-memory-evaluation framework"""
def __init_... | 174 | 5,323 |
ai-agent-book | chapter3/log-sanitization/metrics.py | .py | """
Performance Metrics Module for Log Sanitization
"""
import time
import json
from typing import Dict, List, Optional
from pathlib import Path
from dataclasses import dataclass, asdict
from datetime import datetime
@dataclass
class PerformanceMetrics:
"""Store performance metrics for a single sanitization opera... | 176 | 6,746 |
ai-agent-book | chapter3/log-sanitization/config.py | .py | """
Configuration for Log Sanitization with Local LLM
"""
import os
from pathlib import Path
# Ollama Configuration
# 默认使用 0.6B 超小模型,呼应本章“小模型也能胜任结构化任务”的论点,
# 且可在 CPU / 消费级设备上运行;可用 --model 覆盖为 qwen3:1.7b、qwen3:4b 等。
OLLAMA_MODEL = "qwen3:0.6b"
OLLAMA_TEMPERATURE = 0.1 # Low temperature for consistent detection
# Pat... | 85 | 2,858 |
ai-agent-book | chapter3/log-sanitization/regex_sanitizer.py | .py | """
基于规则(正则)的离线日志脱敏引擎
与 agent.py 中依赖本地 LLM 的方案互补:本模块不需要任何模型或网络,
纯靠正则表达式 + 校验算法(Luhn、身份证校验码)识别日志 / 工具输出中的
敏感信息,速度快、结果确定,适合作为 Agent 日志落盘前的第一道防线。
覆盖的敏感信息类别(按匹配优先级从高到低):
- 私钥 / 证书(PEM 块)
- JWT
- 云厂商与第三方密钥(AWS AKIA、GitHub、Slack、Google、OpenAI 风格 sk-)
- HTTP Authorization: Bearer / Basic 令牌
- 配置中的口令 / 密钥赋值(passwor... | 280 | 9,209 |
ai-agent-book | chapter3/log-sanitization/agent.py | .py | """
Log Sanitization Agent using Local Ollama LLM
"""
import os
import time
import re
import json
from typing import List, Tuple, Dict, Optional
from pathlib import Path
import ollama
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
from config import (
OLLAMA_MODEL,
OL... | 410 | 16,180 |
ai-agent-book | chapter3/log-sanitization/tests/test_null_pii_values.py | .py | """detect_pii must treat JSON null pii_values like an empty list."""
import json
from unittest.mock import patch
from agent import LogSanitizationAgent
def test_null_pii_values_returns_empty_list():
agent = object.__new__(LogSanitizationAgent)
agent.count_tokens = lambda text: len(text) // 4
agent._chat_... | 34 | 1,019 |
ai-agent-book | chapter3/log-sanitization/tests/test_authorization_basic.py | .py | """Authorization: Basic credentials must be redacted like Bearer tokens."""
from regex_sanitizer import sanitize
def test_authorization_basic_redacted():
cred = "dXNlcjpwYXNzd29yZA=="
text, hits = sanitize(f"Authorization: Basic {cred}")
assert cred not in text
assert "[REDACTED_BASIC_AUTH]" in text
... | 41 | 1,394 |
ai-agent-book | chapter3/log-sanitization/tests/test_url_credential_empty_user.py | .py | """Regression: URL credentials with an empty username must be redacted."""
from regex_sanitizer import sanitize
def test_redis_empty_user_password_redacted():
text, hits = sanitize("redis://:secretpass@10.0.0.1:6379/0")
assert "secretpass" not in text
assert "[REDACTED_URL_CRED]" in text
assert any(h[... | 23 | 835 |
ai-agent-book | chapter3/log-sanitization/tests/test_sanitize_conversation.py | .py | #!/usr/bin/env python3
"""Regression tests for sanitize_conversation() in agent.py.
Bug: detect_pii() catches any backend exception and returns ([], {}), but
sanitize_conversation then subscripted the empty metrics dict
(perf_metrics['input_tokens']) -> KeyError that killed the whole batch.
Fixed with .get(..., 0) def... | 140 | 4,544 |
ai-agent-book | chapter3/log-sanitization/tests/test_github_pat.py | .py | """Regression: fine-grained github_pat_* tokens must be redacted."""
from regex_sanitizer import sanitize
def test_github_pat_fine_grained_redacted():
token = "github_pat_" + "A" * 20 + "_" + "B" * 40
text, hits = sanitize(f"Authorization: {token}")
assert token not in text
assert "[REDACTED_GITHUB_TO... | 19 | 650 |
ai-agent-book | chapter3/log-sanitization/tests/test_truncated_pem.py | .py | """Truncated PEM (BEGIN without END) must be redacted, not leaked."""
from regex_sanitizer import sanitize
PEM_HEADER = "-----BEGIN " + "RSA PRIVATE KEY-----\n"
PEM_FOOTER = "-----END " + "RSA PRIVATE KEY-----"
def test_truncated_rsa_pem_without_end_redacted():
blob = (
PEM_HEADER +
"MIIEowIBAAK... | 37 | 1,136 |
ai-agent-book | chapter3/log-sanitization/tests/test_quoted_secret_spaces.py | .py | """Regression: quoted secret assignments must redact the full value, including spaces."""
from regex_sanitizer import sanitize
def test_double_quoted_password_with_spaces():
text, hits = sanitize('password="hunter 2 with spaces"')
assert "hunter" not in text
assert "spaces" not in text
assert "[REDACT... | 24 | 795 |
ai-agent-book | chapter3/log-sanitization/tests/test_url_credential_colon_slash.py | .py | """Regression: URL passwords containing ':' or '/' must be fully redacted."""
from regex_sanitizer import sanitize
def test_password_with_slash_redacted():
text, hits = sanitize("DATABASE_URL=postgres://alice:a/b@db.example:5432/app")
assert "a/b" not in text
assert "[REDACTED_URL_CRED]" in text
asser... | 24 | 880 |
ai-agent-book | chapter3/log-sanitization/tests/conftest.py | .py | """Shared bootstrap for log-sanitization regression tests."""
import sys
from pathlib import Path
from types import ModuleType, SimpleNamespace
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
try:
import ollama # noqa: F401
exce... | 23 | 591 |
ai-agent-book | chapter3/log-sanitization/tests/manual/loader_debug.py | .py | #!/usr/bin/env python3
"""Debug script to test loading conversations"""
import sys
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[2]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from test_loader import TestCaseLoader
def main():
loader = TestCaseLoad... | 43 | 1,281 |
ai-agent-book | chapter3/agentic-rag/quickstart.py | .py | #!/usr/bin/env python3
"""Quick start script for Agentic RAG system"""
import os
import sys
import json
from pathlib import Path
def check_environment():
"""Check if environment is properly configured"""
print("🔍 Checking environment...")
# Check for .env file
if not Path(".env").exists() and P... | 225 | 6,773 |
ai-agent-book | chapter3/agentic-rag/test_structured_backends.py | .py | """
Test script for Agentic RAG with structured index backends (RAPTOR and GraphRAG).
"""
import asyncio
import logging
import os
import pytest
from config import Config, KnowledgeBaseType
from agent import AgenticRAG
# These are manual end-to-end checks for separately launched RAPTOR/GraphRAG
# services, not hermeti... | 215 | 7,236 |
ai-agent-book | chapter3/agentic-rag/compare_offline.py | .py | """离线对比实验:智能体化 RAG(多轮/分解检索)vs 非智能体化 RAG(单次检索)。
本脚本**完全离线运行**——只做检索、不调用任何 LLM、不依赖外部检索服务,
因此无需 API Key 即可复现。它在一个小型中文司法问答集(evaluation/offline_qa.json)
上,量化对比两种检索范式的『证据召回率』:
- 非智能体化:把用户原始问题作为唯一查询做一次检索(single-shot);
- 智能体化:模拟 Agent 分解/改写问题后发起多次检索,再对结果取并集。
金标准(gold_articles)为回答每个问题所必需的法条编号;某法条被判定为『命中』
当且仅当检索结果中存在一个以该法... | 190 | 7,988 |
ai-agent-book | chapter3/agentic-rag/main.py | .py | """Main entry point for Agentic RAG system"""
import os
import json
import logging
import argparse
from typing import Optional
from config import Config, KnowledgeBaseType
from agent import AgenticRAG
from chunking import DocumentIndexer
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %... | 319 | 12,251 |
ai-agent-book | chapter3/agentic-rag/campaign.py | .py | #!/usr/bin/env python3
"""Canonical live campaign for Experiment 3-8.
The comparison keeps the corpus, cases, BM25 implementation, retrieval depth,
answer model, and independent judge fixed. The only changed factor is whether
the answerer receives one search of the original question or may plan and
iterate searches t... | 379 | 17,721 |
ai-agent-book | chapter3/agentic-rag/offline_retriever.py | .py | """In-process offline retriever (BM25 over the local law corpus).
This backend makes the whole experiment runnable without the external
`retrieval-pipeline` HTTP service: it reads the Markdown law files under
``laws/``, splits them into article-level chunks (每一条法条一个 chunk), and
scores queries with Okapi BM25. Retrieva... | 214 | 7,841 |
ai-agent-book | chapter3/agentic-rag/test_chunk_size_zero.py | .py | """Regression: chunk_size=0 must not crash range() on long sentences.
Use the experiment's real configuration module. The former process-global
``sys.modules['config']`` stub leaked into later test modules and made their
imports depend on pytest collection order.
"""
from config import ChunkingConfig
from chunking i... | 19 | 700 |
ai-agent-book | chapter3/agentic-rag/index_local_laws.py | .py | """Script to chunk and index local legal documents from laws directory
This script:
1. Cleans up existing indexes
2. Reads legal documents from local laws directory
3. Chunks them with paragraph-aware boundaries (soft limit 1024, hard limit 2048)
4. Indexes them in the retrieval pipeline
"""
import os
import json
imp... | 491 | 18,785 |
ai-agent-book | chapter3/agentic-rag/test_history_limit_zero.py | .py | """conversation_history_limit=0 must omit history, not include all via [-0:]."""
from types import SimpleNamespace
from unittest.mock import MagicMock
from agent import AgenticRAG
def test_history_limit_zero_omits_history():
agent = object.__new__(AgenticRAG)
agent.config = SimpleNamespace(
agent=Sim... | 41 | 1,326 |
ai-agent-book | chapter3/agentic-rag/test_simple.py | .py | #!/usr/bin/env python3
"""Simple test script for Agentic RAG system"""
import os
import json
from pathlib import Path
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
def _basic_functionality():
"""Test basic functionality of the system"""
print("🧪 Testing Agentic RAG System")
p... | 196 | 6,750 |
ai-agent-book | chapter3/agentic-rag/config.py | .py | """Configuration for Agentic RAG System"""
import os
from dataclasses import dataclass, field
from typing import Optional, Dict, Any
from enum import Enum
from dotenv import load_dotenv
load_dotenv()
def _openrouter_model_id(model: Optional[str]) -> str:
"""Map a provider-native model name to an OpenRouter mode... | 260 | 9,024 |
ai-agent-book | chapter3/agentic-rag/tools.py | .py | """Tools for knowledge base interaction"""
import json
import logging
import requests
from typing import Dict, Any, List, Optional
from dataclasses import dataclass
from config import KnowledgeBaseConfig, KnowledgeBaseType
logger = logging.getLogger(__name__)
@dataclass
class SearchResult:
"""Search result fro... | 514 | 20,148 |
ai-agent-book | chapter3/agentic-rag/chunking.py | .py | """Document chunking and indexing script"""
import os
import json
import hashlib
import logging
import requests
from typing import List, Dict, Any, Optional, Tuple
from pathlib import Path
from datetime import datetime
from config import ChunkingConfig, KnowledgeBaseConfig, KnowledgeBaseType
logging.basicConfig(leve... | 424 | 15,904 |
ai-agent-book | chapter3/agentic-rag/agent.py | .py | """Agentic RAG System with ReAct Pattern"""
import json
import logging
from typing import List, Dict, Any, Optional, Generator
from dataclasses import dataclass, field
from datetime import datetime
from openai import OpenAI
from config import Config, LLMConfig, AgentConfig
from tools import KnowledgeBaseTools, get_to... | 460 | 19,784 |
ai-agent-book | chapter3/agentic-rag/evaluation/test_evaluate_empty_expected.py | .py | """
Test suite locking out ZeroDivisionError in RAGEvaluator.evaluate_response
when test_case contains empty expected_keywords or expected_analysis lists.
"""
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
from evaluate import RAGEvaluator
def test_evaluate_response_empty_expec... | 40 | 1,215 |
ai-agent-book | chapter3/agentic-rag/evaluation/evaluate.py | .py | """Evaluation framework for Agentic RAG system"""
import json
import logging
import time
from typing import List, Dict, Any, Optional
from pathlib import Path
import sys
import os
# ``evaluation`` is intentionally runnable both as a script directory and via
# pytest from the repository root. Put this experiment's di... | 405 | 17,710 |
ai-agent-book | chapter3/agentic-rag/evaluation/dataset_builder.py | .py | """Build evaluation dataset from Chinese legal documents"""
import json
import logging
from typing import List, Dict, Any
from pathlib import Path
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class LegalDatasetBuilder:
"""Build evaluation dataset for Chinese legal Q&A"""
... | 318 | 16,935 |
ai-agent-book | chapter3/agentic-rag-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... | 162 | 5,644 |
ai-agent-book | chapter3/agentic-rag-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 ... | 73 | 2,485 |
ai-agent-book | chapter3/agentic-rag-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 re
import math
import json
import logging
import requests
from collections import Counter
from typin... | 574 | 22,342 |
ai-agent-book | chapter3/agentic-rag-for-user-memory/main.py | .py | #!/usr/bin/env python3
"""Main entry point for Agentic RAG User Memory Evaluation System
This script provides an interactive interface for:
1. Loading test cases from the user-memory-evaluation framework
2. Chunking and indexing conversation histories
3. Evaluating the RAG agent on selected test cases
"""
import argp... | 747 | 30,502 |
ai-agent-book | chapter3/agentic-rag-for-user-memory/offline_demo.py | .py | #!/usr/bin/env python3
"""实验 3-9 离线演示:智能体化记忆检索 vs. 朴素单次检索
本脚本完全离线运行(不需要 port 4242 检索服务,也不需要任何 LLM API Key),
用来直观展示书中实验 3-9 的核心论点:
把用户的跨会话对话历史当作知识库、赋予 Agent「多轮迭代检索」能力后,
它能主动发现单次检索会遗漏的关键信息,从而在「第二层次·多会话检索」
任务上显著超过朴素的一次性检索(naive recall)。
演示载体是评估集里的 layer2_01_multiple_vehicles 用例:用户在两通不同电话里
分别聊到本田 Accord(已在 Firesto... | 294 | 13,614 |
ai-agent-book | chapter3/agentic-rag-for-user-memory/config.py | .py | """Configuration for Agentic RAG User Memory Evaluation System"""
import os
from dataclasses import dataclass, field
from typing import Optional, Dict, Any, List
from enum import Enum
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
def _reasoning_safe_temperature(model, requested=1.0):
"""... | 319 | 12,005 |
ai-agent-book | chapter3/agentic-rag-for-user-memory/agent.py | .py | """Agentic RAG Agent for User Memory Evaluation
This agent uses RAG-indexed conversation memories to answer questions
about user interactions, following the ReAct pattern.
"""
import json
import logging
from typing import List, Dict, Any, Optional, Generator
from dataclasses import dataclass, field
from datetime impo... | 383 | 15,554 |
ai-agent-book | chapter3/memobase/quickstart.py | .py | """
Quick start script for testing Memobase Agent
"""
import os
import sys
from pathlib import Path
# Add parent directory to path for imports
sys.path.insert(0, str(Path(__file__).parent))
from agent import MemobaseAgent
from locomo_benchmark import LOCOMOBenchmark, BenchmarkTask
def quick_demo():
"""Run a qu... | 161 | 6,324 |
ai-agent-book | chapter3/memobase/main.py | .py | """
Main entry point for Memobase Agent with LOCOMO Benchmark
"""
import argparse
import logging
import sys
from pathlib import Path
from datetime import datetime
import json
from typing import Optional
from agent import MemobaseAgent
from locomo_benchmark import LOCOMOBenchmark, BenchmarkTask
from config import (
... | 325 | 10,907 |
ai-agent-book | chapter3/memobase/locomo_benchmark.py | .py | """
LOCOMO Benchmark Implementation for Memobase Agent
Evaluates agent performance on long-context and memory-intensive tasks
"""
import json
import time
import logging
from typing import List, Dict, Any, Optional, Tuple
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
fr... | 597 | 23,935 |
ai-agent-book | chapter3/memobase/profile_demo.py | .py | """
Memobase 用户画像(Profile)+ 事件记忆(Event Memory)演示
对应《深入理解 AI Agent》第 3 章"记忆框架案例"中对 Memobase 的介绍:
Memobase(开源项目 memodb-io/memobase)把用户记忆组织为两部分——
* 用户画像(Profile):按"主题—子主题"两级组织的稳定用户属性
(如 basic_info→姓名、interest→游戏偏好、work→职位),从对话中提取;
* 事件记忆(Event Memory):按时间线记录用户经历的事件,
用于回答"我们上次讨论预算是什么时候"这类与时间有关的问题。
工程上 Memobase... | 325 | 13,054 |
ai-agent-book | chapter3/memobase/config.py | .py | """
Configuration for Memobase Agent with Kimi K3 Model
"""
import os
from pathlib import Path
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 OpenRouter fal... | 141 | 4,449 |
ai-agent-book | chapter3/memobase/test_memory.py | .py | """
Test script for Memobase memory functionality
"""
import os
import sys
import time
from pathlib import Path
from datetime import datetime
# Add parent directory to path for imports
sys.path.insert(0, str(Path(__file__).parent))
from agent import Memory, MemoryStore, MemoryCluster, MemobaseAgent
from config impor... | 281 | 8,478 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.