ai-agent-book 精选快照(<2MB 代码与文档,来自 github.com/bojieli/ai-agent-book)
Build latest book artifacts / build (push) Canceled after 0s
dependency resolution / resolve (3.11) (push) Canceled after 0s
dependency resolution / resolve (3.13) (push) Canceled after 0s
deploy-pages / build (push) Canceled after 0s
deploy-pages / deploy (push) Canceled after 0s
i18n consistency check / check (push) Canceled after 0s
provider adoption tests / test (chapter2/context-compression) (push) Canceled after 0s
provider adoption tests / test (chapter2/prompt-injection) (push) Canceled after 0s
provider adoption tests / test (chapter2/system-hint) (push) Canceled after 0s
provider adoption tests / test (chapter3/log-sanitization) (push) Canceled after 0s
web-search-agent tests / test (push) Canceled after 0s
web-search-agent tests / agentbook (push) Canceled after 0s

This commit is contained in:
2026-08-20 13:12:50 +00:00
commit b119135836
10275 changed files with 3284984 additions and 0 deletions
@@ -0,0 +1,139 @@
"""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 import OpenAI
from domain_tools import execute_tool
ROOT = Path(__file__).resolve().parent
def _load_json(path: Path) -> Any:
with path.open(encoding="utf-8") as handle:
return json.load(handle)
class GeneratedAgent:
def __init__(self, *, model: str | None = None, client: Any | None = None):
self.model = model or os.getenv("OPENAI_MODEL") or os.getenv(
"OPENROUTER_MODEL", "openai/gpt-5.6-luna"
)
use_router = bool(os.getenv("OPENROUTER_API_KEY")) and (
"/" in self.model
or os.getenv("AGENT_PROVIDER", "auto").casefold() in {"auto", "openrouter"}
)
api_key = os.getenv("OPENROUTER_API_KEY") if use_router else os.getenv("OPENAI_API_KEY")
base_url = "https://openrouter.ai/api/v1" if use_router else os.getenv("OPENAI_BASE_URL")
if client is None and not api_key:
raise RuntimeError("Set OPENAI_API_KEY or OPENROUTER_API_KEY")
self.client = client or OpenAI(api_key=api_key, base_url=base_url)
self.system_prompt = (ROOT / "system_prompt.md").read_text(encoding="utf-8")
self.tools = _load_json(ROOT / "tools.json")["tools"]
@staticmethod
def _assistant_message(message: Any) -> dict[str, Any]:
result: dict[str, Any] = {"role": "assistant", "content": message.content or ""}
if message.tool_calls:
result["tool_calls"] = [
{
"id": call.id,
"type": "function",
"function": {
"name": call.function.name,
"arguments": call.function.arguments,
},
}
for call in message.tool_calls
]
return result
def run(
self,
task: str,
*,
history: list[dict[str, Any]] | None = None,
max_iterations: int = 12,
) -> dict[str, Any]:
messages: list[dict[str, Any]] = [
{"role": "system", "content": self.system_prompt},
*(history or []),
{"role": "user", "content": task},
]
trace: list[dict[str, Any]] = []
usage_totals = {
"prompt_tokens": 0,
"cached_prompt_tokens": 0,
"completion_tokens": 0,
"requests": 0,
}
for iteration in range(1, max_iterations + 1):
kwargs = dict(
model=self.model,
messages=messages,
tools=self.tools,
tool_choice="auto",
)
if any(tag in self.model.casefold() for tag in ("kimi-", "gpt-5")):
kwargs["temperature"] = 1
else:
kwargs["temperature"] = 0
response = self.client.chat.completions.create(**kwargs)
message = response.choices[0].message
messages.append(self._assistant_message(message))
usage = getattr(response, "usage", None)
prompt_details = getattr(usage, "prompt_tokens_details", None)
usage_totals["prompt_tokens"] += getattr(usage, "prompt_tokens", 0) or 0
usage_totals["cached_prompt_tokens"] += (
getattr(prompt_details, "cached_tokens", 0) or 0
)
usage_totals["completion_tokens"] += (
getattr(usage, "completion_tokens", 0) or 0
)
usage_totals["requests"] += 1
trace.append({
"iteration": iteration,
"content": message.content or "",
"tool_calls": len(message.tool_calls or []),
"prompt_tokens": getattr(usage, "prompt_tokens", None),
"completion_tokens": getattr(usage, "completion_tokens", None),
})
if not message.tool_calls:
return {
"ok": True,
"answer": message.content or "",
"iterations": iteration,
"trace": trace,
"messages": messages,
"usage": usage_totals,
}
for call in message.tool_calls:
try:
arguments = json.loads(call.function.arguments or "{}")
result = execute_tool(call.function.name, arguments)
except Exception as exc: # tool failures must return to the model
result = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result, ensure_ascii=False),
})
return {
"ok": False,
"answer": "",
"iterations": max_iterations,
"trace": trace,
"messages": messages,
"usage": usage_totals,
"error": "maximum iterations reached",
}
@@ -0,0 +1,24 @@
{
"schema_version": "1.0",
"name": "Reference Policy Agent",
"role": "Evaluate structured policy records using only supplied evidence.",
"requirements": "Demonstrate the uncustomized policy-record template.",
"sample_task": "Evaluate the supplied checks.",
"tool_name": "evaluate_required_records",
"tool_description": "Evaluate every user-supplied record against its required passing state.",
"record_noun": "policy record",
"records_argument": "records",
"identifier_field": "id",
"required_field": "required",
"status_field": "status",
"evidence_field": "evidence",
"passing_values": [
"passed"
],
"approved_label": "APPROVED",
"rejected_label": "REFUSED",
"remediation_by_status": {
"failed": "Correct the failed requirement and rerun it."
},
"default_remediation": "Resolve the non-passing requirement and attach passing evidence."
}
@@ -0,0 +1,88 @@
"""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:
value = json.load(handle)
if not isinstance(value, dict):
raise ValueError("domain_spec.json must contain an object")
return value
def evaluate_policy_records(records: list[dict[str, Any]]) -> dict[str, Any]:
spec = _spec()
required_field = spec["required_field"]
status_field = spec["status_field"]
identifier_field = spec["identifier_field"]
evidence_field = spec["evidence_field"]
passing = {str(value).casefold() for value in spec["passing_values"]}
remediation = {
str(key).casefold(): value
for key, value in spec["remediation_by_status"].items()
}
failures: list[dict[str, Any]] = []
normalized: list[dict[str, Any]] = []
for index, record in enumerate(records):
if not isinstance(record, dict):
raise ValueError(f"record {index} must be an object")
missing = [
field
for field in (identifier_field, required_field, status_field, evidence_field)
if field not in record
]
if missing:
raise ValueError(f"record {index} missing fields: {', '.join(missing)}")
if not isinstance(record[required_field], bool):
raise ValueError(f"record {index} {required_field} must be boolean")
status = str(record[status_field])
row = {
"id": record[identifier_field],
"required": record[required_field],
"status": status,
"evidence": record[evidence_field],
"passed": status.casefold() in passing,
}
normalized.append(row)
if row["required"] and not row["passed"]:
failures.append(
{
**row,
"remediation": remediation.get(
status.casefold(), spec["default_remediation"]
),
}
)
approved = not failures
return {
"approved": approved,
"decision": spec["approved_label"] if approved else spec["rejected_label"],
"evaluated_count": len(normalized),
"failed_required_count": len(failures),
"failed_required_records": failures,
"records": normalized,
}
def execute_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
spec = _spec()
if name == spec["tool_name"]:
records = arguments.get(spec["records_argument"])
if not isinstance(records, list) or not records:
return {
"ok": False,
"error": f"{spec['records_argument']} must be a non-empty array",
}
try:
return {"ok": True, "result": evaluate_policy_records(records)}
except (KeyError, TypeError, ValueError) as exc:
return {"ok": False, "error": str(exc)}
return {"ok": False, "error": f"unknown tool: {name}"}
@@ -0,0 +1,24 @@
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", default="[]")
args = parser.parse_args()
history = json.loads(args.history_json)
if not isinstance(history, list):
raise SystemExit("--history-json must decode to a list")
result = GeneratedAgent(model=args.model).run(args.task, history=history)
print(json.dumps(result, ensure_ascii=False, indent=2))
raise SystemExit(0 if result["ok"] else 1)
if __name__ == "__main__":
main()
@@ -0,0 +1,2 @@
openai>=1.30.0
pytest>=7.0.0
@@ -0,0 +1,9 @@
You are a reliable, tool-using assistant.
Follow these rules:
1. Use tools whenever the answer depends on external or computed facts.
2. Never invent a tool result. Wait for the tool response and cite it in the answer.
3. Validate required arguments before calling a tool.
4. If a tool fails, explain the failure and either correct the arguments or stop safely.
5. Keep responses concise and explicitly distinguish observations from conclusions.
@@ -0,0 +1,74 @@
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, **kwargs):
self.calls.append(copy.deepcopy(kwargs))
if len(self.calls) == 1:
tool_call = SimpleNamespace(
id="call-1",
function=SimpleNamespace(
name="lookup_domain_fact",
arguments=json.dumps({"query": "purpose"}),
),
)
message = SimpleNamespace(content=None, tool_calls=[tool_call])
else:
assert kwargs["messages"][-1]["role"] == "tool"
message = SimpleNamespace(content="Verified answer", tool_calls=[])
usage = SimpleNamespace(prompt_tokens=10, completion_tokens=3)
return SimpleNamespace(choices=[SimpleNamespace(message=message)], usage=usage)
def test_standard_tool_loop_keeps_assistant_call_and_tool_result():
completions = FakeCompletions()
client = SimpleNamespace(chat=SimpleNamespace(completions=completions))
result = GeneratedAgent(model="test-model", client=client).run("What is your purpose?")
assert result["ok"] is True
assert result["answer"] == "Verified answer"
second_messages = completions.calls[1]["messages"]
assert second_messages[-2]["role"] == "assistant"
assert second_messages[-2]["tool_calls"][0]["id"] == "call-1"
assert second_messages[-1]["role"] == "tool"
assert second_messages[-1]["tool_call_id"] == "call-1"
assert result["messages"][:-1] == second_messages
assert result["messages"][-1] == {
"role": "assistant",
"content": "Verified answer",
}
assert result["usage"] == {
"prompt_tokens": 20,
"cached_prompt_tokens": 0,
"completion_tokens": 6,
"requests": 2,
}
def test_prior_multiturn_history_is_preserved_in_order():
completions = FakeCompletions()
client = SimpleNamespace(chat=SimpleNamespace(completions=completions))
history = [
{"role": "user", "content": "Remember owner Mei-Lin."},
{"role": "assistant", "content": "Owner Mei-Lin retained."},
]
result = GeneratedAgent(model="test-model", client=client).run(
"Evaluate the release.", history=history
)
first_messages = completions.calls[0]["messages"]
assert first_messages[1:3] == history
assert result["messages"][1:3] == history
@@ -0,0 +1,63 @@
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="utf-8"))
def record(spec, *, identifier, required, status, evidence):
return {
spec["identifier_field"]: identifier,
spec["required_field"]: required,
spec["status_field"]: status,
spec["evidence_field"]: evidence,
}
def test_required_nonpassing_record_refuses_with_exact_evidence():
spec = load_spec()
records = [
record(
spec,
identifier="required-check",
required=True,
status="failed",
evidence="observed failure",
)
]
result = execute_tool(spec["tool_name"], {spec["records_argument"]: records})
assert result["ok"] is True
assert result["result"]["approved"] is False
assert result["result"]["decision"] == spec["rejected_label"]
assert result["result"]["failed_required_records"][0]["evidence"] == "observed failure"
def test_only_required_nonpassing_records_block_approval():
spec = load_spec()
passing = spec["passing_values"][0]
records = [
record(spec, identifier="required", required=True, status=passing, evidence="ok"),
record(spec, identifier="optional", required=False, status="failed", evidence="optional"),
]
result = execute_tool(spec["tool_name"], {spec["records_argument"]: records})
assert result["ok"] is True
assert result["result"]["approved"] is True
assert result["result"]["decision"] == spec["approved_label"]
def test_missing_or_empty_records_fail_closed():
spec = load_spec()
result = execute_tool(spec["tool_name"], {})
assert result["ok"] is False
assert spec["records_argument"] in result["error"]
@@ -0,0 +1,19 @@
{
"tools": [
{
"type": "function",
"function": {
"name": "lookup_domain_fact",
"description": "Look up a fact in the Agent's verified domain knowledge base. Use this before answering domain-specific factual questions.",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "A concise lookup query."}
},
"required": ["query"],
"additionalProperties": false
}
}
}
]
}