xindoo/agentic-design-patterns/main 599k tokens More Tools
```
├── .github/
   ├── scripts/
      ├── pandoc-listings.tex (200 tokens)
      ├── process_latex_chars.py (400 tokens)
   ├── workflows/
      ├── generate-pdf.yml (3.3k tokens)
├── .gitignore (100 tokens)
├── AGENTS.md (1300 tokens)
├── CLAUDE.md
├── CNAME
├── CONTRIBUTING.md (600 tokens)
├── Gemfile (100 tokens)
├── OPTIMIZE_README.md (300 tokens)
├── PROJECT_STRUCTURE.md (400 tokens)
├── README.md (1300 tokens)
├── SUMMARY.md (1000 tokens)
├── _config.yml (200 tokens)
├── _includes/
   ├── navigation-bilingual.html (800 tokens)
   ├── navigation-en.html (900 tokens)
   ├── navigation.html (800 tokens)
├── _layouts/
   ├── bilingual.html (200 tokens)
   ├── default.html (3.7k tokens)
├── bilingual/
   ├── Agentic Design Patterns.md (2.4k tokens)
   ├── Appendix A_ Advanced Prompting Techniques.md (15.3k tokens)
   ├── Appendix B - AI Agentic Interactions_ From GUI to Real world environment.md (4.2k tokens)
   ├── Appendix C - Quick overview of Agentic Frameworks.md (3.9k tokens)
   ├── Appendix D - Building an Agent with AgentSpace (on-line only).md (1300 tokens)
   ├── Appendix E - AI Agents on the CLI.md (3k tokens)
   ├── Appendix F  - Under the Hood_ An Inside Look at the Agents' Reasoning Engines.md (7.1k tokens)
   ├── Appendix G -  Coding agents.md (3.6k tokens)
   ├── Chapter 10_ Model Context Protocol (MCP).md (8.1k tokens)
   ├── Chapter 11_ Goal Setting and Monitoring.md (4.8k tokens)
   ├── Chapter 12_ Exception Handling and Recovery.md (3.5k tokens)
   ├── Chapter 13_ Human-in-the-Loop.md (4.7k tokens)
   ├── Chapter 14_ Knowledge Retrieval (RAG).md (8.3k tokens)
   ├── Chapter 15_ Inter-Agent Communication (A2A).md (6.4k tokens)
   ├── Chapter 16_ Resource-Aware Optimization.md (6.7k tokens)
   ├── Chapter 17_ Reasoning Techniques.md (11.2k tokens)
   ├── Chapter 18_ Guardrails_Safety Patterns.md (9.4k tokens)
   ├── Chapter 19_ Evaluation and Monitoring.md (8.8k tokens)
   ├── Chapter 1_ Prompt Chaining.md (7k tokens)
   ├── Chapter 20_ Prioritization.md (4.2k tokens)
   ├── Chapter 21_ Exploration and Discovery.md (6.9k tokens)
   ├── Chapter 2_ Routing.md (6.3k tokens)
   ├── Chapter 3_ Parallelization.md (6.4k tokens)
   ├── Chapter 4_ Reflection.md (5.9k tokens)
   ├── Chapter 5_ Tool Use.md (9.1k tokens)
   ├── Chapter 6_ Planning.md (5.3k tokens)
   ├── Chapter 7_ Multi-Agent Collaboration.md (7.6k tokens)
   ├── Chapter 8_ Memory Management.md (9.6k tokens)
   ├── Chapter 9_ Learning and Adaptation.md (6k tokens)
   ├── Conclusion.md (3.2k tokens)
   ├── Frequently Asked Questions_ Agentic Design Patterns.md (4.3k tokens)
   ├── Glossary.md (2.3k tokens)
   ├── Index of Terms.md (8k tokens)
   ├── index.md (2.4k tokens)
├── chapters/
   ├── Agentic Design Patterns.md (500 tokens)
   ├── Appendix A_ Advanced Prompting Techniques.md (4k tokens)
   ├── Appendix B - AI Agentic Interactions_ From GUI to Real world environment.md (1200 tokens)
   ├── Appendix C - Quick overview of Agentic Frameworks.md (1400 tokens)
   ├── Appendix D - Building an Agent with AgentSpace (on-line only).md (400 tokens)
   ├── Appendix E - AI Agents on the CLI.md (900 tokens)
   ├── Appendix F  - Under the Hood_ An Inside Look at the Agents' Reasoning Engines.md (1800 tokens)
   ├── Appendix G -  Coding agents.md (1000 tokens)
   ├── Chapter 10_ Model Context Protocol (MCP).md (2.7k tokens)
   ├── Chapter 11_ Goal Setting and Monitoring.md (1900 tokens)
   ├── Chapter 12_ Exception Handling and Recovery.md (1000 tokens)
   ├── Chapter 13_ Human-in-the-Loop.md (1400 tokens)
   ├── Chapter 14_ Knowledge Retrieval (RAG).md (2.8k tokens)
   ├── Chapter 15_ Inter-Agent Communication (A2A).md (2.6k tokens)
   ├── Chapter 16_ Resource-Aware Optimization.md (2.7k tokens)
   ├── Chapter 17_ Reasoning Techniques.md (4.2k tokens)
   ├── Chapter 18_ Guardrails_Safety Patterns.md (3.7k tokens)
   ├── Chapter 19_ Evaluation and Monitoring.md (3k tokens)
   ├── Chapter 1_ Prompt Chaining.md (2k tokens)
   ├── Chapter 20_ Prioritization.md (1900 tokens)
   ├── Chapter 21_ Exploration and Discovery.md (2.3k tokens)
   ├── Chapter 2_ Routing.md (2.5k tokens)
   ├── Chapter 3_ Parallelization.md (2.2k tokens)
   ├── Chapter 4_ Reflection.md (2000 tokens)
   ├── Chapter 5_ Tool Use.md (4.1k tokens)
   ├── Chapter 6_ Planning.md (1800 tokens)
   ├── Chapter 7_ Multi-Agent Collaboration.md (2.9k tokens)
   ├── Chapter 8_ Memory Management.md (3.8k tokens)
   ├── Chapter 9_ Learning and Adaptation.md (1700 tokens)
   ├── Conclusion.md (700 tokens)
   ├── Frequently Asked Questions_ Agentic Design Patterns.md (1000 tokens)
   ├── Glossary.md (600 tokens)
   ├── Index of Terms.md (3.4k tokens)
   ├── README.md (100 tokens)
├── glossary.md (1100 tokens)
├── images/
   ├── README.md (100 tokens)
   ├── appendix-a/
      ├── image1.png
   ├── appendix-b/
      ├── image1.png
   ├── appendix-d/
      ├── image1.png
      ├── image2.png
      ├── image3.png
      ├── image4.png
      ├── image5.png
      ├── image6.png
   ├── appendix-g/
      ├── image1.png
   ├── chapter-1/
      ├── image1.png
      ├── image2.png
   ├── chapter-10/
      ├── image1.png
   ├── chapter-11/
      ├── image1.png
      ├── image2.png
   ├── chapter-12/
      ├── image1.png
      ├── image2.png
   ├── chapter-13/
      ├── image1.png
   ├── chapter-14/
      ├── image1.png
      ├── image2.png
      ├── image3.png
      ├── image4.png
   ├── chapter-15/
      ├── image1.png
      ├── image2.png
   ├── chapter-16/
      ├── image1.png
      ├── image2.png
   ├── chapter-17/
      ├── image1.png
      ├── image2.png
      ├── image3.png
      ├── image4.png
      ├── image5.png
      ├── image6.png
      ├── image7.png
   ├── chapter-18/
      ├── image1.png
   ├── chapter-19/
      ├── image1.png
      ├── image2.png
      ├── image3.png
      ├── image4.png
   ├── chapter-2/
      ├── image1.png
   ├── chapter-20/
      ├── image1.png
   ├── chapter-21/
      ├── image1.png
      ├── image2.png
   ├── chapter-3/
      ├── image1.png
      ├── image2.png
   ├── chapter-4/
      ├── image1.png
      ├── image2.png
   ├── chapter-5/
      ├── image1.png
      ├── image2.png
   ├── chapter-6/
      ├── image1.png
      ├── image2.png
      ├── image3.png
      ├── image4.png
   ├── chapter-7/
      ├── image1.png
      ├── image2.png
      ├── image3.png
   ├── chapter-8/
      ├── image1.png
   ├── chapter-9/
      ├── image1.png
      ├── image2.png
      ├── image3.png
      ├── image4.png
   ├── cover.png
├── original/
   ├── Agentic Design Patterns.md (1900 tokens)
   ├── Appendix A_ Advanced Prompting Techniques.md (12.2k tokens)
   ├── Appendix B - AI Agentic Interactions_ From GUI to Real world environment.md (3.3k tokens)
   ├── Appendix C - Quick overview of Agentic Frameworks.md (3.1k tokens)
   ├── Appendix D - Building an Agent with AgentSpace (on-line only).md (1000 tokens)
   ├── Appendix E - AI Agents on the CLI.md (2.2k tokens)
   ├── Appendix F  - Under the Hood_ An Inside Look at the Agents' Reasoning Engines.md (5.4k tokens)
   ├── Appendix G -  Coding agents.md (2.7k tokens)
   ├── Chapter 10_ Model Context Protocol (MCP).md (6.2k tokens)
   ├── Chapter 11_ Goal Setting and Monitoring.md (4.1k tokens)
   ├── Chapter 12_ Exception Handling and Recovery.md (2.8k tokens)
   ├── Chapter 13_ Human-in-the-Loop.md (3.8k tokens)
   ├── Chapter 14_ Knowledge Retrieval (RAG).md (6.5k tokens)
   ├── Chapter 15_ Inter-Agent Communication (A2A).md (5.1k tokens)
   ├── Chapter 16_ Resource-Aware Optimization.md (5.6k tokens)
   ├── Chapter 17_ Reasoning Techniques.md (9.1k tokens)
   ├── Chapter 18_ Guardrails_Safety Patterns.md (8k tokens)
   ├── Chapter 19_ Evaluation and Monitoring.md (7.1k tokens)
   ├── Chapter 1_ Prompt Chaining.md (5.5k tokens)
   ├── Chapter 20_ Prioritization.md (3.7k tokens)
   ├── Chapter 21_ Exploration and Discovery.md (5.5k tokens)
   ├── Chapter 2_ Routing.md (5.3k tokens)
   ├── Chapter 3_ Parallelization.md (5.2k tokens)
   ├── Chapter 4_ Reflection.md (4.8k tokens)
   ├── Chapter 5_ Tool Use.md (7.6k tokens)
   ├── Chapter 6_ Planning.md (4.3k tokens)
   ├── Chapter 7_ Multi-Agent Collaboration.md (6.3k tokens)
   ├── Chapter 8_ Memory Management.md (7.9k tokens)
   ├── Chapter 9_ Learning and Adaptation.md (4.7k tokens)
   ├── Conclusion.md (2.5k tokens)
   ├── Glossary.md (1600 tokens)
   ├── Index of Terms.md (6.2k tokens)
   ├── Online contribution - Frequently Asked Questions_ Agentic Design Patterns.md (3.3k tokens)
   ├── README.md (1200 tokens)
├── progress.md (600 tokens)
├── translation-guide.md (200 tokens)
```


## /.github/scripts/pandoc-listings.tex

```tex path="/.github/scripts/pandoc-listings.tex" 
\usepackage{listings}
\usepackage{xcolor}
\usepackage{calc}

\definecolor{codebg}{RGB}{248,248,248}
\definecolor{framecolor}{RGB}{221,221,221}

% Fix for Dimension too large error - reset maxwidth before each listing
\makeatletter
\let\original@lsthk@InitVarsEOL\lsthk@InitVarsEOL
\def\lsthk@InitVarsEOL{%
  \global\lst@maxwidth=0pt
  \original@lsthk@InitVarsEOL
}
\makeatother

\lstset{
  breaklines=true,
  breakatwhitespace=false,
  breakindent=0pt,
  breakautoindent=true,
  % Set safe linewidth using calc package
  linewidth=\linewidth-20pt,
  columns=fullflexible,
  keepspaces=true,
  showstringspaces=false,
  upquote=true,
  backgroundcolor=\color{codebg},
  frame=single,
  rulecolor=\color{framecolor},
  framesep=5pt,
  framerule=0.5pt,
  basicstyle=\ttfamily\footnotesize,
  keywordstyle=\color{blue},
  commentstyle=\color{gray},
  stringstyle=\color{orange},
  numbers=left,
  numberstyle=\tiny\color{gray},
  stepnumber=1,
  numbersep=8pt,
  captionpos=b,
  aboveskip=10pt,
  belowskip=10pt,
  xleftmargin=10pt,
  xrightmargin=10pt,
  % Add line continuation marker
  postbreak=\mbox{\textcolor{gray}{$\hookrightarrow$}\space}
}

```

## /.github/scripts/process_latex_chars.py

```py path="/.github/scripts/process_latex_chars.py" 
#!/usr/bin/env python3
"""
处理 Markdown 文件中的 LaTeX 特殊字符
在非代码块区域转义特殊字符,保持代码块内容不变
"""
import sys


def escape_outside_code_blocks(text):
    """
    在非代码块部分转义 LaTeX 特殊字符
    """
    # 分割文本为代码块和非代码块部分
    parts = []
    in_code_block = False
    lines = text.split('\n')
    current_block = []
    
    for line in lines:
        if line.strip().startswith('\`\`\`'):
            if current_block:
                parts.append((in_code_block, '\n'.join(current_block)))
                current_block = []
            in_code_block = not in_code_block
            current_block.append(line)
        else:
            current_block.append(line)
    
    if current_block:
        parts.append((in_code_block, '\n'.join(current_block)))
    
    # 在非代码块部分转义特殊字符
    result = []
    for is_code, block in parts:
        if not is_code:
            # 转义 LaTeX 特殊字符
            block = block.replace('\\', '\\textbackslash{}')
            block = block.replace('_', '\\_')
            block = block.replace('{', '\\{')
            block = block.replace('}', '\\}')
            block = block.replace('%', '\\%')
            block = block.replace('&', '\\&')
            block = block.replace('#', '\\#')
        result.append(block)
    
    return '\n'.join(result)


def main():
    if len(sys.argv) != 2:
        print("Usage: process_latex_chars.py <markdown_file>")
        sys.exit(1)
    
    input_file = sys.argv[1]
    
    # 读取文件
    with open(input_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 处理内容
    processed = escape_outside_code_blocks(content)
    
    # 写回文件
    with open(input_file, 'w', encoding='utf-8') as f:
        f.write(processed)
    
    print(f"Successfully processed {input_file}")


if __name__ == '__main__':
    main()
```

## /.github/workflows/generate-pdf.yml

```yml path="/.github/workflows/generate-pdf.yml" 
name: Generate PDF and EPUB

on:
  push:
    branches:
      - main
    paths:
      - 'chapters/**'
      - 'original/**'
      - 'bilingual/**'
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    
    steps:
    - name: Checkout repository
      uses: actions/checkout@v4

    - name: Install dependencies
      run: |
        sudo apt-get update
        sudo apt-get install -y wget texlive-xetex texlive-fonts-recommended texlive-lang-chinese fonts-noto-cjk

    - name: Install Pandoc
      run: |
        wget https://github.com/jgm/pandoc/releases/download/3.2/pandoc-3.2-1-amd64.deb
        sudo dpkg -i pandoc-3.2-1-amd64.deb

    # Chinese version generation
    - name: Concatenate Markdown files (Chinese)
      run: |
        cd chapters
        cat > ../combined.md << 'EOF'
        ---
        title: "智能体设计模式"
        subtitle: "构建智能系统实战指南"
        author: "Antonio Gulli"
        translator: "xindoo"
        publisher: "GitHub: https://github.com/xindoo/agentic-design-patterns"
        documentclass: book
        lang: zh-CN
        CJKmainfont: "Noto Sans CJK SC"
        geometry: "margin=1in"
        ---
        
        EOF
        
        process_and_append() {
          local file="$1"
          local prefix="$2"
          sed -e 's|\.\./images/|images/|g' \
              -e "s/^\[image\([0-9]*\)\]:/[${prefix}_image\1]:/" \
              -e "s/!\[\]\[image\([0-9]*\)\]/![][${prefix}_image\1]/g" "$file" >> ../combined.md
          echo -e "\n\n" >> ../combined.md
        }
        
        process_and_append "Chapter 1_ Prompt Chaining.md" "ch1"
        process_and_append "Chapter 2_ Routing.md" "ch2"
        process_and_append "Chapter 3_ Parallelization.md" "ch3"
        process_and_append "Chapter 4_ Reflection.md" "ch4"
        process_and_append "Chapter 5_ Tool Use.md" "ch5"
        process_and_append "Chapter 6_ Planning.md" "ch6"
        process_and_append "Chapter 7_ Multi-Agent Collaboration.md" "ch7"
        process_and_append "Chapter 8_ Memory Management.md" "ch8"
        process_and_append "Chapter 9_ Learning and Adaptation.md" "ch9"
        process_and_append "Chapter 10_ Model Context Protocol (MCP).md" "ch10"
        process_and_append "Chapter 11_ Goal Setting and Monitoring.md" "ch11"
        process_and_append "Chapter 12_ Exception Handling and Recovery.md" "ch12"
        process_and_append "Chapter 13_ Human-in-the-Loop.md" "ch13"
        process_and_append "Chapter 14_ Knowledge Retrieval (RAG).md" "ch14"
        process_and_append "Chapter 15_ Inter-Agent Communication (A2A).md" "ch15"
        process_and_append "Chapter 16_ Resource-Aware Optimization.md" "ch16"
        process_and_append "Chapter 17_ Reasoning Techniques.md" "ch17"
        process_and_append "Chapter 18_ Guardrails_Safety Patterns.md" "ch18"
        process_and_append "Chapter 19_ Evaluation and Monitoring.md" "ch19"
        process_and_append "Chapter 20_ Prioritization.md" "ch20"
        process_and_append "Chapter 21_ Exploration and Discovery.md" "ch21"
        process_and_append "Appendix A_ Advanced Prompting Techniques.md" "appa"
        process_and_append "Appendix B - AI Agentic Interactions_ From GUI to Real world environment.md" "appb"
        process_and_append "Appendix C - Quick overview of Agentic Frameworks.md" "appc"
        process_and_append "Appendix D - Building an Agent with AgentSpace (on-line only).md" "appd"
        process_and_append "Appendix E - AI Agents on the CLI.md" "appe"
        process_and_append "Appendix F  - Under the Hood_ An Inside Look at the Agents' Reasoning Engines.md" "appf"
        process_and_append "Appendix G -  Coding agents.md" "appg"
        process_and_append "Conclusion.md" "conclusion"
        process_and_append "Glossary.md" "glossary"
        process_and_append "Index of Terms.md" "index"
        process_and_append "Frequently Asked Questions_ Agentic Design Patterns.md" "faq"

    - name: Generate PDF (Chinese)
      run: |
        pandoc combined.md \
          -o agentic-design-patterns-chinese.pdf \
          --pdf-engine=xelatex \
          --toc \
          --toc-depth=2 \
          -V mainfont="Noto Sans CJK SC" \
          -V geometry:margin=1in \
          -V hyperrefoptions:linktoc=all \
          --listings \
          -H .github/scripts/pandoc-listings.tex \
          --metadata title="智能体设计模式" \
          --metadata author="Antonio Gulli" \
          --metadata translator="xindoo" \
          --metadata publisher="GitHub: https://github.com/xindoo/agentic-design-patterns" \
          --metadata lang=zh-CN

    - name: Generate EPUB (Chinese)
      run: |
        pandoc combined.md \
          -o agentic-design-patterns-chinese.epub \
          --toc \
          --toc-depth=2 \
          --split-level=1 \
          --metadata title="智能体设计模式" \
          --metadata author="Antonio Gulli" \
          --metadata translator="xindoo" \
          --metadata publisher="GitHub: https://github.com/xindoo/agentic-design-patterns" \
          --metadata lang=zh-CN \
          --epub-cover-image=images/cover.png

    - name: Upload PDF artifact (Chinese)
      uses: actions/upload-artifact@v4
      with:
        name: agentic-design-patterns-chinese-pdf
        path: agentic-design-patterns-chinese.pdf

    - name: Upload EPUB artifact (Chinese)
      uses: actions/upload-artifact@v4
      with:
        name: agentic-design-patterns-chinese-epub
        path: agentic-design-patterns-chinese.epub

    # English version generation
    - name: Concatenate Markdown files (English)
      run: |
        cd original
        cat > ../combined-en.md << 'EOF'
        ---
        title: "Agentic Design Patterns"
        subtitle: "A Practical Guide to Building Intelligent Systems"
        author: "Antonio Gulli"
        publisher: "GitHub: https://github.com/xindoo/agentic-design-patterns"
        documentclass: book
        lang: en-US
        geometry: "margin=1in"
        ---
        
        EOF
        
        process_and_append() {
          local file="$1"
          local prefix="$2"
          sed -e 's|\.\./images/|images/|g' \
              -e "s/^\[image\([0-9]*\)\]:/[${prefix}_image\1]:/" \
              -e "s/!\[\]\[image\([0-9]*\)\]/![][${prefix}_image\1]/g" "$file" >> ../combined-en.md
          echo -e "\n\n" >> ../combined-en.md
        }
        
        process_and_append "Chapter 1_ Prompt Chaining.md" "en_ch1"
        process_and_append "Chapter 2_ Routing.md" "en_ch2"
        process_and_append "Chapter 3_ Parallelization.md" "en_ch3"
        process_and_append "Chapter 4_ Reflection.md" "en_ch4"
        process_and_append "Chapter 5_ Tool Use.md" "en_ch5"
        process_and_append "Chapter 6_ Planning.md" "en_ch6"
        process_and_append "Chapter 7_ Multi-Agent Collaboration.md" "en_ch7"
        process_and_append "Chapter 8_ Memory Management.md" "en_ch8"
        process_and_append "Chapter 9_ Learning and Adaptation.md" "en_ch9"
        process_and_append "Chapter 10_ Model Context Protocol (MCP).md" "en_ch10"
        process_and_append "Chapter 11_ Goal Setting and Monitoring.md" "en_ch11"
        process_and_append "Chapter 12_ Exception Handling and Recovery.md" "en_ch12"
        process_and_append "Chapter 13_ Human-in-the-Loop.md" "en_ch13"
        process_and_append "Chapter 14_ Knowledge Retrieval (RAG).md" "en_ch14"
        process_and_append "Chapter 15_ Inter-Agent Communication (A2A).md" "en_ch15"
        process_and_append "Chapter 16_ Resource-Aware Optimization.md" "en_ch16"
        process_and_append "Chapter 17_ Reasoning Techniques.md" "en_ch17"
        process_and_append "Chapter 18_ Guardrails_Safety Patterns.md" "en_ch18"
        process_and_append "Chapter 19_ Evaluation and Monitoring.md" "en_ch19"
        process_and_append "Chapter 20_ Prioritization.md" "en_ch20"
        process_and_append "Chapter 21_ Exploration and Discovery.md" "en_ch21"
        process_and_append "Appendix A_ Advanced Prompting Techniques.md" "en_appa"
        process_and_append "Appendix B - AI Agentic Interactions_ From GUI to Real world environment.md" "en_appb"
        process_and_append "Appendix C - Quick overview of Agentic Frameworks.md" "en_appc"
        process_and_append "Appendix D - Building an Agent with AgentSpace (on-line only).md" "en_appd"
        process_and_append "Appendix E - AI Agents on the CLI.md" "en_appe"
        process_and_append "Appendix F  - Under the Hood_ An Inside Look at the Agents' Reasoning Engines.md" "en_appf"
        process_and_append "Appendix G -  Coding agents.md" "en_appg"
        process_and_append "Conclusion.md" "en_conclusion"
        process_and_append "Glossary.md" "en_glossary"
        process_and_append "Index of Terms.md" "en_index"
        process_and_append "Online contribution - Frequently Asked Questions_ Agentic Design Patterns.md" "en_faq"

    - name: Generate PDF (English)
      run: |
        pandoc combined-en.md \
          -o agentic-design-patterns-en.pdf \
          --pdf-engine=xelatex \
          --toc \
          --toc-depth=2 \
          -V mainfont="DejaVu Serif" \
          -V geometry:margin=1in \
          -V hyperrefoptions:linktoc=all \
          --listings \
          -H .github/scripts/pandoc-listings.tex \
          --metadata title="Agentic Design Patterns" \
          --metadata author="Antonio Gulli" \
          --metadata publisher="GitHub: https://github.com/xindoo/agentic-design-patterns" \
          --metadata lang=en-US

    - name: Generate EPUB (English)
      run: |
        pandoc combined-en.md \
          -o agentic-design-patterns-en.epub \
          --toc \
          --toc-depth=2 \
          --split-level=1 \
          --metadata title="Agentic Design Patterns" \
          --metadata author="Antonio Gulli" \
          --metadata publisher="GitHub: https://github.com/xindoo/agentic-design-patterns" \
          --metadata lang=en-US \
          --epub-cover-image=images/cover.png

    - name: Upload PDF artifact (English)
      uses: actions/upload-artifact@v4
      with:
        name: agentic-design-patterns-en-pdf
        path: agentic-design-patterns-en.pdf

    - name: Upload EPUB artifact (English)
      uses: actions/upload-artifact@v4
      with:
        name: agentic-design-patterns-en-epub
        path: agentic-design-patterns-en.epub

    # Bilingual version generation
    - name: Concatenate Markdown files (Bilingual)
      run: |
        cd bilingual
        cat > ../combined-bilingual.md << 'EOF'
        ---
        title: "智能体设计模式 (双语版)"
        subtitle: "Agentic Design Patterns (Bilingual Edition)"
        author: "Antonio Gulli"
        translator: "xindoo"
        publisher: "GitHub: https://github.com/xindoo/agentic-design-patterns"
        documentclass: book
        lang: zh-CN
        CJKmainfont: "Noto Sans CJK SC"
        geometry: "margin=1in"
        ---
        
        EOF
        
        process_and_append() {
          local file="$1"
          local prefix="$2"
          sed -e 's|\.\./images/|images/|g' \
              -e "s/^\[image\([0-9]*\)\]:/[${prefix}_image\1]:/" \
              -e "s/!\[\]\[image\([0-9]*\)\]/![][${prefix}_image\1]/g" "$file" >> ../combined-bilingual.md
          echo -e "\n\n" >> ../combined-bilingual.md
        }
        
        process_and_append "Chapter 1_ Prompt Chaining.md" "bi_ch1"
        process_and_append "Chapter 2_ Routing.md" "bi_ch2"
        process_and_append "Chapter 3_ Parallelization.md" "bi_ch3"
        process_and_append "Chapter 4_ Reflection.md" "bi_ch4"
        process_and_append "Chapter 5_ Tool Use.md" "bi_ch5"
        process_and_append "Chapter 6_ Planning.md" "bi_ch6"
        process_and_append "Chapter 7_ Multi-Agent Collaboration.md" "bi_ch7"
        process_and_append "Chapter 8_ Memory Management.md" "bi_ch8"
        process_and_append "Chapter 9_ Learning and Adaptation.md" "bi_ch9"
        process_and_append "Chapter 10_ Model Context Protocol (MCP).md" "bi_ch10"
        process_and_append "Chapter 11_ Goal Setting and Monitoring.md" "bi_ch11"
        process_and_append "Chapter 12_ Exception Handling and Recovery.md" "bi_ch12"
        process_and_append "Chapter 13_ Human-in-the-Loop.md" "bi_ch13"
        process_and_append "Chapter 14_ Knowledge Retrieval (RAG).md" "bi_ch14"
        process_and_append "Chapter 15_ Inter-Agent Communication (A2A).md" "bi_ch15"
        process_and_append "Chapter 16_ Resource-Aware Optimization.md" "bi_ch16"
        process_and_append "Chapter 17_ Reasoning Techniques.md" "bi_ch17"
        process_and_append "Chapter 18_ Guardrails_Safety Patterns.md" "bi_ch18"
        process_and_append "Chapter 19_ Evaluation and Monitoring.md" "bi_ch19"
        process_and_append "Chapter 20_ Prioritization.md" "bi_ch20"
        process_and_append "Chapter 21_ Exploration and Discovery.md" "bi_ch21"
        process_and_append "Appendix A_ Advanced Prompting Techniques.md" "bi_appa"
        process_and_append "Appendix B - AI Agentic Interactions_ From GUI to Real world environment.md" "bi_appb"
        process_and_append "Appendix C - Quick overview of Agentic Frameworks.md" "bi_appc"
        process_and_append "Appendix D - Building an Agent with AgentSpace (on-line only).md" "bi_appd"
        process_and_append "Appendix E - AI Agents on the CLI.md" "bi_appe"
        process_and_append "Appendix F  - Under the Hood_ An Inside Look at the Agents' Reasoning Engines.md" "bi_appf"
        process_and_append "Appendix G -  Coding agents.md" "bi_appg"
        process_and_append "Conclusion.md" "bi_conclusion"
        process_and_append "Glossary.md" "bi_glossary"
        process_and_append "Index of Terms.md" "bi_index"
        process_and_append "Frequently Asked Questions_ Agentic Design Patterns.md" "bi_faq"
        process_and_append "Glossary.md" "bi_glossary"
        process_and_append "Index of Terms.md" "bi_index"
        process_and_append "Frequently Asked Questions_ Agentic Design Patterns.md" "bi_faq"

    - name: Generate PDF (Bilingual)
      run: |
        pandoc combined-bilingual.md \
          -o agentic-design-patterns-bilingual.pdf \
          --pdf-engine=xelatex \
          --toc \
          --toc-depth=2 \
          -V mainfont="Noto Sans CJK SC" \
          -V geometry:margin=1in \
          -V hyperrefoptions:linktoc=all \
          --listings \
          -H .github/scripts/pandoc-listings.tex \
          --metadata title="智能体设计模式 (双语版)" \
          --metadata author="Antonio Gulli" \
          --metadata translator="xindoo" \
          --metadata publisher="GitHub: https://github.com/xindoo/agentic-design-patterns" \
          --metadata lang=zh-CN

    - name: Generate EPUB (Bilingual)
      run: |
        pandoc combined-bilingual.md \
          -o agentic-design-patterns-bilingual.epub \
          --toc \
          --toc-depth=2 \
          --split-level=1 \
          --metadata title="智能体设计模式 (双语版)" \
          --metadata author="Antonio Gulli" \
          --metadata translator="xindoo" \
          --metadata publisher="GitHub: https://github.com/xindoo/agentic-design-patterns" \
          --metadata lang=zh-CN \
          --epub-cover-image=images/cover.png

    - name: Upload PDF artifact (Bilingual)
      uses: actions/upload-artifact@v4
      with:
        name: agentic-design-patterns-bilingual-pdf
        path: agentic-design-patterns-bilingual.pdf

    - name: Upload EPUB artifact (Bilingual)
      uses: actions/upload-artifact@v4
      with:
        name: agentic-design-patterns-bilingual-epub
        path: agentic-design-patterns-bilingual.epub

    - name: Create Release
      if: github.event_name == 'push' && github.ref == 'refs/heads/main'
      uses: softprops/action-gh-release@v1
      with:
        tag_name: v${{ github.run_number }}
        name: Release v${{ github.run_number }}
        files: |
          agentic-design-patterns-chinese.pdf
          agentic-design-patterns-chinese.epub
          agentic-design-patterns-en.pdf
          agentic-design-patterns-en.epub
          agentic-design-patterns-bilingual.pdf
          agentic-design-patterns-bilingual.epub
        draft: false
        prerelease: false
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
```

## /.gitignore

```gitignore path="/.gitignore" 
# Jekyll
_site/
.sass-cache/
.jekyll-cache/
.jekyll-metadata
Gemfile.lock

# Ruby
*.gem
*.rbc
.bundle
.config
coverage
InstalledFiles
lib/bundler/man
pkg
rdoc
spec/reports
test/tmp
test/version_tmp
tmp

# macOS
.DS_Store
.AppleDouble
.LSOverride

# Windows
Thumbs.db
ehthumbs.db
Desktop.ini

# Editor
.vscode/
.idea/
*.swp
*.swo
*~

# Temporary files
*.tmp
*.temp
*.log

# Build output (如果需要生成 HTML 或 PDF)
build/
dist/
output/

# Node modules (如果使用 gitbook 等工具)
node_modules/
package-lock.json

# Python (如果使用 mkdocs 等工具)
__pycache__/
*.py[cod]
venv/
.env
.workspace

```

## /AGENTS.md

# Agentic Design Patterns - 智能体操作指南

本文档为运行在本代码库的AI编码/翻译智能体提供操作规范。

---

## 1. 项目概述

本项目是《Agentic Design Patterns》一书的中文翻译项目,是AI Agent系统设计模式的权威指南。

- **代码仓库**: https://github.com/xindoo/agentic-design-patterns
- **在线站点**: https://adp.xindoo.xyz/
- **技术栈**: Jekyll (GitHub Pages)、Markdown、Ruby
- **核心任务**: 翻译质量优化、内容更新、站点维护

---

## 2. 构建/检查/运行命令

### 环境要求

- 已安装 Ruby 2.7+ 和 Bundler
- 已安装 Node.js (用于代码检查工具)

### 依赖安装

```bash
# 安装Ruby依赖
bundle install

# 安装Node.js代码检查工具(可选,用于质量检查)
npm install -g markdownlint-cli markdown-link-check
```

### 构建与本地运行

```bash
# 构建静态站点到 _site/ 目录
bundle exec jekyll build

# 本地启动服务,支持热重载,访问地址:http://localhost:4000
bundle exec jekyll serve --livereload

# 生产环境构建(与GitHub Pages部署逻辑一致)
JEKYLL_ENV=production bundle exec jekyll build
```

### 代码检查与质量校验

```bash
# 检查所有Markdown文件的格式问题
npx markdownlint-cli chapters/

# 检查指定章节的无效链接
npx markdown-link-check chapters/[章节文件名].md

# 检查特定术语的翻译一致性
grep -r "术语原文" chapters/

# 验证Jekyll配置有效性
bundle exec jekyll doctor
```

### 测试要求

本内容类项目无自动化单元测试,所有修改必须通过:

1. Markdown语法检查无错误
2. 本地构建成功无Jekyll错误
3. 链接检查无无效内部链接
4. 翻译内容人工审核通过

---

## 3. 代码与内容风格规范

### Markdown格式规范

- **标题层级**: 严格保留原文的标题层级结构(# 一级标题、## 二级标题、### 三级标题,以此类推)
- **换行规则**: 段落之间使用1个空行分隔,行尾无多余空格
- **列表格式**: 嵌套列表保留原有缩进,无序列表使用 `-`,有序列表使用 `1.`
- **代码块**: 反引号后必须指定语言标识:
  ```python
  # 示例:带语言标识的代码块
  def example():
      return "value"
  ```
- **行内代码**: 变量名、函数名、命令行输入使用单反引号包裹
- **表格格式**: 保持Markdown表格对齐,表头翻译为中文,内容对齐方式与原文一致

### 翻译标准

#### 准确性优先

- 完整保留所有技术含义,无明确理由不得遗漏或新增内容
- 对技术术语翻译不确定时,添加译者注:`[译者注: 此处XXX术语翻译存疑,原文为XXX]`
- 技术概念使用行业标准译法,避免字面直译

#### 术语一致性

- **强制要求**: 所有术语翻译必须同时参考 `glossary.md` 和 `Index of Terms.md` 中的统一译法
- 新术语首次出现时需标注英文原文:`中文译名(English Original)`
- 后续出现统一使用中文译名即可
- 禁止为已有标准译法的技术术语自创翻译
- **重要原则**: 不要轻易批量替换关键词,必须根据上下文判断是否修改。例如:"代理"可能是技术术语 proxy,"流水线"可能是计算机科学通用术语,"提示链"在某些语境下可能不需要改为"提示词链"。在进行任何替换前,必须先读取文件查看具体上下文。
- **章节固定标题译法**:
  | 原文 | 推荐译文 |  
  |---|---|  
  | At a Glance | 速览 |  
  | What | 问题背景 |  
  | Why | 解决方案 |  
  | Rule of Thumb | 实践建议 |

#### 语言风格

- 使用自然流畅的中文表达,避免直译英文句式
- 保持技术文档的专业、简洁语气
- 全书翻译风格统一,与已翻译章节保持一致
- 标点符号:中文内容使用中文标点,代码和英文术语使用英文标点

### 命名规范

- **文件名**: 章节文件名保留原文英文:`Chapter X_ [Original Name].md`
- **图片路径**: 使用 `![中文描述](../images/chapter-XX/[original-image-filename].png)` 格式
- **分支名**: 新贡献使用 `feature/[任务描述]` 格式,例如 `feature/translate-chapter-5`、`feature/fix-chapter-3-typos`
- **提交信息**: 使用清晰的中文描述:`完成第X章翻译`、`修复第Y章术语错误`、`更新Z章节内容`

### 错误处理

- 遇到无效链接时,修复为正确的内部路径
- 遇到缺失图片时,通知维护者,不得直接删除图片引用
- 发现翻译不一致时,对照 `glossary.md` 修正所有相关出现位置
- 禁止忽略Jekyll构建错误,提交前必须修复根本原因

### 代码与技术内容规则

- **代码片段**: 所有代码保留原文英文,不得翻译代码逻辑、变量名、函数名
- **代码注释**: 可以将代码注释翻译为中文,但代码本身保持不变
- **命令行说明**: 命令本身保留英文,说明部分翻译为中文
- **框架/技术名称**: LangChain、OpenAI、MCP、RAG等专有名词保留原文,除非有广泛接受的标准中文译法

---

## 4. 工作流规范

### 修改前检查

1. 操作前先阅读 `CONTRIBUTING.md` 和 `translation-guide.md`
2. 确认你要修改的内容没有已存在的开放拉取请求
3. 查看 `progress.md` 了解当前翻译进度

### 提交要求

- 所有修改聚焦于单个章节或任务,避免在一个PR中包含不相关的改动
- 完整填写PR模板,说明修改内容和原因
- PR提交前必须通过本地构建和代码检查
- PR描述中包含验证步骤,例如:"本地构建成功,markdownlint检查通过,第3章内容已审核"

### 禁止操作

- 不得修改 `original/` 目录下的文件(原文备份目录)
- 未经维护者明确批准,不得修改 `_config.yml` 中的Jekyll配置
- 未经过讨论不得新增依赖或插件
- 已正确翻译的内容不得随意重写,除非修复明确错误

---

## 5. 双语版本指南

### 5.1 双语版本概述

双语版本将英文原文和中文翻译交替显示,每段英文后紧跟对应的中文翻译,代码块作为整体不分割。这种格式便于读者对照阅读,提高翻译质量和学习效率。

**访问路径**:

- 中文版: `/chapters/`
- 英文版: `/original/`
- 双语版: `/bilingual/`

### 5.2 双语文件结构

```
bilingual/
├── Chapter 1_ Prompt Chaining.md
├── Chapter 2_ Routing.md
├── ...
├── Glossary.md
├── Index of Terms.md
└── index.md
```

**文件名**:与 `chapters/` 和 `original/` 目录保持一致,使用原文英文文件名,例如 `Chapter 1_ Prompt Chaining.md`。

**文件完整性**:`bilingual/` 目录必须包含与 `chapters/` 和 `original/` 相同的完整文件集合,包括所有章节、附录、术语表和索引文件。

### 5.3 双语内容格式规范

#### 基础格式规则

双语文件必须严格按照以下格式组织内容:

```markdown
# English Title

# 中文标题

## English Section Heading

## 中文章节标题

English paragraph here.

中文翻译段落。

Another English paragraph.

另一段中文翻译。

```python
# 代码块保持完整,只出现一次,放在对应英文段落之后
code_here()
```
```

#### 标题层级规范

- **一级标题**:英文标题后紧跟中文标题,各占一行
  ```markdown
  # Chapter 1: Prompt Chaining

  # 第 1 章:提示词链
  ```

- **二级及以下标题**:英文标题后紧跟中文标题,各占一行
  ```markdown
  ## Prompt Chaining Pattern Overview

  ## 提示词链模式概述
  ```

- **标题层级一致性**:严格保持与原文相同的标题层级结构,不得随意更改

#### 段落交替规范

- **逐段对照**:每个英文段落后紧跟对应的中文翻译段落
- **空行分隔**:英文段落与中文段落之间必须有一个空行
- **段落完整性**:保持原文段落结构,不要合并或拆分段落
- **列表处理**:完整的英文列表后紧跟完整的中文列表,保持列表格式一致

  示例:
  ```markdown
  * English list item 1
  * English list item 2

  * 中文列表项 1
  * 中文列表项 2
  ```

#### 代码块处理规范

- **代码块只出现一次**:代码块紧跟在对应的英文说明段落之后,中文翻译段落之前
- **代码保持原样**:代码内容、注释、格式完全保留原文
- **语言标识保留**:保留代码块的语言标识(如 `python`、`bash` 等)

  示例:
  ```markdown
  Here's a code example:

  ```python
  def example():
      return "value"
  ```

  这是一个代码示例:
  ```

#### 特殊元素处理

- **图片引用**:图片只出现一次,放在对应的英文段落之后,中文翻译之前
- **表格**:完整的英文表格后紧跟完整的中文表格,表头和内容都要翻译
- **链接**:链接只出现一次,保持原文链接地址,链接文本可以翻译或保留英文
- **引用块**:完整的英文引用块后紧跟完整的中文引用块

### 5.4 网页版双语支持

- 导航栏自动根据当前语言显示对应目录
- 语言切换按钮支持三态切换:**中文 → 英文 → 双语 → 中文**
- 上一章/下一章导航在三种版本间正常工作
- 使用 `_layouts/bilingual.html` 布局模板渲染双语页面
- 使用 `_includes/navigation-bilingual.html` 提供双语版导航

### 5.5 PDF/EPUB 生成

GitHub Workflow (`.github/workflows/generate-pdf.yml`) 会自动生成三种版本的 PDF 和 EPUB:

| 文件 | 说明 |
|------|------|
| `agentic-design-patterns-chinese.pdf` | 中文版 PDF |
| `agentic-design-patterns-chinese.epub` | 中文版 EPUB |
| `agentic-design-patterns-en.pdf` | 英文版 PDF |
| `agentic-design-patterns-en.epub` | 英文版 EPUB |
| `agentic-design-patterns-bilingual.pdf` | 双语版 PDF |
| `agentic-design-patterns-bilingual.epub` | 双语版 EPUB |

**触发条件**:push 到 main 分支,且修改了 `chapters/**`、`original/**` 或 `bilingual/**`

### 5.6 更新双语版本的流程

#### 完整更新流程

1. **更新中文翻译** → 修改 `chapters/` 目录下的对应文件
2. **更新英文原文**(如需要)→ 修改 `original/` 目录下的对应文件
3. **同步更新双语文件** → 修改 `bilingual/` 目录下的对应文件,确保格式符合 5.3 节规范
4. **提交更改** → 包含 `chapters/`、`original/`(如修改)和 `bilingual/` 的改动
5. **自动触发 Workflow** → 生成新的 PDF/EPUB

#### 双语文件同步检查清单

在提交双语文件更新前,请确认:

- [ ] 所有标题都有对应的中英文对照
- [ ] 所有段落都按英文-中文顺序交替排列
- [ ] 代码块只出现一次且位置正确
- [ ] 图片、表格、链接等特殊元素处理正确
- [ ] 文件名与 `chapters/` 和 `original/` 保持一致
- [ ] 文件完整性检查:没有遗漏任何章节或附录
- [ ] Markdown 语法检查通过
- [ ] 本地 Jekyll 构建成功

### 5.7 双语文件生成工具(如适用)

如果项目提供了自动生成双语文件的工具,请参考工具文档使用。在没有自动化工具的情况下,必须手动按照上述规范创建和维护双语文件。

---

## 7. 双语版本维护规范

### 7.1 双语文件质量标准

- **格式一致性**:严格遵守 5.3 节的格式规范
- **内容完整性**:双语文件必须包含原文的所有内容,不得遗漏
- **翻译准确性**:中文翻译必须与 `chapters/` 目录中的翻译保持一致
- **同步及时性**:`chapters/` 或 `original/` 更新后,`bilingual/` 必须同步更新
- **无冗余内容**:代码块、图片等元素只出现一次,避免重复

### 7.2 禁止操作

- 不得直接修改 `bilingual/` 目录而不同步更新 `chapters/` 目录
- 不得在双语文件中随意调整段落顺序或合并/拆分段落
- 不得删除或重复代码块、图片等特殊元素
- 不得改变原文的标题层级结构
- 不得在未完成同步的情况下提交部分更新

---

## 8. 核心资源

- `glossary.md`: 官方术语翻译对照表
- `translation-guide.md`: 详细翻译标准与最佳实践
- `CONTRIBUTING.md`: 完整贡献流程与要求
- `progress.md`: 当前翻译进度与章节状态
- `PROJECT_STRUCTURE.md`: 代码库文件结构说明


## /CLAUDE.md

AGENTS.md

## /CNAME

``` path="/CNAME" 
adp.xindoo.xyz
```

## /CONTRIBUTING.md

# 贡献指南

欢迎参与《Agentic Design Patterns》中文翻译项目!本指南将帮助您了解如何为项目做出贡献。

## 🎯 项目概览

本项目是《Agentic Design Patterns》一书的中文翻译,涵盖21个核心AI Agent设计模式及7个附录章节。所有翻译内容将通过GitHub Pages在线发布。

**在线访问**: [https://adp.xindoo.xyz/](https://adp.xindoo.xyz/)

## 📋 翻译标准

### 准确性原则
- **技术准确性**: 确保技术概念和术语的准确传达
- **语义完整性**: 不遗漏重要信息,保持原文的技术深度
- **文化适应性**: 适当本土化文化差异内容,保持技术准确性

### 语言风格
- **自然流畅**: 使用符合中文表达习惯的句式
- **专业严谨**: 保持技术文档的专业性和严谨性
- **统一风格**: 全书保持一致的翻译风格和语气

## 🔤 术语规范

### 术语统一
- **参考术语表**: 所有术语必须参考 [`glossary.md`](glossary.md) 中的统一译法
- **首次出现**: 新术语首次出现时可标注英文原文,格式:`中文译名(英文原文)`
- **一致性检查**: 提交前使用搜索功能检查术语使用的一致性

### 常见术语处理
- **代码相关**: 变量名、函数名、类名保持英文原样
- **框架名称**: LangChain、Google ADK等框架名称保持英文
- **技术概念**: Agent、Prompt、RAG等技术概念使用统一译法

## 📝 格式要求

### Markdown格式
- **标题层级**: 保持与原文一致的标题层级结构(# H1, ## H2, ### H3)
- **代码块**: 使用正确的语言标识符,保持代码格式完整
- **列表**: 有序列表和无序列表保持原有缩进结构
- **表格**: 确保表格对齐,表头使用中文

### 代码处理
```markdown
```python
# 代码注释可以翻译为中文
def example_function():
    # 函数和变量名保持英文
    return "结果"
```
```

### 图片引用
- **路径格式**: `![图片描述](../images/chapter-XX/image-name.png)`
- **图片描述**: 使用准确的中文描述
- **图片处理**: 如原图包含英文文字,需创建中文版本图片

## 🔄 工作流程

### 1. 准备工作
1. Fork本仓库到您的GitHub账户
2. 克隆仓库到本地:`git clone https://github.com/您的用户名/agentic-design-patterns.git`
3. 创建特性分支:`git checkout -b feature/translate-chapter-XX`

### 2. 认领任务
1. 查看 [`progress.md`](progress.md) 了解可认领的章节
2. 在Issues中创建新issue或评论现有issue表示认领
3. 等待维护者分配任务

### 3. 翻译过程
1. **准备原文**: 从 [`original/`](original/) 目录获取对应章节原文
2. **创建文件**: 在 [`chapters/`](chapters/) 目录创建翻译文件
3. **分段翻译**: 逐段翻译,保持原文结构
4. **处理图片**: 更新图片引用路径,确保指向正确位置
5. **自我检查**: 完成翻译后进行自我质量检查

### 4. 提交审核
1. 提交更改:`git commit -am '完成第XX章翻译'`
2. 推送分支:`git push origin feature/translate-chapter-XX`
3. 创建Pull Request
4. 在PR描述中说明:
   - 翻译的章节名称
   - 主要翻译内容概述
   - 任何需要特别注意的技术难点

### 5. 审核流程
1. **技术审核**: 至少一位技术背景的贡献者审核技术准确性
2. **语言审核**: 至少一位语言背景的贡献者审核语言质量
3. **修改完善**: 根据审核意见修改翻译
4. **合并发布**: 审核通过后合并到主分支

## ✅ 质量检查清单

在提交PR前,请确保完成以下检查:

### 技术准确性
- [ ] 技术概念翻译准确无误
- [ ] 代码示例保持原样,注释翻译正确
- [ ] 专业术语使用统一译法
- [ ] 技术细节无遗漏或误解

### 语言质量
- [ ] 语言流畅自然,符合中文表达习惯
- [ ] 无语法错误和错别字
- [ ] 标点符号使用规范
- [ ] 段落结构清晰合理

### 格式规范
- [ ] Markdown格式正确
- [ ] 标题层级结构完整
- [ ] 图片引用路径正确
- [ ] 代码块格式完整

### 一致性检查
- [ ] 术语使用与术语表一致
- [ ] 风格与已翻译章节保持一致
- [ ] 全章翻译风格统一

## 🛠️ 实用工具推荐

### 术语检查
```bash
# 检查术语一致性
grep -r "术语" chapters/ | head -10
```

### 格式验证
```bash
# 验证Markdown格式
npx markdownlint-cli chapters/
```

### 链接检查
```bash
# 检查内部链接有效性
npx markdown-link-check chapters/your-chapter.md
```

## 📚 学习资源

- [翻译指南](translation-guide.md) - 详细的翻译规范和技巧
- [术语表](glossary.md) - 统一的技术术语翻译
- [项目结构](PROJECT_STRUCTURE.md) - 项目文件组织说明
- [进度追踪](progress.md) - 实时翻译状态更新

## 🤝 社区准则

### 沟通方式
- **问题讨论**: 使用GitHub Issues进行技术讨论
- **代码审查**: 在Pull Request中进行代码审查和讨论
- **紧急联系**: 通过邮件联系维护者

### 行为准则
- **尊重他人**: 保持专业和尊重的沟通态度
- **建设性反馈**: 提供具体、建设性的反馈意见
- **共同学习**: 这是一个共同学习进步的过程

### 认可贡献
所有贡献者将在项目README中列出,重大贡献将在发布说明中特别致谢。

## 🆘 获取帮助

如果您在翻译过程中遇到困难,可以通过以下方式获取帮助:

1. **查阅文档**: 首先查看相关指南文档
2. **搜索问题**: 在Issues中搜索类似问题
3. **创建Issue**: 描述具体问题和技术难点
4. **联系维护者**: 
   - 邮箱: ixindoo@gmail.com
   - GitHub: [xindoo](https://github.com/xindoo)

## 📄 许可证说明

本翻译项目遵循原书的许可证条款。翻译内容仅供学习交流使用,请勿用于商业用途。

---

感谢您为开源社区做出的贡献!您的每一份努力都让中文技术文档更加丰富和完善。

## /Gemfile

``` path="/Gemfile" 
# Gemfile for GitHub Pages

source "https://rubygems.org"

# Jekyll 版本
gem "jekyll", "~> 3.9.0"

# GitHub Pages gem - 包含所有 GitHub Pages 支持的插件
gem "github-pages", group: :jekyll_plugins

# 其他有用的插件
group :jekyll_plugins do
  gem "jekyll-feed", "~> 0.12"
  gem "jekyll-sitemap"
  gem "jekyll-seo-tag"
  gem "jekyll-relative-links"
end

# Windows 和 JRuby 不包含 zoneinfo 文件,需要使用 tzinfo-data gem
platforms :mingw, :x64_mingw, :mswin, :jruby do
  gem "tzinfo", "~> 1.2"
  gem "tzinfo-data"
end

# Windows 性能增强
gem "wdm", "~> 0.1.1", :platforms => [:mingw, :x64_mingw, :mswin]
```

## /OPTIMIZE_README.md

# 翻译优化脚本使用说明

本目录提供两个并行优化脚本,用于批量优化章节翻译。

## 脚本对比

| 脚本 | 语言 | 依赖 | 特点 |
|------|------|------|------|
| `optimize_translations.py` | Python | Python 3.6+ | 推荐使用,无需额外依赖 |
| `optimize_translations.sh` | Bash | GNU Parallel, coreutils | 需要安装额外工具 |

## 推荐使用: Python 版本

### 快速开始

```bash
# 直接运行
./optimize_translations.py
```

### 功能特点

- 自动跳过索引、术语表等非章节文件
- 可配置的并行数 (默认 4)
- 可配置的超时时间 (默认 10 分钟)
- 实时显示处理进度
- 完成后显示成功/失败统计

### 配置修改

编辑脚本开头的配置部分:

```python
MAX_WORKERS = 4      # 最大并行任务数
TIMEOUT = 600         # 超时时间(秒)
```

### 跳过的文件

脚本默认跳过以下文件:
- Index of Terms.md
- Glossary.md
- README.md
- Agentic Design Patterns.md
- Frequently Asked Questions_ Agentic Design Patterns.md
- Conclusion.md

## Bash 版本 (备选)

### 依赖安装

```bash
# macOS
brew install parallel coreutils

# Ubuntu/Debian
sudo apt install parallel
```

### 运行

```bash
./optimize_translations.sh
```

## 使用流程

1. **确认环境**
   - 确保 `opencode` 命令可用
   - 确保在项目根目录下运行

2. **运行脚本**
   ```bash
   ./optimize_translations.py
   ```

3. **确认执行**
   - 脚本会显示将要处理的章节列表
   - 输入 `y` 确认开始

4. **等待完成**
   - 脚本会并行处理多个章节
   - 实时显示处理状态

5. **查看结果**
   - 完成后显示成功/失败统计
   - 失败的章节会列出

## 注意事项

- 每个任务默认超时时间为 10 分钟
- 建议先从较小的并行数开始测试 (2-4)
- 如遇问题,可以单独运行失败的章节
- 脚本不会修改原文件,而是通过 opencode 进行修改

## 单独处理某个章节

如果需要单独处理某个章节,可以直接运行:

```bash
opencode run "ulw 优化下 Chapter 1_ Prompt Chaining.md 章节的翻译,尤其是一些晦涩、表述不畅的部分,但不要改变原意"
```


## /PROJECT_STRUCTURE.md

# 项目结构说明

```
agentic-design-patterns/
│
├── README.md                 # 项目主说明文档
├── CONTRIBUTING.md          # 贡献指南
├── translation-guide.md     # 翻译指南
├── progress.md              # 翻译进度追踪
├── glossary.md              # 术语对照表
├── SUMMARY.md               # GitBook 目录文件
├── PROJECT_STRUCTURE.md     # 本文件 - 项目结构说明
├── .gitignore               # Git 忽略文件配置
│
├── chapters/                # 翻译后的章节目录
│   ├── README.md            # 章节目录说明
│   ├── chapter-01.md        # 第1章(待添加原文后翻译)
│   ├── chapter-02.md        # 第2章
│   ├── ...                  # 第3-24章
│   └── chapter-25.md        # 第25章
│
├── original/                # 原文备份目录
│   ├── README.md            # 原文目录说明
│   ├── chapter-01.md        # 原文第1章(待添加)
│   ├── ...                  # 其他原文章节
│   └── chapter-25.md        # 原文第25章
│
├── images/                  # 图片资源目录
│   ├── README.md            # 图片目录说明
│   ├── common/              # 公共图片资源
│   ├── chapter-1/           # 第1章图片
│   ├── chapter-2/           # 第2章图片
│   ├── ...                  # 第3-24章图片目录
│   └── chapter-25/          # 第25章图片
│
└── assets/                  # 其他资源文件目录
    └── README.md            # 资源目录说明

```

## 目录说明

### 根目录文件

- **README.md**: 项目总体介绍,包括项目简介、结构、贡献方式等
- **CONTRIBUTING.md**: 详细的贡献指南,包括翻译规范、工作流程、审核标准
- **translation-guide.md**: 翻译指南,包括翻译原则、格式规范、术语对照
- **progress.md**: 翻译进度追踪表,记录每章的翻译状态和负责人
- **glossary.md**: 术语对照表,统一专业术语的翻译
- **SUMMARY.md**: GitBook 目录文件,包含所有章节链接
- **.gitignore**: Git 版本控制忽略文件配置

### 核心目录

1. **chapters/**: 存放翻译后的中文章节
   - 每个文件对应一章内容
   - 命名格式:`chapter-XX.md`(XX 为 01-25)
   
2. **original/**: 存放英文原文
   - 便于翻译时对照参考
   - 保持与 chapters 相同的命名结构

3. **images/**: 存放所有图片资源
   - `common/`: 公共图片(logo、通用图标等)
   - `chapter-XX/`: 各章节专用图片
   
4. **assets/**: 其他资源文件
   - 可存放字体、样式、脚本等辅助文件

## 使用流程

1. **准备阶段**
   - 将原书的英文章节文件放入 `original/` 目录
   - 将原书的图片按章节分类放入对应的 `images/chapter-XX/` 目录

2. **翻译阶段**
   - 在 Issues 中认领要翻译的章节
   - 参考 `original/` 中的原文进行翻译
   - 将翻译结果保存到 `chapters/` 目录
   - 更新图片引用路径

3. **审核阶段**
   - 提交 Pull Request
   - 其他贡献者审核翻译质量
   - 根据反馈修改完善

4. **完成阶段**
   - PR 合并后更新 `progress.md`
   - 继续下一章节的翻译

## 注意事项

- 所有 Markdown 文件使用 UTF-8 编码
- 图片引用使用相对路径
- 保持目录结构清晰有序
- 及时更新进度文件

## /README.md

![封面图](images/cover.png)

# Agentic Design Patterns(中文翻译项目)

## 👨‍💻 关于xindoo

**xindoo** - 本翻译项目的发起者和主要维护者

- **GitHub**: [xindoo](https://github.com/xindoo)
- **个人网站**: [zxs.io](https://zxs.io)
- **博客**:[xindoo](https://blog.csdn.net/xindoo)
- **个人简介**: 热衷于技术分享和开源贡献的开发者,专注于 AI 技术、系统架构、职业发展。 
- **微信公众号(XIN洞察)**: 资深博主,做过运维、写过代码、现任产品经理,从命令行终端敲到产品设计稿,跨视角硬核解码新时代的XIN洞察。欢迎扫码关注。

<p align="center">
  <img src="https://raw.githubusercontent.com/xindoo/xindoo/master/img/xindoochat.jpg" width="220" alt="XIN洞察"/>
</p>

## 📚 项目简介

本项目是《Agentic Design Patterns》一书的中文翻译项目。该书系统介绍了 AI Agent 系统的各种设计模式,涵盖从基础到高级的 21 个核心模式,以及多个附录章节。

## 🎯 关于本书

《Agentic Design Patterns》探讨了构建智能 AI Agent 系统的核心设计模式,包括:
- 提示链、路由、并行化等基础模式
- 反思、工具使用、规划等进阶模式
- 多智能体协作、记忆管理、知识检索等高级模式
- 安全防护、评估监控等实践模式

## 📖 目录结构

### 核心章节

1. [第1章:提示链(Prompt Chaining)](chapters/Chapter%201_%20Prompt%20Chaining.md)
2. [第2章:路由(Routing)](chapters/Chapter%202_%20Routing.md)
3. [第3章:并行化(Parallelization)](chapters/Chapter%203_%20Parallelization.md)
4. [第4章:反思(Reflection)](chapters/Chapter%204_%20Reflection.md)
5. [第5章:工具使用(Tool Use)](chapters/Chapter%205_%20Tool%20Use.md)
6. [第6章:规划(Planning)](chapters/Chapter%206_%20Planning.md)
7. [第7章:多智能体协作(Multi-Agent Collaboration)](chapters/Chapter%207_%20Multi-Agent%20Collaboration.md)
8. [第8章:记忆管理(Memory Management)](chapters/Chapter%208_%20Memory%20Management.md)
9. [第9章:学习与适应(Learning and Adaptation)](chapters/Chapter%209_%20Learning%20and%20Adaptation.md)
10. [第10章:模型上下文协议(Model Context Protocol)](chapters/Chapter%2010_%20Model%20Context%20Protocol%20(MCP).md)
11. [第11章:目标设定与监控(Goal Setting and Monitoring)](chapters/Chapter%2011_%20Goal%20Setting%20and%20Monitoring.md)
12. [第12章:异常处理与恢复(Exception Handling and Recovery)](chapters/Chapter%2012_%20Exception%20Handling%20and%20Recovery.md)
13. [第13章:人机协同(Human-in-the-Loop)](chapters/Chapter%2013_%20Human-in-the-Loop.md)
14. [第14章:知识检索(Knowledge Retrieval - RAG)](chapters/Chapter%2014_%20Knowledge%20Retrieval%20(RAG).md)
15. [第15章:智能体间通信(Inter-Agent Communication - A2A)](chapters/Chapter%2015_%20Inter-Agent%20Communication%20(A2A).md)
16. [第16章:资源感知优化(Resource-Aware Optimization)](chapters/Chapter%2016_%20Resource-Aware%20Optimization.md)
17. [第17章:推理技术(Reasoning Techniques)](chapters/Chapter%2017_%20Reasoning%20Techniques.md)
18. [第18章:安全防护模式(Guardrails/Safety Patterns)](chapters/Chapter%2018_%20Guardrails_Safety%20Patterns.md)
19. [第19章:评估与监控(Evaluation and Monitoring)](chapters/Chapter%2019_%20Evaluation%20and%20Monitoring.md)
20. [第20章:优先级排序(Prioritization)](chapters/Chapter%2020_%20Prioritization.md)
21. [第21章:探索与发现(Exploration and Discovery)](chapters/Chapter%2021_%20Exploration%20and%20Discovery.md)

### 附录章节

- [附录A:高级提示技术](chapters/Appendix%20A_%20Advanced%20Prompting%20Techniques.md)
- [附录B:AI 智能体交互:从 GUI 到真实世界环境](chapters/Appendix%20B%20-%20AI%20Agentic%20Interactions_%20From%20GUI%20to%20Real%20world%20environment.md)
- [附录C:智能体框架快速概览](chapters/Appendix%20C%20-%20Quick%20overview%20of%20Agentic%20Frameworks.md)
- [附录D:使用 AgentSpace 构建智能体(仅在线)](chapters/Appendix%20D%20-%20Building%20an%20Agent%20with%20AgentSpace%20(on-line%20only).md)
- [附录E:命令行上的 AI 智能体](chapters/Appendix%20E%20-%20AI%20Agents%20on%20the%20CLI.md)
- [附录F:深入探究:智能体推理引擎内部机制](chapters/Appendix%20F%20%20-%20Under%20the%20Hood_%20An%20Inside%20Look%20at%20the%20Agents'%20Reasoning%20Engines.md)
- [附录G:编程智能体](chapters/Appendix%20G%20-%20%20Coding%20agents.md)

### 其他内容

- [常见问题解答](chapters/Frequently%20Asked%20Questions_%20Agentic%20Design%20Patterns.md)
- [术语表](chapters/Glossary.md)
- [术语索引](chapters/Index%20of%20Terms.md)
- [总结](chapters/Conclusion.md)

## 📁 项目结构

```
agentic-design-patterns/
├── README.md                    # 项目说明文档(本文件)
├── SUMMARY.md                   # GitBook 目录文件
├── CONTRIBUTING.md              # 贡献指南
├── translation-guide.md         # 翻译规范指南
├── progress.md                  # 翻译进度追踪
├── glossary.md                  # 术语对照表
├── PROJECT_STRUCTURE.md         # 项目结构说明
├── _config.yml                  # Jekyll 配置文件
├── Gemfile                      # Ruby 依赖管理
├── CNAME                        # 自定义域名配置
├── chapters/                    # 翻译后的章节目录
│   ├── README.md                # 章节说明
│   ├── Agentic Design Patterns.md
│   ├── Chapter 1_ Prompt Chaining.md
│   ├── Chapter 2_ Routing.md
│   └── ...                      # 其他章节和附录
├── original/                    # 原文备份目录
│   ├── Agentic Design Patterns.md
│   ├── Chapter 1_ Prompt Chaining.md
│   ├── Chapter 2_ Routing.md
│   └── ...                      # 其他原文章节
├── images/                      # 图片资源目录
│   ├── README.md                # 图片目录说明
│   ├── cover.png                # 封面图片
│   ├── chapter-1/               # 第1章图片
│   ├── chapter-2/               # 第2章图片
│   └── ...                      # 其他章节图片
├── _includes/                   # Jekyll 包含文件
│   ├── navigation.html          # 导航菜单
│   └── navigation-en.html       # 英文导航菜单
└── _layouts/                    # Jekyll 布局文件
    └── default.html             # 默认布局模板
```

## 🌐 在线访问

本项目已部署到 GitHub Pages,可以在线阅读:

**访问地址:** [https://adp.xindoo.xyz/](https://adp.xindoo.xyz/)


## 📊 翻译进度

根据 [progress.md](progress.md) 的统计,所有 32 个文件(21个核心章节 + 7个附录 + 4个其他内容)已经完成初步翻译,目前处于待审核状态。

**当前状态:**
- ✅ 已完成翻译:32/32
- 📝 已审核完成:32/32

查看详细翻译进度请参考 [progress.md](progress.md)

## 🤝 如何贡献

我们欢迎任何形式的贡献!参与方式:

1. **Fork 本仓库**
2. **创建特性分支** (`git checkout -b feature/translate-chapter-xx`)
3. **提交更改** (`git commit -am '完成第XX章翻译'`)
4. **推送分支** (`git push origin feature/translate-chapter-xx`)
5. **创建 Pull Request**

详细贡献指南请参阅 [CONTRIBUTING.md](CONTRIBUTING.md)

## 📝 翻译规范

在开始翻译前,请仔细阅读 [translation-guide.md](translation-guide.md),主要规范包括:

- **保持原文结构**:段落、标题层级保持一致
- **术语统一**:参考 [glossary.md](glossary.md) 中的术语对照表
- **代码保持原样**:代码示例、命令行等保持英文
- **图片路径**:确保图片引用路径正确指向 `images/` 目录
- **格式规范**:遵循 Markdown 格式规范
- **校对审核**:提交前进行自我校对

**注意**:所有翻译文件已初步完成,当前主要任务是进行二次审核和质量检查。

## 📚 相关资源

- [术语对照表](glossary.md) - 统一的技术术语翻译
- [翻译指南](translation-guide.md) - 详细的翻译规范和注意事项
- [项目结构说明](PROJECT_STRUCTURE.md) - 项目文件组织说明
- [GitBook 目录](SUMMARY.md) - 在线书籍的完整目录结构
- [Jekyll 配置](_config.yml) - GitHub Pages 网站配置
- [翻译进度追踪](progress.md) - 实时更新翻译状态

## Star History

[![Star History Chart](https://star-history.dera.page/svg?repos=xindoo/agentic-design-patterns&type=date&legend=top-left)](https://github.com/xindoo/agentic-design-patterns)

## 📄 许可证

本翻译项目遵循原书的许可证条款。翻译内容仅供学习交流使用。

## 联系我们
邮箱: ixindoo@gmail.com  
个人网站: [https://zxs.io/](https://zxs.io/)

---

**注意**:本项目为学习交流目的的翻译项目,如有版权问题请联系处理。

## /SUMMARY.md

# 目录

* [Agentic Design Patterns(中文翻译项目)](README.md)
* [贡献指南](CONTRIBUTING.md)
* [项目结构说明](PROJECT_STRUCTURE.md)
* [目录](TABLE_OF_CONTENTS.md)
* [glossary](glossary.md)
* [翻译进度追踪](progress.md)
* [翻译指南](translation-guide.md)
* [章节目录](chapters/README.md)
  * [智能体设计模式](<chapters/Agentic Design Patterns.md>)
  * [第 1 章:提示链](<chapters/Chapter 1_ Prompt Chaining.md>)
  * [第 2 章:路由](<chapters/Chapter 2_ Routing.md>)
  * [第 3 章:并行化](<chapters/Chapter 3_ Parallelization.md>)
  * [第 4 章:反思](<chapters/Chapter 4_ Reflection.md>)
  * [第 5 章:工具使用](<chapters/Chapter 5_ Tool Use.md>)
  * [第 6 章:规划](<chapters/Chapter 6_ Planning.md>)
  * [第 7 章:多智能体协作](<chapters/Chapter 7_ Multi-Agent Collaboration.md>)
  * [第 8 章:记忆管理](<chapters/Chapter 8_ Memory Management.md>)
  * [第 9 章:学习与适应](<chapters/Chapter 9_ Learning and Adaptation.md>)
  * [第 10 章:模型上下文协议(MCP)](<chapters/Chapter 10_ Model Context Protocol (MCP).md>)
  * [第 11 章:目标设定与监控](<chapters/Chapter 11_ Goal Setting and Monitoring.md>)
  * [第 12 章:异常处理与恢复](<chapters/Chapter 12_ Exception Handling and Recovery.md>)
  * [第 13 章:人机协同](<chapters/Chapter 13_ Human-in-the-Loop.md>)
  * [第 14 章:知识检索(RAG)](<chapters/Chapter 14_ Knowledge Retrieval (RAG).md>)
  * [第 15 章:智能体间通信(A2A)](<chapters/Chapter 15_ Inter-Agent Communication (A2A).md>)
  * [第 16 章:资源感知优化](<chapters/Chapter 16_ Resource-Aware Optimization.md>)
  * [第 17 章:推理技术](<chapters/Chapter 17_ Reasoning Techniques.md>)
  * [第 18 章:护栏与安全模式](<chapters/Chapter 18_ Guardrails_Safety Patterns.md>)
  * [第 19 章:评估与监控](<chapters/Chapter 19_ Evaluation and Monitoring.md>)
  * [第 20 章:优先级排序](<chapters/Chapter 20_ Prioritization.md>)
  * [第 21 章:探索与发现](<chapters/Chapter 21_ Exploration and Discovery.md>)
  * [附录 A:高级提示技术](<chapters/Appendix A_ Advanced Prompting Techniques.md>)
  * [附录 B:AI 智能体交互:从 GUI 到真实世界环境](<chapters/Appendix B - AI Agentic Interactions_ From GUI to Real world environment.md>)
  * [附录 C:智能体框架快速概览](<chapters/Appendix C - Quick overview of Agentic Frameworks.md>)
  * [附录 D:使用 AgentSpace 构建智能体(仅在线)](<chapters/Appendix D - Building an Agent with AgentSpace (on-line only).md>)
  * [附录 E:命令行中的 AI 智能体](<chapters/Appendix E - AI Agents on the CLI.md>)
  * [附录 F:深入探究:智能体推理引擎内部机制](<chapters/Appendix F  - Under the Hood_ An Inside Look at the Agents' Reasoning Engines.md>)
  * [附录 G:编程智能体](<chapters/Appendix G -  Coding agents.md>)
  * [总结](chapters/Conclusion.md)
  * [术语表](chapters/Glossary.md)
  * [术语索引](<chapters/Index of Terms.md>)
  * [常见问题解答:Agentic 设计模式](<chapters/Frequently Asked Questions_ Agentic Design Patterns.md>)
* [图片资源目录](images/README.md)
* [原文目录](original/README.md)
  * [智能体设计模式](<original/Agentic Design Patterns.md>)
  * [第 1 章:提示链](<original/Chapter 1_ Prompt Chaining.md>)
  * [第 2 章:路由](<original/Chapter 2_ Routing.md>)
  * [第 3 章:并行化](<original/Chapter 3_ Parallelization.md>)
  * [第 4 章:反思](<original/Chapter 4_ Reflection.md>)
  * [第 5 章:工具使用](<original/Chapter 5_ Tool Use.md>)
  * [第 6 章:规划](<original/Chapter 6_ Planning.md>)
  * [第 7 章:多智能体协作](<original/Chapter 7_ Multi-Agent Collaboration.md>)
  * [第 8 章:记忆管理](<original/Chapter 8_ Memory Management.md>)
  * [第 9 章:学习与适应](<original/Chapter 9_ Learning and Adaptation.md>)
  * [第 10 章:模型上下文协议(MCP)](<original/Chapter 10_ Model Context Protocol (MCP).md>)
  * [第 11 章:目标设定与监控](<original/Chapter 11_ Goal Setting and Monitoring.md>)
  * [第 12 章:异常处理与恢复](<original/Chapter 12_ Exception Handling and Recovery.md>)
  * [第 13 章:人机协同](<original/Chapter 13_ Human-in-the-Loop.md>)
  * [第 14 章:知识检索(RAG)](<original/Chapter 14_ Knowledge Retrieval (RAG).md>)
  * [第 15 章:智能体间通信(A2A)](<original/Chapter 15_ Inter-Agent Communication (A2A).md>)
  * [第 16 章:资源感知优化](<original/Chapter 16_ Resource-Aware Optimization.md>)
  * [第 17 章:推理技术](<original/Chapter 17_ Reasoning Techniques.md>)
  * [第 18 章:护栏与安全模式](<original/Chapter 18_ Guardrails_Safety Patterns.md>)
  * [第 19 章:评估与监控](<original/Chapter 19_ Evaluation and Monitoring.md>)
  * [第 20 章:优先级排序](<original/Chapter 20_ Prioritization.md>)
  * [第 21 章:探索与发现](<original/Chapter 21_ Exploration and Discovery.md>)
  * [附录 A:高级提示技术](<original/Appendix A_ Advanced Prompting Techniques.md>)
  * [附录 B:AI 智能体交互:从 GUI 到真实世界环境](<original/Appendix B - AI Agentic Interactions_ From GUI to Real world environment.md>)
  * [附录 C:智能体框架快速概览](<original/Appendix C - Quick overview of Agentic Frameworks.md>)
  * [附录 D:使用 AgentSpace 构建智能体(仅在线)](<original/Appendix D - Building an Agent with AgentSpace (on-line only).md>)
  * [附录 E:命令行中的 AI 智能体](<original/Appendix E - AI Agents on the CLI.md>)
  * [附录 F:深入探究:智能体推理引擎内部机制](<original/Appendix F  - Under the Hood_ An Inside Look at the Agents' Reasoning Engines.md>)
  * [附录 G:编程智能体](<original/Appendix G -  Coding agents.md>)
  * [总结](original/Conclusion.md)
  * [术语表](original/Glossary.md)
  * [术语索引](<original/Index of Terms.md>)
  * [常见问题解答:智能体设计模式](<original/Online contribution - Frequently Asked Questions_ Agentic Design Patterns.md>)


## /_config.yml

```yml path="/_config.yml" 
# Jekyll 配置文件

# 网站基本信息
title: Agentic Design Patterns
description: 《Agentic Design Patterns》中文翻译项目 - 系统介绍 AI Agent 系统的各种设计模式
author: 
  name: xindoo

# 网站设置
lang: zh-CN
timezone: Asia/Shanghai
baseurl: "/" # 子目录路径
url: "https://adp.xindoo.xyz" # 你的域名

# 主题设置
theme: jekyll-theme-cayman
# 或者使用其他主题:
# theme: just-the-docs
# remote_theme: pmarsceill/just-the-docs

# Markdown 设置
markdown: kramdown
kramdown:
  input: GFM
  syntax_highlighter: rouge
  syntax_highlighter_opts:
    block:
      line_numbers: true

# 插件
plugins:
  - jekyll-feed
  - jekyll-sitemap
  - jekyll-seo-tag
  - jekyll-relative-links

# 相对链接配置
relative_links:
  enabled: true
  collections: true

# 包含和排除文件
include:
  - README.md
  - chapters
  - images
  - original
  - bilingual

exclude:
  - Gemfile
  - Gemfile.lock
  - node_modules
  - vendor
  - .sass-cache
  - .jekyll-cache
  - .github
  - translation-guide.md
  - PROJECT_STRUCTURE.md
  - progress.md

# 默认值
defaults:
  - scope:
      path: ""
      type: "pages"
    values:
      layout: "default"

# 导航设置(用于某些主题)
navigation:
  - title: 首页
    url: /
  - title: 核心章节
    url: /chapters/
  - title: 贡献指南
    url: /CONTRIBUTING.html

# 代码高亮主题
highlighter: rouge

# 启用相对路径
permalink: pretty
```

## /_includes/navigation-bilingual.html

```html path="/_includes/navigation-bilingual.html" 
<div class="navigation">
  <h3>📚 双语章节</h3>
  <ul>
    <li><a href="{{ '/bilingual/Chapter 1_ Prompt Chaining' | relative_url }}">第 1 章:提示词链</a></li>
    <li><a href="{{ '/bilingual/Chapter 2_ Routing' | relative_url }}">第 2 章:路由</a></li>
    <li><a href="{{ '/bilingual/Chapter 3_ Parallelization' | relative_url }}">第 3 章:并行化</a></li>
    <li><a href="{{ '/bilingual/Chapter 4_ Reflection' | relative_url }}">第 4 章:反思</a></li>
    <li><a href="{{ '/bilingual/Chapter 5_ Tool Use' | relative_url }}">第 5 章:工具使用(函数调用)</a></li>
    <li><a href="{{ '/bilingual/Chapter 6_ Planning' | relative_url }}">第 6 章:规划</a></li>
    <li><a href="{{ '/bilingual/Chapter 7_ Multi-Agent Collaboration' | relative_url }}">第 7 章:多 Agent 协作</a></li>
    <li><a href="{{ '/bilingual/Chapter 8_ Memory Management' | relative_url }}">第 8 章:记忆管理</a></li>
    <li><a href="{{ '/bilingual/Chapter 9_ Learning and Adaptation' | relative_url }}">第 9 章:学习和适应</a></li>
    <li><a href="{{ '/bilingual/Chapter 10_ Model Context Protocol (MCP)' | relative_url }}">第 10 章:模型上下文协议 (MCP)</a></li>
    <li><a href="{{ '/bilingual/Chapter 11_ Goal Setting and Monitoring' | relative_url }}">第 11 章:目标设定和监控</a></li>
    <li><a href="{{ '/bilingual/Chapter 12_ Exception Handling and Recovery' | relative_url }}">第 12 章:异常处理和恢复</a></li>
    <li><a href="{{ '/bilingual/Chapter 13_ Human-in-the-Loop' | relative_url }}">第 13 章:人机协同</a></li>
    <li><a href="{{ '/bilingual/Chapter 14_ Knowledge Retrieval (RAG)' | relative_url }}">第 14 章:知识检索(RAG)</a></li>
    <li><a href="{{ '/bilingual/Chapter 15_ Inter-Agent Communication (A2A)' | relative_url }}">第 15 章:Agent 间通信(A2A)</a></li>
    <li><a href="{{ '/bilingual/Chapter 16_ Resource-Aware Optimization' | relative_url }}">第 16 章:资源感知优化</a></li>
    <li><a href="{{ '/bilingual/Chapter 17_ Reasoning Techniques' | relative_url }}">第 17 章:推理技术</a></li>
    <li><a href="{{ '/bilingual/Chapter 18_ Guardrails_Safety Patterns' | relative_url }}">第 18 章:Guardrails/安全模式</a></li>
    <li><a href="{{ '/bilingual/Chapter 19_ Evaluation and Monitoring' | relative_url }}">第 19 章:评估和监控</a></li>
    <li><a href="{{ '/bilingual/Chapter 20_ Prioritization' | relative_url }}">第 20 章:优先级排序</a></li>
    <li><a href="{{ '/bilingual/Chapter 21_ Exploration and Discovery' | relative_url }}">第 21 章:探索和发现</a></li>
  </ul>

  <h3>📖 附录章节(双语)</h3>
  <ul>
    <li><a href="{{ '/bilingual/Appendix A_ Advanced Prompting Techniques' | relative_url }}">附录 A:高级提示工程技巧</a></li>
    <li><a href="{{ '/bilingual/Appendix B - AI Agentic Interactions_ From GUI to Real world environment' | relative_url }}">附录 B - AI Agentic 交互</a></li>
    <li><a href="{{ '/bilingual/Appendix C - Quick overview of Agentic Frameworks' | relative_url }}">附录 C - Agentic 框架快速概览</a></li>
    <li><a href="{{ '/bilingual/Appendix D - Building an Agent with AgentSpace (on-line only)' | relative_url }}">附录 D - 使用 AgentSpace 构建 Agent</a></li>
    <li><a href="{{ '/bilingual/Appendix E - AI Agents on the CLI' | relative_url }}">附录 E - 命令行界面中的 AI Agent</a></li>
    {% capture appendix_f_url %}/bilingual/Appendix F  - Under the Hood_ An Inside Look at the Agents' Reasoning Engines{% endcapture %}
    <li><a href="{{ appendix_f_url | relative_url }}">附录 F - 深入剖析</a></li>
    <li><a href="{{ '/bilingual/Appendix G -  Coding agents' | relative_url }}">附录 G - 编码 Agent</a></li>
  </ul>

  <h3>📝 其他内容(双语)</h3>
  <ul>
    <li><a href="{{ '/bilingual/Frequently Asked Questions_ Agentic Design Patterns' | relative_url }}">常见问题解答</a></li>
    <li><a href="{{ '/bilingual/Glossary' | relative_url }}">术语表</a></li>
    <li><a href="{{ '/bilingual/Index of Terms' | relative_url }}">术语索引</a></li>
    <li><a href="{{ '/bilingual/Conclusion' | relative_url }}">结论</a></li>
  </ul>

  <h3>📂 项目信息</h3>
  <ul>
    <li><a href="{{ '/CONTRIBUTING' | relative_url }}">贡献指南</a></li>
    <li><a href="{{ '/glossary' | relative_url }}">术语对照表</a></li>
  </ul>
</div>
```

## /_includes/navigation-en.html

```html path="/_includes/navigation-en.html" 
<div class="navigation">
  <h3>📚 Core Chapters</h3>
  <ul>
    <li><a href="{{ '/original/Chapter 1_ Prompt Chaining' | relative_url }}">Chapter 1: Prompt Chaining</a></li>
    <li><a href="{{ '/original/Chapter 2_ Routing' | relative_url }}">Chapter 2: Routing</a></li>
    <li><a href="{{ '/original/Chapter 3_ Parallelization' | relative_url }}">Chapter 3: Parallelization</a></li>
    <li><a href="{{ '/original/Chapter 4_ Reflection' | relative_url }}">Chapter 4: Reflection</a></li>
    <li><a href="{{ '/original/Chapter 5_ Tool Use' | relative_url }}">Chapter 5: Tool Use (Function Calling)</a></li>
    <li><a href="{{ '/original/Chapter 6_ Planning' | relative_url }}">Chapter 6: Planning</a></li>
    <li><a href="{{ '/original/Chapter 7_ Multi-Agent Collaboration' | relative_url }}">Chapter 7: Multi-Agent Collaboration</a></li>
    <li><a href="{{ '/original/Chapter 8_ Memory Management' | relative_url }}">Chapter 8: Memory Management</a></li>
    <li><a href="{{ '/original/Chapter 9_ Learning and Adaptation' | relative_url }}">Chapter 9: Learning and Adaptation</a></li>
    <li><a href="{{ '/original/Chapter 10_ Model Context Protocol (MCP)' | relative_url }}">Chapter 10: Model Context Protocol (MCP)</a></li>
    <li><a href="{{ '/original/Chapter 11_ Goal Setting and Monitoring' | relative_url }}">Chapter 11: Goal Setting and Monitoring</a></li>
    <li><a href="{{ '/original/Chapter 12_ Exception Handling and Recovery' | relative_url }}">Chapter 12: Exception Handling and Recovery</a></li>
    <li><a href="{{ '/original/Chapter 13_ Human-in-the-Loop' | relative_url }}">Chapter 13: Human-in-the-Loop</a></li>
    <li><a href="{{ '/original/Chapter 14_ Knowledge Retrieval (RAG)' | relative_url }}">Chapter 14: Knowledge Retrieval (RAG)</a></li>
    <li><a href="{{ '/original/Chapter 15_ Inter-Agent Communication (A2A)' | relative_url }}">Chapter 15: Inter-Agent Communication (A2A)</a></li>
    <li><a href="{{ '/original/Chapter 16_ Resource-Aware Optimization' | relative_url }}">Chapter 16: Resource-Aware Optimization</a></li>
    <li><a href="{{ '/original/Chapter 17_ Reasoning Techniques' | relative_url }}">Chapter 17: Reasoning Techniques</a></li>
    <li><a href="{{ '/original/Chapter 18_ Guardrails_Safety Patterns' | relative_url }}">Chapter 18: Guardrails/Safety Patterns</a></li>
    <li><a href="{{ '/original/Chapter 19_ Evaluation and Monitoring' | relative_url }}">Chapter 19: Evaluation and Monitoring</a></li>
    <li><a href="{{ '/original/Chapter 20_ Prioritization' | relative_url }}">Chapter 20: Prioritization</a></li>
    <li><a href="{{ '/original/Chapter 21_ Exploration and Discovery' | relative_url }}">Chapter 21: Exploration and Discovery</a></li>
  </ul>

  <h3>📖 Appendices</h3>
  <ul>
    <li><a href="{{ '/original/Appendix A_ Advanced Prompting Techniques' | relative_url }}">Appendix A: Advanced Prompting Techniques</a></li>
    <li><a href="{{ '/original/Appendix B - AI Agentic Interactions_ From GUI to Real world environment' | relative_url }}">Appendix B - AI Agentic Interactions: From GUI to Real world environment</a></li>
    <li><a href="{{ '/original/Appendix C - Quick overview of Agentic Frameworks' | relative_url }}">Appendix C - Quick overview of Agentic Frameworks</a></li>
    <li><a href="{{ '/original/Appendix D - Building an Agent with AgentSpace (on-line only)' | relative_url }}">Appendix D - Building an Agent with AgentSpace (on-line only)</a></li>
    <li><a href="{{ '/original/Appendix E - AI Agents on the CLI' | relative_url }}">Appendix E - AI Agents on the CLI</a></li>
    {% capture appendix_f_url %}/original/Appendix F  - Under the Hood_ An Inside Look at the Agents' Reasoning Engines{% endcapture %}
    <li><a href="{{ appendix_f_url | relative_url }}">Appendix F - Under the Hood: An Inside Look at the Agents' Reasoning Engines</a></li>
    <li><a href="{{ '/original/Appendix G -  Coding agents' | relative_url }}">Appendix G - Coding agents</a></li>
  </ul>

  <h3>📝 Additional Content</h3>
  <ul>
    <li><a href="{{ '/original/Online contribution - Frequently Asked Questions_ Agentic Design Patterns' | relative_url }}">Frequently Asked Questions: Agentic Design Patterns</a></li>
    <li><a href="{{ '/original/Glossary' | relative_url }}">Glossary</a></li>
    <li><a href="{{ '/original/Index of Terms' | relative_url }}">Index of Terms</a></li>
    <li><a href="{{ '/original/Conclusion' | relative_url }}">Conclusion</a></li>
  </ul>

  <h3>📂 Project Information</h3>
  <ul>
    <li><a href="{{ '/CONTRIBUTING' | relative_url }}">Contributing Guide</a></li>
    <li><a href="{{ '/glossary' | relative_url }}">Glossary Comparison</a></li>
  </ul>
</div>
```

## /_includes/navigation.html

```html path="/_includes/navigation.html" 
<div class="navigation">
  <h3>📚 核心章节</h3>
  <ul>
    <li><a href="{{ '/chapters/Chapter 1_ Prompt Chaining' | relative_url }}">第 1 章:提示词链</a></li>
    <li><a href="{{ '/chapters/Chapter 2_ Routing' | relative_url }}">第 2 章:路由</a></li>
    <li><a href="{{ '/chapters/Chapter 3_ Parallelization' | relative_url }}">第 3 章:并行化</a></li>
    <li><a href="{{ '/chapters/Chapter 4_ Reflection' | relative_url }}">第 4 章:反思</a></li>
    <li><a href="{{ '/chapters/Chapter 5_ Tool Use' | relative_url }}">第 5 章:工具使用(函数调用)</a></li>
    <li><a href="{{ '/chapters/Chapter 6_ Planning' | relative_url }}">第 6 章:规划</a></li>
    <li><a href="{{ '/chapters/Chapter 7_ Multi-Agent Collaboration' | relative_url }}">第 7 章:多 Agent 协作</a></li>
    <li><a href="{{ '/chapters/Chapter 8_ Memory Management' | relative_url }}">第 8 章:记忆管理</a></li>
    <li><a href="{{ '/chapters/Chapter 9_ Learning and Adaptation' | relative_url }}">第 9 章:学习和适应</a></li>
    <li><a href="{{ '/chapters/Chapter 10_ Model Context Protocol (MCP)' | relative_url }}">第 10 章:模型上下文协议 (MCP)</a></li>
    <li><a href="{{ '/chapters/Chapter 11_ Goal Setting and Monitoring' | relative_url }}">第 11 章:目标设定和监控</a></li>
    <li><a href="{{ '/chapters/Chapter 12_ Exception Handling and Recovery' | relative_url }}">第 12 章:异常处理和恢复</a></li>
    <li><a href="{{ '/chapters/Chapter 13_ Human-in-the-Loop' | relative_url }}">第 13 章:人机协同</a></li>
    <li><a href="{{ '/chapters/Chapter 14_ Knowledge Retrieval (RAG)' | relative_url }}">第 14 章:知识检索(RAG)</a></li>
    <li><a href="{{ '/chapters/Chapter 15_ Inter-Agent Communication (A2A)' | relative_url }}">第 15 章:Agent 间通信(A2A)</a></li>
    <li><a href="{{ '/chapters/Chapter 16_ Resource-Aware Optimization' | relative_url }}">第 16 章:资源感知优化</a></li>
    <li><a href="{{ '/chapters/Chapter 17_ Reasoning Techniques' | relative_url }}">第 17 章:推理技术</a></li>
    <li><a href="{{ '/chapters/Chapter 18_ Guardrails_Safety Patterns' | relative_url }}">第 18 章:Guardrails/安全模式</a></li>
    <li><a href="{{ '/chapters/Chapter 19_ Evaluation and Monitoring' | relative_url }}">第 19 章:评估和监控</a></li>
    <li><a href="{{ '/chapters/Chapter 20_ Prioritization' | relative_url }}">第 20 章:优先级排序</a></li>
    <li><a href="{{ '/chapters/Chapter 21_ Exploration and Discovery' | relative_url }}">第 21 章:探索和发现</a></li>
  </ul>

  <h3>📖 附录章节</h3>
  <ul>
    <li><a href="{{ '/chapters/Appendix A_ Advanced Prompting Techniques' | relative_url }}">附录 A:高级提示工程技巧</a></li>
    <li><a href="{{ '/chapters/Appendix B - AI Agentic Interactions_ From GUI to Real world environment' | relative_url }}">附录 B - AI Agentic 交互:从图形界面到现实世界环境</a></li>
    <li><a href="{{ '/chapters/Appendix C - Quick overview of Agentic Frameworks' | relative_url }}">附录 C - Agentic 框架快速概览</a></li>
    <li><a href="{{ '/chapters/Appendix D - Building an Agent with AgentSpace (on-line only)' | relative_url }}">附录 D - 使用 AgentSpace 构建 Agent</a></li>
    <li><a href="{{ '/chapters/Appendix E - AI Agents on the CLI' | relative_url }}">附录 E - 命令行界面中的 AI Agent</a></li>
    {% capture appendix_f_url %}/chapters/Appendix F  - Under the Hood_ An Inside Look at the Agents' Reasoning Engines{% endcapture %}
    <li><a href="{{ appendix_f_url | relative_url }}">附录 F - 深入剖析:Agent 推理引擎的内部运作机制</a></li>
    <li><a href="{{ '/chapters/Appendix G -  Coding agents' | relative_url }}">附录 G - 编码 Agent</a></li>
  </ul>

  <h3>📝 其他内容</h3>
  <ul>
    <li><a href="{{ '/chapters/Frequently Asked Questions_ Agentic Design Patterns' | relative_url }}">常见问题解答:Agentic 设计模式</a></li>
    <li><a href="{{ '/chapters/Glossary' | relative_url }}">术语表</a></li>
    <li><a href="{{ '/chapters/Index of Terms' | relative_url }}">术语索引</a></li>
    <li><a href="{{ '/chapters/Conclusion' | relative_url }}">结论</a></li>
  </ul>

  <h3>📂 项目信息</h3>
  <ul>
    <li><a href="{{ '/CONTRIBUTING' | relative_url }}">贡献指南</a></li>
    <li><a href="{{ '/glossary' | relative_url }}">术语对照表</a></li>
  </ul>
</div>
```

## /_layouts/bilingual.html

```html path="/_layouts/bilingual.html" 
---
layout: default
---
<style>
/* 双语内容样式 */
.bilingual-paragraph {
    padding: 0.5rem 0;
    margin: 0;
}

.bilingual-paragraph.english {
    border-left: 3px solid #0366d6;
    padding-left: 1rem;
    margin-bottom: 1rem;
}

.bilingual-paragraph.chinese {
    border-left: 3px solid #159957;
    padding-left: 1rem;
    margin-bottom: 1.5rem;
    color: #57606a;
}

body.dark-mode .bilingual-paragraph.chinese {
    color: #8b949e;
}

/* 代码块样式 - 不分割,保持完整 */
.bilingual-paragraph pre {
    margin: 1rem 0;
}

.bilingual-section {
    margin-bottom: 2rem;
}

/* 语言标签样式 */
.lang-label {
    display: inline-block;
    font-size: 0.75rem;
    font-weight: 600;
    padding: 0.1rem 0.5rem;
    border-radius: 3px;
    margin-bottom: 0.25rem;
}

.lang-label.en {
    background-color: #0366d6;
    color: #fff;
}

.lang-label.zh {
    background-color: #159957;
    color: #fff;
}
</style>

{{ content }}
```

## /_layouts/default.html

```html path="/_layouts/default.html" 
<!DOCTYPE html>
<html lang="{{ site.lang | default: 'zh-CN' }}">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  {% seo %}
  
  <link rel="stylesheet" href="{{ '/assets/css/style.css?v=' | append: site.github.build_revision | relative_url }}">
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji"; line-height: 1.6; color: #24292e; }
    .page-header { background-color: #159957; background-image: linear-gradient(120deg, #155799, #159957); padding: 0.5rem 1rem; position: sticky; top: 0; z-index: 10; width: 100%; display: flex; justify-content: space-between; align-items: center; }
    .project-name { margin: 0; font-size: 1.5rem; font-weight: bold; color: #fff; }
    .project-tagline { margin: 0; font-weight: normal; opacity: 0.8; font-size: 0.8rem; color: #fff; }
    .main-content { max-width: 1200px; margin: 0 auto; padding: 2rem 1rem; display: flex; gap: 2rem; }
    .sidebar { width: 280px; flex-shrink: 0; }
    .sidebar nav { position: sticky; top: 20px; max-height: calc(100vh - 40px); overflow-y: auto; }
    .post-nav { margin-top: 3rem; display: flex; justify-content: space-between; border-top: 1px solid #eee; padding-top: 1rem; }
    .post-nav a { color: #0366d6; text-decoration: none; font-weight: bold; }
    .post-nav a:hover { text-decoration: underline; }
    .sidebar h3 { margin-top: 1.5rem; margin-bottom: 0.5rem; font-size: 1.1rem; color: #0366d6; }
    .sidebar ul { list-style: none; padding-left: 0; margin: 0; }
    .sidebar li { margin: 0.3rem 0; }
    .sidebar a { color: #24292e; text-decoration: none; display: block; padding: 0.25rem 0; }
    .sidebar a:hover { color: #0366d6; text-decoration: underline; }
    .content { flex: 1; min-width: 0; }
    .content img { max-width: 100%; height: auto; }
    .content pre { padding: 1rem; background-color: #f6f8fa; border-radius: 6px; overflow-x: auto; }
    .content code { background-color: #f6f8fa; padding: 0.2em 0.4em; border-radius: 3px; font-size: 85%; }
    .content pre code { background-color: transparent; padding: 0; }
    .btn { display: inline-block; margin-bottom: 1rem; color: rgba(255, 255, 255, 0.9); background-color: rgba(255, 255, 255, 0.08); border-color: rgba(255, 255, 255, 0.2); border-style: solid; border-width: 1px; border-radius: 0.3rem; padding: 0.75rem 1rem; text-decoration: none; transition: all 0.2s; }
    .btn:hover { color: rgba(255, 255, 255, 1); background-color: rgba(255, 255, 255, 0.2); border-color: rgba(255, 255, 255, 0.3); }
    .language-toggle { margin-bottom: 0; }
    .language-btn { background-color: rgba(255, 255, 255, 0.15); border-color: rgba(255, 255, 255, 0.3); font-weight: 500; }
    .header-controls .btn { padding: 0; width: 42px; height: 42px; display: inline-flex; justify-content: center; align-items: center; line-height: 1; }
    /* Dark Mode Styles */
    body.dark-mode { background-color: #0d1117; color: #c9d1d9; }
    body.dark-mode .sidebar a { color: #c9d1d9; }
    body.dark-mode .sidebar a:hover, body.dark-mode .sidebar h3, body.dark-mode .post-nav a, body.dark-mode .content a { color: #58a6ff; }
    body.dark-mode .content pre, body.dark-mode .content code { background-color: #161b22; color: #c9d1d9; }
    body.dark-mode .post-nav { border-top-color: #30363d; }
    .header-controls .btn svg { width: 24px; height: 24px; fill: #fff; }
    .header-controls .btn .sun-icon, .header-controls .btn .moon-icon { fill: none; }
    .language-btn:hover { background-color: rgba(255, 255, 255, 0.25); border-color: rgba(255, 255, 255, 0.4); }
    .header-title { text-align: left; }
    .header-controls { display: flex; align-items: center; gap: 1rem; }
    .page-header .btn { margin-bottom: 0; }
    .sidebar-toggle-btn { display: none; background-color: transparent; border: none; padding: 0.5rem; margin-right: 0.5rem; cursor: pointer; }
    .sidebar-toggle-btn .icon-bar { display: block; width: 22px; height: 2px; background-color: #fff; border-radius: 1px; }
    .sidebar-toggle-btn .icon-bar + .icon-bar { margin-top: 4px; }
    @media screen and (max-width: 768px) {
      .sidebar-toggle-btn { display: block; }
      .main-content { flex-direction: column; }
      .sidebar { width: 100%; display: none; }
      .sidebar.is-visible { display: block; }
      .sidebar nav { position: static; max-height: none; overflow-y: visible; }
      .page-header { justify-content: flex-start; }
      .project-name { font-size: 1.2rem; }
      .project-tagline { display: none; }
      .header-controls { gap: 0.5rem; }
      .header-controls .btn { padding: 0.5rem 0.75rem; font-size: 0.8rem; }
    }
  </style>
</head>
<body>
  <header class="page-header" role="banner">
    <button type="button" class="sidebar-toggle-btn" id="sidebar-toggle">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <div class="header-title">
      <h1 class="project-name">{{ site.title | default: site.github.repository_name }}</h1>
      <h2 class="project-tagline">{{ site.description | default: site.github.project_tagline }}</h2>
    </div>
    <div class="header-controls">
      <div class="theme-toggle">
        <button id="themeToggle" class="btn" aria-label="Toggle theme">
          <svg class="sun-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display: none;"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg>
          <svg class="moon-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display: none;"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg>
        </button>
      </div>
      <div class="language-toggle">
        <button id="languageToggle" class="btn language-btn"></button>
      </div>
      {% if site.github.is_project_page %}
        <a href="{{ site.github.repository_url }}" class="btn" title="View on GitHub">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.91 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/></svg>
        </a>
      {% endif %}
    </div>
  </header>

  <div class="main-content">
    <aside class="sidebar">
      <nav id="nav-zh" class="navigation-content" style="display: block;">
        {% include navigation.html %}
      </nav>
      <nav id="nav-en" class="navigation-content" style="display: none;">
        {% include navigation-en.html %}
      </nav>
      <nav id="nav-bilingual" class="navigation-content" style="display: none;">
        {% include navigation-bilingual.html %}
      </nav>
    </aside>
    
    <main class="content" role="main">
      {{ content }}

      {%- if page.path contains 'original/' -%}
        {%- assign pages = site.pages | where_exp: "item", "item.path contains 'original/'" -%}
      {%- else -%}
        {%- if page.path contains 'bilingual/' -%}
          {%- assign pages = site.pages | where_exp: "item", "item.path contains 'bilingual/'" -%}
        {%- else -%}
          {%- assign pages = site.pages | where_exp: "item", "item.path contains 'chapters/'" -%}
        {%- endif -%}
      {%- endif -%}

      {%- assign chapter_entries = "" | split: "" -%}
      {%- assign other_pages = "" | split: "" -%}

      {%- for p in pages -%}
        {%- if p.path contains 'Chapter' -%}
          {%- assign num_str = p.path | split: 'Chapter ' | last | split: '_' | first | strip -%}
          {%- assign num = num_str | plus: 0 -%}
          {%- if num < 10 -%}
            {%- assign padded = '0' | append: num -%}
          {%- else -%}
            {%- assign padded = num | append: '' -%}
          {%- endif -%}
          {%- assign entry = padded | append: '||' | append: p.url -%}
          {%- assign chapter_entries = chapter_entries | push: entry -%}
        {%- else -%}
          {%- assign other_pages = other_pages | push: p -%}
        {%- endif -%}
      {%- endfor -%}

      {%- assign sorted_entries = chapter_entries | sort -%}
      {%- assign sorted_chapters = "" | split: "" -%}
      {%- for e in sorted_entries -%}
        {%- assign parts = e | split: '||' -%}
        {%- assign url = parts[1] -%}
        {%- assign matched = pages | where: "url", url -%}
        {%- if matched.size > 0 -%}
          {%- assign sorted_chapters = sorted_chapters | push: matched[0] -%}
        {%- endif -%}
      {%- endfor -%}

      {%- assign sorted_pages = other_pages | concat: sorted_chapters -%}

      {%- for page_item in sorted_pages -%}
        {%- if page_item.url == page.url -%}
          {%- assign current_index = forloop.index0 -%}
        {%- endif -%}
      {%- endfor -%}
      {%- assign pages = sorted_pages -%}

      {%- assign prev_index = current_index | minus: 1 -%}
      {%- assign next_index = current_index | plus: 1 -%}

      {%- if prev_index >= 0 -%}
        {%- assign prev_page = pages[prev_index] -%}
      {%- endif -%}

      {%- if next_index < pages.size -%}
        {%- assign next_page = pages[next_index] -%}
      {%- endif -%}

      {% if prev_page or next_page %}
      <nav class="post-nav">
        <div>
          {% if prev_page %}
            <a href="{{ prev_page.url | relative_url }}">
              {% if page.path contains 'original/' or page.path contains 'bilingual/' %}
                &laquo; Previous: {{ prev_page.title }}
              {% else %}
                &laquo; 上一章: {{ prev_page.title }}
              {% endif %}
            </a>
          {% endif %}
        </div>
        <div>
          {% if next_page %}
            <a href="{{ next_page.url | relative_url }}">
              {% if page.path contains 'original/' or page.path contains 'bilingual/' %}
                Next: {{ next_page.title }} &raquo;
              {% else %}
                下一章: {{ next_page.title }} &raquo;
              {% endif %}
            </a>
          {% endif %}
        </div>
      </nav>
      {% endif %}
    </main>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // Theme toggle functionality
      const themeToggle = document.getElementById('themeToggle');
      const sunIcon = document.querySelector('.sun-icon');
      const moonIcon = document.querySelector('.moon-icon');
      
      const savedTheme = localStorage.getItem('theme');
      const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
      
      const setTheme = (theme) => {
        if (theme === 'dark') {
          document.body.classList.add('dark-mode');
          if (sunIcon) sunIcon.style.display = 'block';
          if (moonIcon) moonIcon.style.display = 'none';
        } else {
          document.body.classList.remove('dark-mode');
          if (sunIcon) sunIcon.style.display = 'none';
          if (moonIcon) moonIcon.style.display = 'block';
        }
        localStorage.setItem('theme', theme);
      };
      
      setTheme(savedTheme || systemTheme);
      
      if (themeToggle) {
        themeToggle.addEventListener('click', () => {
          const isDark = document.body.classList.contains('dark-mode');
          setTheme(isDark ? 'light' : 'dark');
        });
      }

      const sidebarToggle = document.getElementById('sidebar-toggle');
      const sidebar = document.querySelector('.sidebar');

      if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', function() {
          sidebar.classList.toggle('is-visible');
        });
      }

      const header = document.querySelector('.page-header');
      const sidebarNav = document.querySelector('.sidebar nav');
      if (header && sidebarNav) {
        const updateSidebarNavTop = () => {
          const headerHeight = header.offsetHeight;
          sidebarNav.style.top = (headerHeight + 20) + 'px';
          sidebarNav.style.maxHeight = `calc(100vh - ${headerHeight + 40}px)`;
        };
        updateSidebarNavTop();
        window.addEventListener('resize', updateSidebarNavTop);
      }

      // Language toggle functionality with three states (zh -> en -> bilingual -> zh)
      const languageToggle = document.getElementById('languageToggle');
      const navZh = document.getElementById('nav-zh');
      const navEn = document.getElementById('nav-en');
      const navBilingual = document.getElementById('nav-bilingual');
      const pathname = window.location.pathname;

      const isEnglish = pathname.startsWith('/original/');
      const isBilingual = pathname.startsWith('/bilingual/');

      if (isBilingual) {
        navZh.style.display = 'none';
        navEn.style.display = 'none';
        navBilingual.style.display = 'block';
        languageToggle.textContent = '中';
      } else if (isEnglish) {
        navZh.style.display = 'none';
        navEn.style.display = 'block';
        navBilingual.style.display = 'none';
        languageToggle.textContent = '双';
      } else {
        navZh.style.display = 'block';
        navEn.style.display = 'none';
        navBilingual.style.display = 'none';
        languageToggle.textContent = 'En';
      }

      if (languageToggle) {
        languageToggle.addEventListener('click', function() {
            const currentPath = window.location.pathname;
            const isEnglish = currentPath.startsWith('/original/');
            const isBilingual = currentPath.startsWith('/bilingual/');
            const isRoot = currentPath === '/' || currentPath === '/index.html';

            let newUrl;

            if (isBilingual) {
                // Switch from bilingual to Chinese
                if (isRoot) {
                    newUrl = '/';
                } else {
                    newUrl = currentPath.replace('/bilingual/', '/chapters/');
                }
            } else if (isEnglish) {
                // Switch from English to bilingual
                if (currentPath === '/original/' || currentPath === '/original/index.html') {
                    newUrl = '/bilingual/';
                } else {
                    newUrl = currentPath.replace('/original/', '/bilingual/');
                }
            } else {
                // Switch from Chinese to English
                if (isRoot) {
                    newUrl = '/original/';
                } else {
                    newUrl = currentPath.replace('/chapters/', '/original/');
                }
            }
            
            if (newUrl === currentPath) {
               newUrl = isBilingual ? '/' : (isEnglish ? '/bilingual/' : '/original/');
            }

            window.location.href = newUrl;
        });
      }

      function fixMarkdownLinks() {
        const contentArea = document.querySelector('.content');
        if (!contentArea) return;
        const links = contentArea.querySelectorAll('a[href*=".md"]');
        links.forEach(function(link) {
          const href = link.getAttribute('href');
          if (!href || !href.includes('.md')) return;
          if (/^([a-z]+:|#|\/\/)/i.test(href)) return;
          try {
            const resolved = new URL(href, window.location.href);
            if (resolved.origin !== window.location.origin) return;
            resolved.pathname = resolved.pathname.replace(/\.md$/i, '');
            link.setAttribute('href', resolved.pathname + resolved.search + resolved.hash);
          } catch (e) {
            // Leave the link untouched if URL parsing fails.
          }
        });
      }
      
      fixMarkdownLinks();
    });
  </script>

  {% if site.google_analytics %}
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
      ga('create', '{{ site.google_analytics }}', 'auto');
      ga('send', 'pageview');
    </script>
  {% endif %}
  <link href="https://cdn.jsdelivr.net/npm/@n8n/chat/dist/style.css" rel="stylesheet" />
  {% assign md_filename = page.path | split: '/' | last | split: '.' | first %}
  <script type="module">
    import { createChat } from 'https://cdn.jsdelivr.net/npm/@n8n/chat/dist/chat.bundle.es.js';

    createChat({
      webhookUrl: 'https://n8n.xindoo.xyz/webhook/891dc8de-d517-4a72-a5fb-b7d432f869c9/chat',
      target: '#n8n-chat',
      mode: 'window',
      chatInputKey: 'chatInput',
      chatSessionKey: 'sessionId',
      loadPreviousSession: true,
      metadata: {
        title: '{{ md_filename }}'
      },
      showWelcomeScreen: false,
      defaultLanguage: 'cn',
      initialMessages: [
        '你可以向我提问任何关于本书的问题',
        '你也可以让我帮忙解释本章节'
      ],
      i18n: {
        cn: {
          title: 'ADP阅读助手',
          subtitle: "你可以询问我任何关于本书的问题!",
          footer: '',
          getStarted: '新对话',
          inputPlaceholder: '输入你的问题...',
        },
      },
      enableStreaming: true
    });
  </script>
</body>
</html>
```

## /bilingual/Agentic Design Patterns.md

---
layout: bilingual
lang: bilingual
---

# Agentic Design Patterns

# 智能体设计模式

*A Hands-On Guide to Building Intelligent Systems[^1], [Antonio Gulli](https://www.linkedin.com/in/searchguy/)*  

*构建智能系统的实战指南[^2],作者:[Antonio Gulli](https://www.linkedin.com/in/searchguy/)*  

Table of Contents - total 424 pages = 1+2+1+1+4+9+103+61+34+114+74+5+4 11

**目录总览**(424 页)

[Dedication](https://docs.google.com/document/d/1cQ61mNpiWn6eSORmWjEjF44vN2Lpba8kyKmNwIC60ig/edit?usp=sharing), 1 page

- 致谢(1 页)

[Acknowledgment](https://docs.google.com/document/d/1u2y6tY48bw8nriDUuwWEf9s8g66vyIqBKSKZDOS-n0s/edit?tab=t.0#heading=h.y1l1kh7vu0qi), *2 pages*  \[final, last read done\]  

- 鸣谢(2 页)

[Foreword](https://docs.google.com/document/d/18Q9kfZuCTL37ztrSjLxwf8Elr5UfAiAavmnj0IqSpbU/edit?tab=t.0#heading=h.5wi2c0amdd0f), 1 page   \[final, last read done\]  

- 前言(1 页)

[A Thought Leader's Perspective: Power and Responsibility](https://docs.google.com/document/d/1PWhaXD_UNKgJaxYe3JBxRFRt3_B8Wm67CFxtSBQ4LkU/edit?tab=t.0#heading=h.2v348nrvaqww)   \[final, last read done\]  

- 思想领袖视角:权力与责任

[Introduction](https://docs.google.com/document/d/1K5jwqB6jh20uHL0TTWxqWOxFk-dzFxRvHzrRRV79hrg/edit?tab=t.0), 4 pages \[final, last read done\]  

- [引言](README.md)(4 页)

[What makes an AI system an "agent"?](https://docs.google.com/document/d/1Nw6hRa7ItdLr_Tj5hF2q-OH8B_uPKb--RLn8SXZKA94/edit?usp=sharing), 9 pages \[final, last read done\]

- 是什么让 AI 系统成为"智能体"?(9 页)

Part One, (Total: 103 pages)

## 第一部分:核心模式(103 页)

1. [Chapter 1: Prompt Chaining](https://docs.google.com/document/d/1flxKGrbnF2g8yh3F-oVD5Xx7ZumId56HbFpIiPdkqLI/edit?usp=sharing) ([code](https://colab.research.google.com/drive/15XCzDOvBhIQaZ__xkvruf5sP9OznAbK9)), 12 pages \[final, last read done, code ok\]  

1. [提示词链](Chapter%201_%20Prompt%20Chaining.md)(12 页)

2. [Chapter 2: Routing](https://docs.google.com/document/d/1ux_n8n3T4bYndOjs1DKW5ccpC802KISdy2IWnlvYbas/edit?tab=t.0) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 13 pages \[final, last read done, code ok\]  

2. [路由决策](Chapter%202_%20Routing.md)(13 页)

3. [Chapter 3: Parallelization](https://docs.google.com/document/d/1XVMp4RcRkoUJTVbrPfoWZX703CUJpWkrhyFU2cfUOA/edit?tab=t.0) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 15 pages \[final, last read done, code ok\]  

3. [并行执行](Chapter%203_%20Parallelization.md)(15 页)

4. [Chapter 4: Reflection](https://docs.google.com/document/d/1HXXJOQIMWowtLw4WMiSR360caDAlZPtl5dPPgvq9IT4/edit?tab=t.0#heading=h.a7nkedxjnyap) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 13 pages \[final, last read done, code ok\]  

4. [反思优化](Chapter%204_%20Reflection.md)(13 页)

5. [Chapter 5: Tool Use](https://docs.google.com/document/d/1bE4iMljhppqGY1p48gQWtZvk6MfRuJRCiba1yRykGNE/edit?usp=sharing) [(code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 20 pages \[final, last read done, code ok\]  

5. [工具调用](Chapter%205_%20Tool%20Use.md)(20 页)

6. [Chapter 6: Planning](https://docs.google.com/document/d/18vvNESEwHnVUREzIipuaDNCnNAREGqEfy9MQYC9wb4o/edit?usp=sharing) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 13 pages \[final, last read done, code ok\]  

6. [任务规划](Chapter%206_%20Planning.md)(13 页)

7. [Chapter 7: Multi-Agent](https://docs.google.com/document/d/1RZ5-2fykDQKOBx01pwfKkDe0GCs5ydca7xW9Q4wqS_M/edit?tab=t.0) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 17 pages \[final,  last read done, code ok\], **121**  

7. [多智能体协作](Chapter%207_%20Multi-Agent%20Collaboration.md)(17 页)

Part Two (Total: 61 pages)

## 第二部分:认知机制(61 页)

8. [Chapter 8: Memory Management](https://docs.google.com/document/d/1asVTObtzIye0I9ypAztaeeI_sr_Hx2TORE02uUuqH_c/edit?tab=t.0) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 21 pages \[final, last read done, code ok\]  

8. [记忆管理](Chapter%208_%20Memory%20Management.md)(21 页)

9. [Chapter 9: Learning and Adaptation](https://docs.google.com/document/d/1UHTEDCmSM1nwB-iyMoHuYzVcu_B_4KkJ2ITGGUKqo8s/edit?tab=t.0) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 12 pages \[final, last read done, code ok\]  

9. [学习与适应](Chapter%209_%20Learning%20and%20Adaptation.md)(12 页)

10. [Chapter 10: Model Context Protocol (MCP)](https://docs.google.com/document/d/1e6XimYczKmhX9zpqEyxLFWPQgGuG0brp7Hic2sFl_qw/edit?usp=sharing) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 16 pages  \[final, last read done, code ok\]  

10. [模型上下文协议 (MCP)](Chapter%2010_%20Model%20Context%20Protocol%20(MCP).md)(16 页)

11. [Chapter 11: Goal Setting and Monitoring](https://docs.google.com/document/d/10ndlCB39BWjyFRWKpcoKib4vuPD1ojD-x0-ynMaf5uw/edit?tab=t.0) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 12 pages \[final, last read done, code ok\], **182**  

11. [目标设定与监控](Chapter%2011_%20Goal%20Setting%20and%20Monitoring.md)(12 页)

Part Three (Total: 34 pages)

## 第三部分:容错与扩展(34 页)

12. [Chapter 12: Exception Handling and Recovery](https://docs.google.com/document/d/1C07AuMur6-infwE0viCp4QtAy_wWI-uceFm6MaYHQGk/edit?tab=t.0#heading=h.m2kk4kdjt6ir) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 8 pages \[final,  last read done, code ok\]  

12. [异常处理与恢复](Chapter%2012_%20Exception%20Handling%20and%20Recovery.md)(8 页)

13. [Chapter 13: Human-in-the-Loop](https://docs.google.com/document/d/1ImOZcw6yeb7a-uRBMNP1VdovYfyip4IdsAcLu9yue-0/edit?usp=sharing) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 9 pages \[final, last read done, code ok\]  

13. [人机协同](Chapter%2013_%20Human-in-the-Loop.md)(9 页)

14. [Chapter 14: Knowledge Retrieval (RAG)](https://docs.google.com/document/d/1v96Oobio6xDOqbK8ejsXjmOc4Dp2uoLMo5_gfJgi-NE/edit?usp=sharing) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 17 pages \[final, last read done, code ok\], **216**  

14. [知识检索 (RAG)](Chapter%2014_%20Knowledge%20Retrieval%20(RAG).md)(17 页)

Part Four (Total: 114 pages)

## 第四部分:高级架构(114 页)

15. [Chapter 15: Inter-Agent Communication (A2A)](https://docs.google.com/document/d/1H6HmUYcy5kugt5gt7Kh2Zzb8C62d5pu36RsgMNDCX24/edit?usp=sharing) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 15 pages \[final, last read done, code ok\]  

15. [智能体间通信 (A2A)](Chapter%2015_%20Inter-Agent%20Communication%20(A2A).md)(15 页)

16. [Chapter 16: Resource-Aware Optimization](https://docs.google.com/document/d/1nAN58l6JjqEJHk43126uh7xgdEblCpcbsNUHXgtBmJQ/edit?usp=sharing) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 15 pages  \[final, last read done, code ok\]  

16. [资源感知优化](Chapter%2016_%20Resource-Aware%20Optimization.md)(15 页)

17. [Chapter 17: Reasoning Techniques](https://docs.google.com/document/d/1Yt1W_hLaC6ZNgJXfT4W6NrCL4TzNVdKOX50kgpHiIq4/edit?usp=sharing) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 24 pages \[final, last read done, code ok\]  

17. [推理技术](Chapter%2017_%20Reasoning%20Techniques.md)(24 页)

18. [Chapter 18: Guardrails/Safety Patterns](https://docs.google.com/document/d/1Gpc5af_okze1kprRLohP6-81e1KwL6HggjeLvxQyIuk/edit?usp=sharing) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 19 pages \[final, last read done, code ok\]  

18. [安全护栏模式](Chapter%2018_%20Guardrails_Safety%20Patterns.md)(19 页)

19. [Chapter 19: Evaluation and Monitoring](https://docs.google.com/document/d/1G3zOZM2ZOd0gUp5dy66FUjKMOcALh9l-JpvPxgGMm8w/edit?usp=sharing) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 18 pages \[final, last read done, code ok\]  

19. [评估与监控](Chapter%2019_%20Evaluation%20and%20Monitoring.md)(18 页)

20. [Chapter 20: Prioritization](https://docs.google.com/document/d/1qyXxGM2hNqW_qjXuBFxrEUeoYVO79BoW1ogKu1bfdCY/edit?usp=sharing) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 10 pages \[final, last read done, code ok \]  

20. [优先级管理](Chapter%2020_%20Prioritization.md)(10 页)

21. [Chapter 21: Exploration and Discovery](https://docs.google.com/document/d/1zeeMVTqjqRIli6G9MMWThhoQhvKqLOjJF2EHHUXLhdk/edit?usp=sharing) ([code](https://drive.google.com/drive/u/0/folders/1Y3U3IrYCiJ3E45Z8okR5eCg7OPnWQtPV)), 13 pages \[final, last read done, code ok\], **330**  

21. [探索与发现](Chapter%2021_%20Exploration%20and%20Discovery.md)(13 页)

Appendix (Total: 74 pages)

## 附录(74 页)

22. [Appendix A: Advanced Prompting Techniques](https://docs.google.com/document/d/1V7EKEWibOH6IhHD_PtbFZiml492-2191jDQCcTkhtTI/edit?usp=sharing), 28 pages \[final, last read done, code ok\]  

22. [高级提示技术](Appendix%20A_%20Advanced%20Prompting%20Techniques.md)(28 页)

23. [Appendix B - AI Agentic ….: From GUI to Real world environment](https://docs.google.com/document/d/11pma_tCoC7uZ2SFKjcR5KyI0_ooMGSoadI6f9mxG2I/edit?tab=t.0#heading=h.4bsgiycebw26), 6 pages \[final, last read done, code ok\]  

23. [AI 智能体交互:从 GUI 到真实世界](Appendix%20B%20-%20AI%20Agentic%20Interactions_%20From%20GUI%20to%20Real%20world%20environment.md)(6 页)

24. [Appendix C - Quick overview of Agentic Frameworks](https://docs.google.com/document/d/151rGsiEYOkXUcNDRus_N8TxxuvjoyTDViBhzt9z0Mfw/edit?tab=t.0#heading=h.8y2llpsk10ds), 8 pages \[final, last read done, code ok\] ,  

24. [智能体框架概览](Appendix%20C%20-%20Quick%20overview%20of%20Agentic%20Frameworks.md)(8 页)

25. [Appendix D - Building an Agent with AgentSpace (on-line only)](https://docs.google.com/document/d/1bDRJ8mKtLTeWNC-cGD0Cr8pEJQgJHNcjqz5ekloAjaE/edit?tab=t.0), 6 pages \[final, last read done, code ok\]  

25. [使用 AgentSpace 构建智能体](Appendix%20D%20-%20Building%20an%20Agent%20with%20AgentSpace%20(on-line%20only).md)(6 页)

26. [Appendix E - AI Agents on the CLI](http://docs.google.com/document/d/1W4znto0a8Ikajw5a4tEyRAaB2nJPJw_iFc4w4qNnjho/edit?tab=t.0#heading=h.6zaq0kvy131m) , 5 pages \[final, last read done, code ok\]  

26. [命令行 AI 智能体](Appendix%20E%20-%20AI%20Agents%20on%20the%20CLI.md)(5 页)

27. [Appendix F - Under the Hood: An Inside Look at the Agents' Reasoning Engines](https://docs.google.com/document/d/14q3fQ-FZmDgiughno_WLSILMWkURvUgR7mlGiFtvwd4/edit?tab=t.0), 14 pages \[final, read, code ok\],  

27. [智能体推理引擎剖析](Appendix%20F%20%20-%20Under%20the%20Hood_%20An%20Inside%20Look%20at%20the%20Agents'%20Reasoning%20Engines.md)(14 页)

28. [Appendix G -  Coding agents](https://docs.google.com/document/d/1tVyhgwrD4fu_D_pHUrwhNxoguRG3tLc1KObXFxrxE_s/edit?tab=t.0), 7 pages  **406**

28. [编程实现智能体](Appendix%20G%20-%20%20Coding%20agents.md)(7 页)

[Conclusion](https://docs.google.com/document/d/1NGzpg9VldtStb_7jRkXJYBaHFwPwJ7WN6ZcTr7dNSVA/edit?usp=sharing), 5 pages \[final, last read done\]

- [结论](Conclusion.md)(5 页)

[Glossary](https://docs.google.com/document/d/1_j_OdzeUALluBUO1GkZ48DsHbbDETiM_1G4farVLPnE/edit?usp=sharing), 4 pages  \[final, last read done\]

- [术语表](Glossary.md)(4 页)

[Index of Terms](https://docs.google.com/document/d/15MrpoJBrZIi6aEZrBJCeCvVsIoC-EecYG9EWVk3YCKw/edit?tab=t.0), 11 pages  (*Generated by Gemini. Reasoning step included as an agentic example*) \[final, read\]

- [术语索引](Index%20of%20Terms.md)(11 页,含智能体推理示例)

[Online Contribution - Frequently Asked Questions: Agentic Design Patterns](https://docs.google.com/document/d/1XxQsHX3FWEP3TisQeWZwFfYw81zDwEHfHdIfjypa_0g/edit?tab=t.0)

- [常见问题解答](Frequently%20Asked%20Questions_%20Agentic%20Design%20Patterns.md)

**Pre Print**: [https://www.amazon.com/Agentic-Design-Patterns-Hands-Intelligent/dp/3032014018/](https://www.amazon.com/Agentic-Design-Patterns-Hands-Intelligent/dp/3032014018/)

**预印本**:[https://www.amazon.com/Agentic-Design-Patterns-Hands-Intelligent/dp/3032014018/](https://www.amazon.com/Agentic-Design-Patterns-Hands-Intelligent/dp/3032014018/)  

![封面图][image1]

[^1]:  All my royalties will be donated to Save the Children

[^2]: 本书所有版税将捐赠给救助儿童会 (Save the Children)

[image1]: ../images/cover.png


## /bilingual/Appendix A_ Advanced Prompting Techniques.md

---
layout: bilingual
lang: bilingual
---

# Appendix A: Advanced Prompting Techniques

# 附录 A:高级提示技术

## Introduction to Prompting

## 提示技术简介

Prompting, the primary interface for interacting with language models, is the process of crafting inputs to guide the model towards generating a desired output. This involves structuring requests, providing relevant context, specifying the output format, and demonstrating expected response types. Well-designed prompts can maximize the potential of language models, resulting in accurate, relevant, and creative responses. In contrast, poorly designed prompts can lead to ambiguous, irrelevant, or erroneous outputs.

提示技术是与语言模型交互的核心方式,指通过精心设计输入来引导模型生成期望输出的过程。这包括构建请求结构、提供相关上下文、指定输出格式以及展示预期的响应模式。设计精良的提示能够充分发挥语言模型的潜力,产生准确、相关且富有创造性的响应。反之,设计不当的提示则可能导致模糊、不相关甚至错误的输出。

The objective of prompt engineering is to consistently elicit high-quality responses from language models. This requires understanding the capabilities and limitations of the models and effectively communicating intended goals. It involves developing expertise in communicating with AI by learning how to best instruct it.

提示工程的目标是从语言模型中持续获得高质量的输出。这需要深入理解模型的能力边界和局限性,并有效地传达预期目标。它涉及通过学习如何最优地指导 AI 来发展与 AI 沟通的专业技能。

This appendix details various prompting techniques that extend beyond basic interaction methods. It explores methodologies for structuring complex requests, enhancing the model's reasoning abilities, controlling output formats, and integrating external information. These techniques are applicable to building a range of applications, from simple chatbots to complex multi-agent systems, and can improve the performance and reliability of agentic applications.

本附录详细介绍了超越基础交互方法的各类提示技术。它探讨了构建复杂请求、增强模型推理能力、控制输出格式以及整合外部信息的方法论。这些技术适用于构建从简单聊天机器人到复杂多智能体的各类应用,能够显著提升 Agentic 应用的性能和可靠性。

Agentic patterns, the architectural structures for building intelligent systems, are detailed in the main chapters. These patterns define how agents plan, utilize tools, manage memory, and collaborate. The efficacy of these agentic systems is contingent upon their ability to interact meaningfully with language models.

Agentic 模式是构建智能系统的架构蓝图,在主要章节中已有详细阐述。这些模式定义了智能体如何规划、使用工具、管理记忆和协同工作。这些 Agentic 系统的效能最终取决于它们与语言模型进行有意义交互的能力。

## Core Prompting Principles

## 核心提示原则

Core Principles for Effective Prompting of Language Models:

与语言模型进行有效提示的核心原则:

Effective prompting rests on fundamental principles guiding communication with language models, applicable across various models and task complexities. Mastering these principles is essential for consistently generating useful and accurate responses.

有效的提示建立在与语言模型沟通的基本原则之上,这些原则适用于各种模型和任务复杂度。掌握这些原则对于持续生成有用且准确的响应至关重要。

**Clarity and Specificity**: Instructions should be unambiguous and precise. Language models interpret patterns; multiple interpretations may lead to unintended responses. Define the task, desired output format, and any limitations or requirements. Avoid vague language or assumptions. Inadequate prompts yield ambiguous and inaccurate responses, hindering meaningful output.

**清晰性与具体性**:指令应当明确无误且精确。语言模型基于模式进行推理;多重解释可能导致意外结果。需要明确定义任务、期望的输出格式以及任何限制或要求。避免使用模糊语言或做出假设。不充分的提示会产生模糊和不准确的响应,影响输出质量。

**Conciseness**: While specificity is crucial, it should not compromise conciseness. Instructions should be direct. Unnecessary wording or complex sentence structures can confuse the model or obscure the primary instruction. Prompts should be simple; what is confusing to the user is likely confusing to the model. Avoid intricate language and superfluous information. Use direct phrasing and active verbs to clearly delineate the desired action. Effective verbs include: Act, Analyze, Categorize, Classify, Contrast, Compare, Create, Describe, Define, Evaluate, Extract, Find, Generate, Identify, List, Measure, Organize, Parse, Pick, Predict, Provide, Rank, Recommend, Return, Retrieve, Rewrite, Select, Show, Sort, Summarize, Translate, Write.

**简洁性**:在确保具体性的同时,必须保持简洁。指令应当直截了当。不必要的措辞或复杂的句子结构可能混淆模型或掩盖核心指令。提示应当简单明了:对用户而言困惑的内容,对模型同样可能造成困惑。避免使用复杂语言和冗余信息。采用直接表达和主动动词来清晰界定期望操作。有效的动词包括:执行、分析、分类、归类、对比、比较、创建、描述、定义、评估、提取、查找、生成、识别、列出、测量、组织、解析、挑选、预测、提供、排序、推荐、返回、检索、重写、选择、显示、整理、总结、翻译、编写。

**Using Verbs:** Verb choice is a key prompting tool. Action verbs indicate the expected operation. Instead of "Think about summarizing this," a direct instruction like "Summarize the following text" is more effective. Precise verbs guide the model to activate relevant training data and processes for that specific task.

**善用动词**:动词选择是提示工程的关键技巧。动作动词明确指示期望的操作。与其说"考虑总结这个",不如直接使用"总结以下文本"这样的指令更为有效。精确的动词能够引导模型激活与特定任务相关的训练数据和流程。

**Instructions Over Constraints:** Positive instructions are generally more effective than negative constraints. Specifying the desired action is preferred to outlining what not to do. While constraints have their place for safety or strict formatting, excessive reliance can cause the model to focus on avoidance rather than the objective. Frame prompts to guide the model directly. Positive instructions align with human guidance preferences and reduce confusion.

**指令优于约束**:积极指令通常比消极约束更为有效。明确指定期望操作比罗列禁止事项效果更好。虽然约束在安全控制或严格格式要求中有其价值,但过度依赖可能使模型过度关注规避而非目标达成。构建提示时应直接引导模型。积极指令更符合人类指导习惯,并能减少混淆。

**Experimentation and Iteration:** Prompt engineering is an iterative process. Identifying the most effective prompt requires multiple attempts. Begin with a draft, test it, analyze the output, identify shortcomings, and refine the prompt. Model variations, configurations (like temperature or top-p), and slight phrasing changes can yield different results. Documenting attempts is vital for learning and improvement. Experimentation and iteration are necessary to achieve the desired performance.

**实验与迭代**:提示工程是一个迭代过程。找到最有效的提示需要多次尝试。从初步设计开始,进行测试,分析输出,识别不足,然后优化提示。模型变体、配置参数(如温度或 top-p)以及细微的措辞变化都可能产生不同结果。记录实验过程对于学习和改进至关重要。实验和迭代是实现预期性能的必要手段。

These principles form the foundation of effective communication with language models. By prioritizing clarity, conciseness, action verbs, positive instructions, and iteration, a robust framework is established for applying more advanced prompting techniques.

这些原则构成了与语言模型有效沟通的基础。通过优先考虑清晰性、简洁性、善用动词、积极指令和迭代流程,为应用更高级提示技术奠定了坚实基础。

## Basic Prompting Techniques

## 基础提示技术

Building on core principles, foundational techniques provide language models with varying levels of information or examples to direct their responses. These methods serve as an initial phase in prompt engineering and are effective for a wide spectrum of applications.

基于核心原则,基础技术为语言模型提供不同层次的信息或示例来引导其响应。这些方法作为提示工程的入门阶段,适用于广泛的应用场景。

## Zero-Shot Prompting

## 零样本提示(Zero-Shot)

Zero-shot prompting is the most basic form of prompting, where the language model is provided with an instruction and input data without any examples of the desired input-output pair. It relies entirely on the model's pre-training to understand the task and generate a relevant response. Essentially, a zero-shot prompt consists of a task description and initial text to begin the process.

零样本提示是最基础的提示形式,语言模型仅接收指令和输入数据,不提供任何期望的输入-输出对示例。它完全依赖模型的预训练知识来理解任务并生成相关响应。本质上,零样本提示包含任务描述和启动过程的初始文本。

* **When to use:** Zero-shot prompting is often sufficient for tasks that the model has likely encountered extensively during its training, such as simple question answering, text completion, or basic summarization of straightforward text. It's the quickest approach to try first.  
* **Example:**  
  Translate the following English sentence to French: 'Hello, how are you?'

* **适用场景**:零样本提示通常适用于模型在训练过程中可能广泛接触的任务,例如简单问答、文本补全或基础文本摘要。这是最快捷的初步尝试方法。
* **示例**:
  将以下英文句子翻译成法语:'Hello, how are you?'

## One-Shot Prompting

## 单样本提示(One-Shot)

One-shot prompting involves providing the language model with a single example of the input and the corresponding desired output prior to presenting the actual task. This method serves as an initial demonstration to illustrate the pattern the model is expected to replicate. The purpose is to equip the model with a concrete instance that it can use as a template to effectively execute the given task.

单样本提示在呈现实际任务前,向语言模型提供一个输入及其对应期望输出的示例。这种方法作为初始演示,展示模型应遵循的模式。目的是为模型提供具体实例,使其能够作为模板有效执行给定任务。

* **When to use:** One-shot prompting is useful when the desired output format or style is specific or less common. It gives the model a concrete instance to learn from. It can improve performance compared to zero-shot for tasks requiring a particular structure or tone.  
* **Example:**  
  Translate the following English sentences to Spanish:  
  English: 'Thank you.'  
  Spanish: 'Gracias.'

  English: 'Please.'  
  Spanish:

* **适用场景**:当期望的输出格式或风格较为特殊或不常见时,单样本提示十分有用。它为模型提供了具体的学习范例。相比零样本,它能提升需要特定结构或语气任务的性能。
* **示例**:
  将以下英文句子翻译成西班牙语:
  英文:'Thank you.'
  西班牙语:'Gracias.'

  英文:'Please.'
  西班牙语:

## Few-Shot Prompting

## 少样本提示(Few-Shot)

Few-shot prompting enhances one-shot prompting by supplying several examples, typically three to five, of input-output pairs. This aims to demonstrate a clearer pattern of expected responses, improving the likelihood that the model will replicate this pattern for new inputs. This method provides multiple examples to guide the model to follow a specific output pattern.

少样本提示在单样本基础上增强,提供多个(通常三到五个)输入-输出对示例。这旨在展示更清晰的预期响应模式,提高模型为新输入复制该模式的可能性。此方法通过多个示例引导模型遵循特定输出模式。

* **When to use:** Few-shot prompting is particularly effective for tasks where the desired output requires adhering to a specific format, style, or exhibiting nuanced variations. It's excellent for tasks like classification, data extraction with specific schemas, or generating text in a particular style, especially when zero-shot or one-shot don't yield consistent results. Using at least three to five examples is a general rule of thumb, adjusting based on task complexity and model token limits.  
* **Importance of Example Quality and Diversity:** The effectiveness of few-shot prompting heavily relies on the quality and diversity of the examples provided. Examples should be accurate, representative of the task, and cover potential variations or edge cases the model might encounter. High-quality, well-written examples are crucial; even a small mistake can confuse the model and result in undesired output. Including diverse examples helps the model generalize better to unseen inputs.  
* **Mixing Up Classes in Classification Examples:** When using few-shot prompting for classification tasks (where the model needs to categorize input into predefined classes), it's a best practice to mix up the order of the examples from different classes. This prevents the model from potentially overfitting to the specific sequence of examples and ensures it learns to identify the key features of each class independently, leading to more robust and generalizable performance on unseen data.  
* **Evolution to "Many-Shot" Learning:** As modern LLMs like Gemini get stronger with long context modeling, they are becoming highly effective at utilizing "many-shot" learning. This means optimal performance for complex tasks can now be achieved by including a much larger number of examples—sometimes even hundreds—directly within the prompt, allowing the model to learn more intricate patterns.  
* **Example:**  
  Classify the sentiment of the following movie reviews as POSITIVE, NEUTRAL, or NEGATIVE:

   Review: "The acting was superb and the story was engaging."  
   Sentiment: POSITIVE

   Review: "It was okay, nothing special."  
   Sentiment: NEUTRAL

   Review: "I found the plot confusing and the characters unlikable."  
   Sentiment: NEGATIVE

   Review: "The visuals were stunning, but the dialogue was weak."  
   Sentiment:

Understanding when to apply zero-shot, one-shot, and few-shot prompting techniques, and thoughtfully crafting and organizing examples, are essential for enhancing the effectiveness of agentic systems. These basic methods serve as the groundwork for various prompting strategies.

理解何时应用零样本、单样本和少样本提示技术,并精心设计和组织示例,对于提升 Agentic 系统的效能至关重要。这些基础方法为各种提示策略奠定了根基。

## Structuring Prompts

## 提示结构设计

Beyond the basic techniques of providing examples, the way you structure your prompt plays a critical role in guiding the language model. Structuring involves using different sections or elements within the prompt to provide distinct types of information, such as instructions, context, or examples, in a clear and organized manner. This helps the model parse the prompt correctly and understand the specific role of each piece of text.

除了提供示例的基础技术外,提示的结构化方式在引导语言模型方面起着关键作用。结构化涉及在提示中使用不同部分或元素,以清晰有序的方式提供指令、上下文或示例等不同类型的信息。这有助于模型正确解析提示,理解每段文本的特定角色。

## System Prompting

## 系统提示

System prompting sets the overall context and purpose for a language model, defining its intended behavior for an interaction or session. This involves providing instructions or background information that establish rules, a persona, or overall behavior. Unlike specific user queries, a system prompt provides foundational guidelines for the model's responses. It influences the model's tone, style, and general approach throughout the interaction. For example, a system prompt can instruct the model to consistently respond concisely and helpfully or ensure responses are appropriate for a general audience. System prompts are also utilized for safety and toxicity control by including guidelines such as maintaining respectful language.

系统提示为语言模型设定整体上下文和目的,定义其在交互或会话中的预期行为。这涉及提供建立规则、角色或整体行为的指令或背景信息。与具体的用户查询不同,系统提示为模型的响应提供基础指导。它影响模型在整个交互过程中的语气、风格和总体方法。例如,系统提示可指示模型始终保持简洁有益的响应,或确保输出适合普通受众。系统提示还用于安全和内容控制,包含保持尊重语言等指导原则。

Furthermore, to maximize their effectiveness, system prompts can undergo automatic prompt optimization through LLM-based iterative refinement. Services like the Vertex AI Prompt Optimizer facilitate this by systematically improving prompts based on user-defined metrics and target data, ensuring the highest possible performance for a given task.

此外,为最大化其效果,系统提示可通过基于 LLM 的迭代改进进行自动优化。Vertex AI Prompt Optimizer 等服务通过根据用户定义的指标和目标数据系统性地优化提示来促进这一过程,确保特定任务的最佳性能。

* **Example:**  
  You are a helpful and harmless AI assistant. Respond to all queries in a polite and informative manner. Do not generate content that is harmful, biased, or inappropriate

* **示例**:
  你是一个乐于助人且无害的 AI 助手。以礼貌且信息丰富的方式回应所有查询。不要生成有害、有偏见或不适当的内容。

## Role Prompting

## 角色提示

Role prompting assigns a specific character, persona, or identity to the language model, often in conjunction with system or contextual prompting. This involves instructing the model to adopt the knowledge, tone, and communication style associated with that role. For example, prompts such as "Act as a travel guide" or "You are an expert data analyst" guide the model to reflect the perspective and expertise of that assigned role. Defining a role provides a framework for the tone, style, and focused expertise, aiming to enhance the quality and relevance of the output. The desired style within the role can also be specified, for instance, "a humorous and inspirational style."

角色提示为语言模型分配特定角色、身份或专业背景,通常与系统或上下文提示结合使用。这涉及指示模型采用与该角色相关的知识、语气和沟通风格。例如,"扮演旅游指南"或"你是一位专业数据分析师"等提示引导模型体现所分配角色的视角和专长。定义角色为语气、风格和专业焦点提供框架,旨在提升输出的质量和相关性。还可指定角色内的期望风格,如"幽默且鼓舞人心的风格"。

* **Example:**  
  Act as a seasoned travel blogger. Write a short, engaging paragraph about the best hidden gem in Rome.

* **示例**:
  扮演一位经验丰富的旅行博主。写一段简短且引人入胜的文字,介绍罗马最佳隐藏景点。

## Using Delimiters

## 使用分隔符

Effective prompting involves clear distinction of instructions, context, examples, and input for language models. Delimiters, such as triple backticks (```), XML tags (<instruction>, <context>), or markers (---), can be utilized to visually and programmatically separate these sections. This practice, widely used in prompt engineering, minimizes misinterpretation by the model, ensuring clarity regarding the role of each part of the prompt.

有效的提示需要为语言模型清晰区分指令、上下文、示例和输入。可使用分隔符,如三重反引号(```)、XML 标签(<instruction>、<context>)或标记(---),在视觉和程序上分隔这些部分。这种在提示工程中广泛采用的做法,通过明确提示各部分的角色,最小化模型的误解。

* **Example:**  
  <instruction>Summarize the following article, focusing on the main arguments presented by the author.</instruction>  
  <article>  
  [Insert the full text of the article here]  
  </article>

* **示例**:
  <instruction>总结以下文章,重点关注作者提出的主要论点。</instruction>
  <article>
  [在此插入文章全文]
  </article>

## Contextual Engineering

## 上下文工程

Context engineering, unlike static system prompts, dynamically provides background information crucial for tasks and conversations. This ever-changing information helps models grasp nuances, recall past interactions, and integrate relevant details, leading to grounded responses and smoother exchanges. Examples include previous dialogue, relevant documents (as in Retrieval Augmented Generation), or specific operational parameters. For instance, when discussing a trip to Japan, one might ask for three family-friendly activities in Tokyo, leveraging the existing conversational context. In agentic systems, context engineering is fundamental to core agent behaviors like memory persistence, decision-making, and coordination across sub-tasks. Agents with dynamic contextual pipelines can sustain goals over time, adapt strategies, and collaborate seamlessly with other agents or tools—qualities essential for long-term autonomy. This methodology posits that the quality of a model's output depends more on the richness of the provided context than on the model's architecture. It signifies a significant evolution from traditional prompt engineering, which primarily focused on optimizing the phrasing of immediate user queries. Context engineering expands its scope to include multiple layers of information.

上下文工程与静态系统提示不同,它动态提供对任务和对话至关重要的背景信息。这种持续变化的信息帮助模型理解细微差别、回忆过往交互并整合相关细节,从而产生有根据的响应和更流畅的交流。示例包括先前对话、相关文档(如在检索增强生成中)或特定操作参数。例如,在讨论日本旅行时,可请求提供东京的三个适合家庭的活动,利用现有对话上下文。在 Agentic 系统中,上下文工程是核心智能体能力(如记忆持久性、决策制定和跨子任务协调)的基础。具备动态上下文管道的智能体能够维持目标、调整策略,并与其他智能体或人类协作——这些是实现长期自主性的关键特质。该方法论认为,模型输出的质量更多取决于所提供上下文的丰富度,而非模型架构本身。它标志着从传统提示工程的重大演进,传统提示工程主要聚焦于优化直接用户查询的措辞。上下文工程将其范畴扩展至包含多层信息。

These layers include:

这些层次包括:

* **System prompts:** Foundational instructions that define the AI's operational parameters (e.g., "You are a technical writer; your tone must be formal and precise").  
* **External data:**  
  * **Retrieved documents:** Information actively fetched from a knowledge base to inform responses (e.g., pulling technical specifications).  
  * **Tool outputs:** Results from the AI using an external API for real-time data (e.g., querying a calendar for availability).  
* **Implicit data:** Critical information such as user identity, interaction history, and environmental state. Incorporating implicit context presents challenges related to privacy and ethical data management. Therefore, robust governance is essential for context engineering, especially in sectors like enterprise, healthcare, and finance.

* **系统提示**:定义 AI 操作参数的基础指令(例如,"你是技术文档作者;语气必须正式且精确")。
* **外部数据**:
  * **检索文档**:从知识库主动获取以支撑响应的信息(例如,提取技术规格)。
  * **工具输出**:AI 使用外部 API 获取实时数据的结果(例如,查询日历获取可用性)。
* **隐式数据**:关键信息,如用户身份、交互历史和环境状态。整合隐式上下文面临与隐私和道德数据管理相关的挑战。因此,强大的治理机制对上下文工程至关重要,尤其是在企业、医疗和金融等领域。

The core principle is that even advanced models underperform with a limited or poorly constructed view of their operational environment. This practice reframes the task from merely answering a question to building a comprehensive operational picture for the agent. For example, a context-engineered agent would integrate a user's calendar availability (tool output), the professional relationship with an email recipient (implicit data), and notes from previous meetings (retrieved documents) before responding to a query. This enables the model to generate highly relevant, personalized, and pragmatically useful outputs. The "engineering" aspect involves creating robust pipelines to fetch and transform this data at runtime and establishing feedback loops to continually improve context quality.

核心原则是,即使是先进模型,若对其操作环境的认知有限或构建不当,表现也会欠佳。这种做法将任务从单纯回答问题重新定义为为智能体构建全面的操作图景。例如,一个经过上下文工程设计的智能体在回复用户查询前,会整合用户的日历可用性(工具输出)、与邮件收件人的专业关系(隐式数据)以及过往会议记录(检索文档)。这使得模型能够生成高度相关、个性化且实用的输出。"工程"方面涉及构建稳健的管道以在运行时获取和转换这些数据,并建立反馈循环以持续提升上下文质量。

To implement this, specialized tuning systems, such as Google's Vertex AI prompt optimizer, can automate the improvement process at scale. By systematically evaluating responses against sample inputs and predefined metrics, these tools can enhance model performance and adapt prompts and system instructions across different models without extensive manual rewriting. Providing an optimizer with sample prompts, system instructions, and a template allows it to programmatically refine contextual inputs, offering a structured method for implementing the necessary feedback loops for sophisticated Context Engineering.  
This structured approach differentiates a rudimentary AI tool from a more sophisticated, contextually-aware system. It treats context as a primary component, emphasizing what the agent knows, when it knows it, and how it uses that information. This practice ensures the model has a well-rounded understanding of the user's intent, history, and current environment. Ultimately, Context Engineering is a crucial methodology for transforming stateless chatbots into highly capable, situationally-aware systems.

为实现这一点,专门的调优系统(如 Google 的 Vertex AI prompt optimizer)可大规模自动化改进过程。通过基于样本输入和预定义指标系统评估响应,这些工具能提升模型性能,并在不同模型间调整提示和系统指令,无需大量手动重写。为优化器提供样本提示、系统指令和模板,使其能程序化地优化上下文输入,为实施复杂上下文工程所需的反馈循环提供结构化方法。

这种结构化方法将基础 AI 工具与更复杂的情境感知系统区分开来。它将上下文视为核心要素,强调智能体知晓什么、何时知晓以及如何运用这些信息。这种做法确保模型对用户的意图、历史和当前环境有全面理解。最终,上下文工程是将无状态聊天机器人转变为高能力情境感知系统的关键方法论。

## Structured Output

## 结构化输出

Often, the goal of prompting is not just to get a free-form text response, but to extract or generate information in a specific, machine-readable format. Requesting structured output, such as JSON, XML, CSV, or Markdown tables, is a crucial structuring technique. By explicitly asking for the output in a particular format and potentially providing a schema or example of the desired structure, you guide the model to organize its response in a way that can be easily parsed and used by other parts of your agentic system or application. Returning JSON objects for data extraction is beneficial as it forces the model to create a structure and can limit hallucinations. Experimenting with output formats is recommended, especially for non-creative tasks like extracting or categorizing data.

通常,提示的目标不仅是获得自由形式的文本响应,而是以特定机器可读格式提取或生成信息。请求结构化输出(如 JSON、XML、CSV 或 Markdown 表格)是一项关键的结构化技术。通过明确要求特定格式输出并可能提供期望结构的模式或示例,您可以引导模型以易于被 Agentic 系统或其他应用组件解析和使用的方式组织响应。返回 JSON 对象进行数据提取的优势在于强制模型创建结构,从而限制幻觉产生。建议尝试不同输出格式,特别是对于数据提取或分类等非创意任务。

* **Example:**  
  Extract the following information from the text below and return it as a JSON object with keys "name", "address", and "phone_number".

  Text: "Contact John Smith at 123 Main St, Anytown, CA or call (555) 123-4567."

* **示例**:
  从以下文本中提取信息,并以包含 "name"、"address" 和 "phone_number" 键的 JSON 对象形式返回。

  文本:"联系 John Smith,地址:123 Main St, Anytown, CA,或致电 (555) 123-4567。"

Effectively utilizing system prompts, role assignments, contextual information, delimiters, and structured output significantly enhances the clarity, control, and utility of interactions with language models, providing a strong foundation for developing reliable agentic systems. Requesting structured output is crucial for creating pipelines where the language model's output serves as the input for subsequent system or processing steps.

有效利用系统提示、角色分配、上下文信息、分隔符和结构化输出,显著提升了与语言模型交互的清晰度、控制力和实用性,为构建可靠的 Agentic 系统奠定了坚实基础。请求结构化输出对于创建管道至关重要,其中语言模型的输出将作为后续系统或处理步骤的输入。

**Leveraging Pydantic for an Object-Oriented Facade:** A powerful technique for enforcing structured output and enhancing interoperability is to use the LLM's generated data to populate instances of Pydantic objects. Pydantic is a Python library for data validation and settings management using Python type annotations. By defining a Pydantic model, you create a clear and enforceable schema for your desired data structure. This approach effectively provides an object-oriented facade to the prompt's output, transforming raw text or semi-structured data into validated, type-hinted Python objects.

**利用 Pydantic 实现面向对象封装**:强制执行结构化输出和增强互操作性的强大技术是使用 LLM 生成的数据填充 Pydantic 对象实例。Pydantic 是一个使用 Python 类型注解进行数据验证和设置管理的 Python 库。通过定义 Pydantic 模型,您可以为期望的数据结构创建清晰且可强制执行的模式。这种方法有效地为提示输出提供了面向对象的封装,将原始文本或半结构化数据转换为经过验证的、类型提示的 Python 对象。

You can directly parse a JSON string from an LLM into a Pydantic object using the model_validate_json method. This is particularly useful as it combines parsing and validation in a single step.

您可以使用 model_validate_json 方法直接将来自 LLM 的 JSON 字符串解析为 Pydantic 对象。这特别高效,因为它在一个步骤中同时完成解析和验证。

```python
from pydantic import BaseModel, EmailStr, Field, ValidationError
from typing import List, Optional
from datetime import date

# --- Pydantic Model Definition (from above) ---
class User(BaseModel):
    name: str = Field(..., description="The full name of the user.")
    email: EmailStr = Field(..., description="The user's email address.")
    date_of_birth: Optional[date] = Field(None, description="The user's date of birth.")
    interests: List[str] = Field(default_factory=list, description="A list of the user's interests.")

# --- Hypothetical LLM Output ---
llm_output_json = """
{
    "name": "Alice Wonderland",
    "email": "alice.w@example.com",
    "date_of_birth": "1995-07-21",
    "interests": [
        "Natural Language Processing",
        "Python Programming",
        "Gardening"
    ]
}
"""

# --- Parsing and Validation ---
try:
    # Use the model_validate_json class method to parse the JSON string.
    # This single step parses the JSON and validates the data against the User model.
    user_object = User.model_validate_json(llm_output_json)
    # Now you can work with a clean, type-safe Python object.
    print("Successfully created User object!")
    print(f"Name: {user_object.name}")
    print(f"Email: {user_object.email}")
    print(f"Date of Birth: {user_object.date_of_birth}")
    print(f"First Interest: {user_object.interests[0]}")
    # You can access the data like any other Python object attribute.
    # Pydantic has already converted the 'date_of_birth' string to a datetime.date object.
    print(f"Type of date_of_birth: {type(user_object.date_of_birth)}")
except ValidationError as e:
    # If the JSON is malformed or the data doesn't match the model's types,
    # Pydantic will raise a ValidationError.
    print("Failed to validate JSON from LLM.")
    print(e)
```

This Python code demonstrates how to use the Pydantic library to define a data model and validate JSON data. It defines a User model with fields for name, email, date of birth, and interests, including type hints and descriptions. The code then parses a hypothetical JSON output from a Large Language Model (LLM) using the model_validate_json method of the User model. This method handles both JSON parsing and data validation according to the model's structure and types. Finally, the code accesses the validated data from the resulting Python object and includes error handling for ValidationError in case the JSON is invalid.

这段 Python 代码演示了如何使用 Pydantic 库定义数据模型并验证 JSON 数据。它定义了一个包含姓名、电子邮件、出生日期和兴趣字段的 User 模型,附带类型提示和描述。代码随后使用 User 模型的 model_validate_json 方法解析来自大型语言模型(LLM)的假设 JSON 输出。该方法根据模型结构和类型要求处理 JSON 解析和数据验证。最后,代码从生成的 Python 对象中访问已验证数据,并包含 ValidationError 的异常处理,以应对 JSON 无效的情况。

For XML data, the xmltodict library can be used to convert the XML into a dictionary, which can then be passed to a Pydantic model for parsing. By using Field aliases in your Pydantic model, you can seamlessly map the often verbose or attribute-heavy structure of XML to your object's fields.

对于 XML 数据,可使用 xmltodict 库将 XML 转换为字典,然后传递给 Pydantic 模型进行解析。通过在 Pydantic 模型中使用 Field 别名,可以无缝地将通常冗长或属性密集的 XML 结构映射到对象的字段。

This methodology is invaluable for ensuring the interoperability of LLM-based components with other parts of a larger system. When an LLM's output is encapsulated within a Pydantic object, it can be reliably passed to other functions, APIs, or data processing pipelines with the assurance that the data conforms to the expected structure and types. This practice of "parse, don't validate" at the boundaries of your system components leads to more robust and maintainable applications.

## Reasoning and Thought Process Techniques

## 推理与思维过程技术

Large language models excel at pattern recognition and text generation but often face challenges with tasks requiring complex, multi-step reasoning. This appendix focuses on techniques designed to enhance these reasoning capabilities by encouraging models to reveal their internal thought processes. Specifically, it addresses methods to improve logical deduction, mathematical computation, and planning.

大型语言模型擅长模式识别和文本生成,但在需要复杂多步骤推理的任务中常常面临挑战。本附录重点介绍旨在通过鼓励模型揭示其内部思维过程来增强推理能力的技术。具体而言,它探讨了改进逻辑推演、数学计算和规划的方法。

## Chain of Thought (CoT)

## 思维链(Chain of Thought, CoT)

The Chain of Thought (CoT) prompting technique is a powerful method for improving the reasoning abilities of language models by explicitly prompting the model to generate intermediate reasoning steps before arriving at a final answer. Instead of just asking for the result, you instruct the model to "think step by step." This process mirrors how a human might break down a problem into smaller, more manageable parts and work through them sequentially.

思维链(CoT)提示技术是一种强大方法,通过明确提示模型在得出最终答案前生成中间推理步骤来提高语言模型的推理能力。您不仅是要求结果,而是指示模型"逐步思考"。这一过程模拟了人类如何将问题分解为更小、更易管理的部分并按顺序处理。

CoT helps the LLM generate more accurate answers, particularly for tasks that require some form of calculation or logical deduction, where models might otherwise struggle and produce incorrect results. By generating these intermediate steps, the model is more likely to stay on track and perform the necessary operations correctly.

CoT 帮助 LLM 生成更准确的答案,特别是对于需要计算或逻辑推演的任务,这些任务中模型可能因直接得出结果而产生错误。通过生成中间步骤,模型更有可能保持正确方向并准确执行必要操作。

There are two main variations of CoT:

CoT 有两个主要变体:

* **Zero-Shot CoT:** This involves simply adding the phrase "Let's think step by step" (or similar phrasing) to your prompt without providing any examples of the reasoning process. Surprisingly, for many tasks, this simple addition can significantly improve the model's performance by triggering its ability to expose its internal reasoning trace.  
  * **Example (Zero-Shot CoT):**  
    If a train travels at 60 miles per hour and covers a distance of 240 miles, how long did the journey take? Let's think step by step.

* **零样本思维链(Zero-Shot CoT)**:这涉及简单地在提示中添加"让我们逐步思考"(或类似措辞)的短语,不提供任何推理过程示例。令人惊讶的是,对于许多任务,这一简单添加能通过触发模型暴露内部推理轨迹的能力,显著提升其性能。
  * **示例(Zero-Shot CoT)**:
    如果火车以每小时 60 英里的速度行驶,覆盖 240 英里的距离,旅程耗时多久?让我们逐步思考。

* **Few-Shot CoT:** This combines CoT with few-shot prompting. You provide the model with several examples where both the input, the step-by-step reasoning process, and the final output are shown. This gives the model a clearer template for how to perform the reasoning and structure its response, often leading to even better results on more complex tasks compared to zero-shot CoT.  
  * **Example (Few-Shot CoT):**  
    Q: The sum of three consecutive integers is 36. What are the integers?  
    A: Let the first integer be x. The next consecutive integer is x+1, and the third is x+2. The sum is x + (x+1) + (x+2) = 3x + 3. We know the sum is 36, so 3x + 3 = 36. Subtract 3 from both sides: 3x = 33. Divide by 3: x = 11. The integers are 11, 11+1=12, and 11+2=13. The integers are 11, 12, and 13.

    Q: Sarah has 5 apples, and she buys 8 more. She eats 3 apples. How many apples does she have left? Let's think step by step.  
    A: Let's think step by step. Sarah starts with 5 apples. She buys 8 more, so she adds 8 to her initial amount: 5 + 8 = 13 apples. Then, she eats 3 apples, so we subtract 3 from the total: 13 - 3 = 10. Sarah has 10 apples left. The answer is 10.

* **少样本思维链(Few-Shot CoT)**:这结合了 CoT 与少样本提示。您向模型提供多个示例,展示输入、逐步推理过程和最终输出。这为模型提供了更清晰的模板,指导其如何执行推理和构建响应,通常在复杂任务上比零样本 CoT 产生更好结果。
  * **示例(Few-Shot CoT)**:
    问:三个连续整数的和是 36。这些整数是什么?
    答:设第一个整数为 x。下一个连续整数是 x+1,第三个是 x+2。和为 x + (x+1) + (x+2) = 3x + 3。已知和为 36,所以 3x + 3 = 36。两边减去 3:3x = 33。除以 3:x = 11。这些整数是 11、11+1=12 和 11+2=13。这些整数是 11、12 和 13。

    问:Sarah 有 5 个苹果,她又买了 8 个。她吃了 3 个苹果。她还剩多少苹果?让我们逐步思考。
    答:让我们逐步思考。Sarah 开始有 5 个苹果。她买了 8 个,所以她在初始数量上加 8:5 + 8 = 13 个苹果。然后,她吃了 3 个苹果,所以从总数中减去 3:13 - 3 = 10。Sarah 还剩 10 个苹果。答案是 10。

CoT offers several advantages. It is relatively low-effort to implement and can be highly effective with off-the-shelf LLMs without requiring fine-tuning. A significant benefit is the increased interpretability of the model's output; you can see the reasoning steps it followed, which helps in understanding why it arrived at a particular answer and in debugging if something went wrong. Additionally, CoT appears to improve the robustness of prompts across different versions of language models, meaning the performance is less likely to degrade when a model is updated. The main disadvantage is that generating the reasoning steps increases the length of the output, leading to higher token usage, which can increase costs and response time.

CoT 具有多个优势。它相对易于实施,且能在现成 LLM 上高效运行,无需微调。一个重要好处是模型输出的可解释性增强;您可以观察其遵循的推理步骤,这有助于理解其得出特定答案的原因,并在出现问题时进行调试。此外,CoT 似乎提升了提示在不同版本语言模型间的鲁棒性,意味着模型更新时性能不易下降。主要缺点是生成推理步骤会增加输出长度,导致更高的 token 使用量,可能增加成本和响应时间。

Best practices for CoT include ensuring the final answer is presented *after* the reasoning steps, as the generation of the reasoning influences the subsequent token predictions for the answer. Also, for tasks with a single correct answer (like mathematical problems), setting the model's temperature to 0 (greedy decoding) is recommended when using CoT to ensure deterministic selection of the most probable next token at each step.

CoT 的最佳实践包括确保最终答案在推理步骤*之后*呈现,因为推理生成会影响后续答案 token 的预测。此外,对于具有单一正确答案的任务(如数学问题),建议在使用 CoT 时将模型温度设置为 0(贪婪解码),以确保在每一步确定性地选择最可能的下一个 token。

## Self-Consistency

## 自洽性(Self-Consistency)

Building on the idea of Chain of Thought, the Self-Consistency technique aims to improve the reliability of reasoning by leveraging the probabilistic nature of language models. Instead of relying on a single greedy reasoning path (as in basic CoT), Self-Consistency generates multiple diverse reasoning paths for the same problem and then selects the most consistent answer among them.

基于思维链理念,自我一致性技术旨在通过利用语言模型的概率性质来提高推理可靠性。自我一致性不依赖单一贪婪推理路径(如基本 CoT),而是为同一问题生成多个不同推理路径,然后从中选择最一致的答案。

Self-Consistency involves three main steps:

自我一致性包含三个主要步骤:

1. **Generating Diverse Reasoning Paths:** The same prompt (often a CoT prompt) is sent to the LLM multiple times. By using a higher temperature setting, the model is encouraged to explore different reasoning approaches and generate varied step-by-step explanations.  
2. **Extract the Answer:** The final answer is extracted from each of the generated reasoning paths.  
3. **Choose the Most Common Answer:** A majority vote is performed on the extracted answers. The answer that appears most frequently across the diverse reasoning paths is selected as the final, most consistent answer.

1. **生成多样化推理路径**:将同一提示(通常是 CoT 提示)多次发送给 LLM。通过使用更高温度设置,鼓励模型探索不同推理方法并生成多样化逐步解释。
2. **提取答案**:从每个生成的推理路径中提取最终答案。
3. **选择最常出现的答案**:对提取的答案进行多数投票。在不同推理路径中出现最频繁的答案被选为最终、最一致的答案。

This approach improves the accuracy and coherence of responses, particularly for tasks where multiple valid reasoning paths might exist or where the model might be prone to errors in a single attempt. The benefit is a pseudo-probability likelihood of the answer being correct, increasing overall accuracy. However, the significant cost is the need to run the model multiple times for the same query, leading to much higher computation and expense.

这种方法提高了响应的准确性和连贯性,特别适用于可能存在多个有效推理路径或模型单次尝试易出错的任务。优势在于获得答案正确的伪概率可能性,从而提升整体准确性。然而,显著代价是需要为同一查询多次运行模型,导致计算成本和费用大幅增加。

* **Example (Conceptual):**  
  * *Prompt:* "Is the statement 'All birds can fly' true or false? Explain your reasoning."  
  * *Model Run 1 (High Temp):* Reasons about most birds flying, concludes True.  
  * *Model Run 2 (High Temp):* Reasons about penguins and ostriches, concludes False.  
  * *Model Run 3 (High Temp):* Reasons about birds *in general*, mentions exceptions briefly, concludes True.  
  * *Self-Consistency Result:* Based on majority vote (True appears twice), the final answer is "True". (Note: A more sophisticated approach would weigh the reasoning quality).

* **示例(概念性)**:
  * *提示*:"陈述'所有鸟类都能飞'是真还是假?解释你的推理。"
  * *模型运行 1(高温度)*:推理大多数鸟类会飞,结论为真。
  * *模型运行 2(高温度)*:考虑企鹅和鸵鸟等例外,结论为假。
  * *模型运行 3(高温度)*:讨论鸟类*一般*特性,简要提及例外,结论为真。
  * *自我一致性结果*:基于多数投票(真出现两次),最终答案为"真"。(注:更复杂的方法会权衡推理质量)。

## Step-Back Prompting

## 后退提示

Step-back prompting enhances reasoning by first asking the language model to consider a general principle or concept related to the task before addressing specific details. The response to this broader question is then used as context for solving the original problem.

后退提示通过首先要求语言模型考虑与任务相关的一般原则或概念来增强推理,然后再处理具体细节。对这一更广泛问题的响应随后用作解决原始问题的上下文。

This process allows the language model to activate relevant background knowledge and wider reasoning strategies. By focusing on underlying principles or higher-level abstractions, the model can generate more accurate and insightful answers, less influenced by superficial elements. Initially considering general factors can provide a stronger basis for generating specific creative outputs. Step-back prompting encourages critical thinking and the application of knowledge, potentially mitigating biases by emphasizing general principles.

此过程允许语言模型激活相关背景知识和更广泛的推理策略。通过关注基本原则或更高层次抽象,模型能生成更准确和富有洞察力的答案,减少受表面元素影响。初始考虑一般因素可为生成特定创意输出提供更强基础。后退提示鼓励批判性思维和知识应用,通过强调一般原则可能减轻偏见。

* **Example:**  
  * *Prompt 1 (Step-Back):* "What are the key factors that make a good detective story?"  
  * *Model Response 1:* (Lists elements like red herrings, compelling motive, flawed protagonist, logical clues, satisfying resolution).  
  * *Prompt 2 (Original Task + Step-Back Context):* "Using the key factors of a good detective story [insert Model Response 1 here], write a short plot summary for a new mystery novel set in a small town."

* **示例**:
  * *提示 1(后退)*:"优秀侦探故事的关键要素是什么?"
  * *模型响应 1*:(列出如红鲱鱼、令人信服的动机、有缺陷的主角、逻辑线索、令人满意的结局等要素)。
  * *提示 2(原始任务 + 后退上下文)*:"运用优秀侦探故事的关键要素[在此插入模型响应 1],为一部设定在小镇的新神秘小说撰写简短情节摘要。"

## Tree of Thoughts (ToT)

## 思维树(Tree of Thoughts, ToT)

Tree of Thoughts (ToT) is an advanced reasoning technique that extends the Chain of Thought method. It enables a language model to explore multiple reasoning paths concurrently, instead of following a single linear progression. This technique utilizes a tree structure, where each node represents a "thought"—a coherent language sequence acting as an intermediate step. From each node, the model can branch out, exploring alternative reasoning routes.

思维树(ToT)是一种高级推理技术,扩展了思维链方法。它使语言模型能够同时探索多个推理路径,而非遵循单一线性进程。此技术采用树状结构,其中每个节点代表一个"思维"——作为中间步骤的连贯语言序列。从每个节点,模型可分支探索替代推理路线。

ToT is particularly suited for complex problems that require exploration, backtracking, or the evaluation of multiple possibilities before arriving at a solution. While more computationally demanding and intricate to implement than the linear Chain of Thought method, ToT can achieve superior results on tasks necessitating deliberate and exploratory problem-solving. It allows an agent to consider diverse perspectives and potentially recover from initial errors by investigating alternative branches within the "thought tree."

ToT 特别适合需要探索、回溯或在得出解决方案前评估多种可能性的复杂问题。虽然比线性思维链方法计算要求更高且实现更复杂,但 ToT 能在需要深思熟虑和探索性问题解决的任务上取得更优结果。它允许智能体探索不同视角,并通过调查"思维树"中的替代分支从初始错误中恢复。

* **Example (Conceptual):** For a complex creative writing task like "Develop three different possible endings for a story based on these plot points," ToT would allow the model to explore distinct narrative branches from a key turning point, rather than just generating one linear continuation.

* **示例(概念性)**:对于像"基于这些情节点为故事构思三种不同可能结局"的复杂创意写作任务,ToT 将允许模型从关键转折点探索不同叙事分支,而非仅生成单一线性延续。

These reasoning and thought process techniques are crucial for building agents capable of handling tasks that go beyond simple information retrieval or text generation. By prompting models to expose their reasoning, consider multiple perspectives, or step back to general principles, we can significantly enhance their ability to perform complex cognitive tasks within agentic systems.

这些推理和思维过程技术对于构建能处理超越简单信息检索或文本生成任务的智能体至关重要。通过提示模型暴露推理、考虑多视角或后退至一般原则,我们能显著增强其在 Agentic 系统中执行复杂认知任务的能力。

## Action and Interaction Techniques

## 行动与交互技术

Intelligent agents possess the capability to actively engage with their environment, beyond generating text. This includes utilizing tools, executing external functions, and participating in iterative cycles of observation, reasoning, and action. This section examines prompting techniques designed to enable these active behaviors.

智能体具备主动与环境交互的能力,这超越了单纯的文本生成。这包括利用工具、执行外部函数以及参与观察、推理和行动的迭代循环。本节探讨旨在实现这些主动行为的提示技术。

## Tool Use / Function Calling

## 工具使用/工具调用

A crucial ability for an agent is using external tools or calling functions to perform actions beyond its internal capabilities. These actions may include web searches, database access, sending emails, performing calculations, or interacting with external APIs. Effective prompting for tool use involves designing prompts that instruct the model on the appropriate timing and methodology for tool utilization.

Agent 的关键能力之一是使用外部工具或调用函数来执行超出其内部能力范围的操作。这些操作可能包括网络搜索、数据库访问、发送电子邮件、执行计算或与外部 API 交互。有效的工具使用提示涉及设计能够指示模型在适当时机和方法下利用工具的指令。

Modern language models often undergo fine-tuning for "function calling" or "tool use." This enables them to interpret descriptions of available tools, including their purpose and parameters. Upon receiving a user request, the model can determine the necessity of tool use, identify the appropriate tool, and format the required arguments for its invocation. The model does not execute the tool directly. Instead, it generates a structured output, typically in JSON format, specifying the tool and its parameters. An agentic system then processes this output, executes the tool, and provides the tool's result back to the model, integrating it into the ongoing interaction.

现代语言模型通常经过"工具调用"或"工具使用"的专门微调。这使得它们能够理解可用工具的描述,包括其用途和参数。在接收到用户请求后,模型可以判断是否需要使用工具,识别合适的工具,并格式化调用所需的参数。模型本身并不直接执行工具,而是生成结构化输出(通常为 JSON 格式),指定要使用的工具及其参数。随后,Agentic 系统处理此输出,执行工具,并将工具结果返回给模型,将其整合到持续交互中。

* **Example:**  
  You have access to a weather tool that can get the current weather for a specified city. The tool is called 'get_current_weather' and takes a 'city' parameter (string).

  User: What's the weather like in London right now?

  * *Expected Model Output (Function Call):*  
    {  
      "tool_code": "get_current_weather",  
      "tool_name": "get_current_weather",  
      "parameters": {  
        "city": "London"  
      }  
    }

* **示例**:
  你可以访问一个天气工具,该工具可以获取指定城市的当前天气。该工具名为 'get_current_weather',接受一个 'city' 参数(字符串类型)。

  用户:伦敦现在的天气怎么样?

  * *预期模型输出(工具调用)*:
    {
      "tool_code": "get_current_weather",
      "tool_name": "get_current_weather",
      "parameters": {
        "city": "London"
      }
    }

## ReAct (Reason & Act)

## ReAct(推理与行动)

ReAct, short for Reason and Act, is a prompting paradigm that combines Chain of Thought-style reasoning with the ability to perform actions using tools in an interleaved manner. ReAct mimics how humans operate – we reason verbally and take actions to gather more information or make progress towards a goal.

ReAct 是"推理与行动"的缩写,是一种将思维链风格推理与使用工具执行操作交织结合的提示范式。ReAct 模拟人类的工作方式——我们通过口头推理并采取行动来收集更多信息或推进目标实现。

The ReAct pattern involves a loop:

ReAct 模式包含一个循环过程:

1. **Thought:** The model generates a thought process, explaining its current understanding and plan.  
2. **Action:** Based on the thought, the model decides to perform an action, often using a tool (e.g., Search, Calculator, API call). It outputs the name of the tool and the required input.  
3. **Observation:** The agentic system executes the tool and provides the result (Observation) back to the model.  
4. The loop continues with the model generating a new "Thought" based on the latest "Observation," leading to further "Actions" and "Observations" until the task is complete and the model outputs a "Final Answer."

1. **思考**:模型生成思维过程,阐述其当前理解和计划。
2. **行动**:基于思考,模型决定执行操作,通常涉及使用工具(如搜索、计算器、API 调用)。它输出工具名称和所需输入。
3. **观察**:Agentic 系统执行工具并将结果(观察)反馈给模型。
4. 循环继续,模型基于最新"观察"生成新的"思考",引发进一步的"行动"和"观察",直至任务完成,模型输出"最终答案"。

This interleaved process of thinking and acting allows the agent to dynamically gather information, react to tool outputs, and refine its approach, making it particularly effective for tasks requiring interaction with dynamic environments or external knowledge sources.

这种思考与行动的交错过程使智能体动态收集信息、响应工具输出并优化策略,特别适用于需要与动态环境或外部知识源交互的任务。

* **Example (Illustrative ReAct Trace):**  
  User: What is the capital of France and its current population?

  Thought: The user is asking for two pieces of information: the capital of France and its population. I can use a search tool to find this information. I will start by confirming the capital, although I am likely to know it.  
  Action: Search({"query": "capital of France"})  
  Observation: Paris

  Thought: Okay, the capital is Paris. Now I need to find the population of Paris.  
  Action: Search({"query": "current population of Paris"})  
  Observation: The population of Paris was estimated to be around 2.1 million people in 2023.

  Thought: I have found both pieces of information. I can now provide the final answer to the user.  
  Final Answer: The capital of France is Paris, and its estimated population in 2023 was around 2.1 million people.

* **示例(说明性 ReAct 轨迹)**:
  用户:法国的首都是什么?当前人口是多少?

  思考:用户询问两个信息:法国首都及其人口。我可以使用搜索工具查找这些信息。我将从确认首都开始,尽管我可能已经知道。
  行动:Search({"query": "capital of France"})
  观察:巴黎

  思考:好的,首都是巴黎。现在我需要查找巴黎的人口。
  行动:Search({"query": "current population of Paris"})
  观察:巴黎人口在 2023 年估计约为 210 万人。

  思考:我已找到两条信息。现在可以向用户提供最终答案。
  最终答案:法国的首都是巴黎,其 2023 年估计人口约为 210 万人。

These techniques are vital for building agents that can actively engage with the world, retrieve real-time information, and perform tasks that require interacting with external systems.

这些技术对于构建能够主动与世界互动、检索实时信息并执行需要与外部系统交互任务的智能体至关重要。

## Advanced Techniques

## 高级技术

Beyond the foundational, structural, and reasoning patterns, there are several other prompting techniques that can further enhance the capabilities and efficiency of agentic systems. These range from using AI to optimize prompts to incorporating external knowledge and tailoring responses based on user characteristics.

除了基础、结构和推理模式外,还有多种其他提示技术可以进一步提升 Agentic 系统的能力和效率。这些技术涵盖从使用 AI 优化提示到整合外部知识和基于用户特征定制响应等多个方面。

## Automatic Prompt Engineering (APE)

## 自动提示工程(APE)

Recognizing that crafting effective prompts can be a complex and iterative process, Automatic Prompt Engineering (APE) explores using language models themselves to generate, evaluate, and refine prompts. This method aims to automate the prompt writing process, potentially enhancing model performance without requiring extensive human effort in prompt design.

认识到制作有效提示可能是一个复杂且迭代的过程,自动提示工程(APE)探索使用语言模型本身来生成、评估和改进提示。这种方法旨在自动化提示编写过程,有可能在无需大量人工设计投入的情况下提升模型性能。

The general idea is to have a "meta-model" or a process that takes a task description and generates multiple candidate prompts. These prompts are then evaluated based on the quality of the output they produce on a given set of inputs (perhaps using metrics like BLEU or ROUGE, or human evaluation). The best-performing prompts can be selected, potentially refined further, and used for the target task. Using an LLM to generate variations of a user query for training a chatbot is an example of this.

基本思路是构建一个"元模型"或流程,该流程接收任务描述并生成多个候选提示。然后根据这些提示在给定输入集上产生的输出质量进行评估(可能使用 BLEU 或 ROUGE 等指标,或人工评估)。表现最佳的提示可以被选择,进一步优化后用于目标任务。使用 LLM 生成用户查询变体以训练聊天机器人就是此类应用的一个实例。

* **Example (Conceptual):** A developer provides a description: "I need a prompt that can extract the date and sender from an email." An APE system generates several candidate prompts. These are tested on sample emails, and the prompt that consistently extracts the correct information is selected.

* **示例(概念性)**:开发者提供描述:"我需要一个能从电子邮件中提取日期和发件人的提示。"APE 系统生成若干候选提示。这些提示在样本电子邮件上测试,最终选择能稳定提取正确信息的提示。

Of course. Here is a rephrased and slightly expanded explanation of programmatic prompt optimization using frameworks like DSPy:

当然。以下是使用 DSPy 等框架进行程序化提示优化的重新表述和适度扩展说明:

Another powerful prompt optimization technique, notably promoted by the DSPy framework, involves treating prompts not as static text but as programmatic modules that can be automatically optimized. This approach moves beyond manual trial-and-error and into a more systematic, data-driven methodology.

另一种强大的提示优化技术,尤其以 DSPy 框架为代表,将提示视为可自动优化的程序化模块,而非静态文本。这种方法超越了手动试错,进入了更系统化、数据驱动的方法论范畴。

The core of this technique relies on two key components:

该技术的核心依赖于两个关键组件:

1. **A Goldset (or High-Quality Dataset):** This is a representative set of high-quality input-and-output pairs. It serves as the "ground truth" that defines what a successful response looks like for a given task.  
2. **An Objective Function (or Scoring Metric):** This is a function that automatically evaluates the LLM's output against the corresponding "golden" output from the dataset. It returns a score indicating the quality, accuracy, or correctness of the response.

1. **金标准集(或高质量数据集)**:这是一组具有代表性的高质量输入-输出对。它作为"真实基准",定义了特定任务下成功响应应具备的特征。
2. **目标函数(或评分指标)**:这是一个自动评估 LLM 输出与数据集中对应"黄金"输出的函数。它返回一个分数,指示响应的质量、准确性或正确性。

Using these components, an optimizer, such as a Bayesian optimizer, systematically refines the prompt. This process typically involves two main strategies, which can be used independently or in concert:

利用这些组件,优化器(如贝叶斯优化器)系统性地改进提示。此过程通常涉及两种主要策略,可独立或协同使用:

* **Few-Shot Example Optimization:** Instead of a developer manually selecting examples for a few-shot prompt, the optimizer programmatically samples different combinations of examples from the goldset. It then tests these combinations to identify the specific set of examples that most effectively guides the model toward generating the desired outputs.

* **Few-Shot 示例优化**:优化器并非由开发者手动选择 few-shot 提示的示例,而是从金标准集中程序化地采样不同示例组合。随后测试这些组合,以识别最能有效引导模型生成期望输出的特定示例集合。

* **Instructional Prompt Optimization:** In this approach, the optimizer automatically refines the prompt's core instructions. It uses an LLM as a "meta-model" to iteratively mutate and rephrase the prompt's text—adjusting wording, tone, or structure—to discover which phrasing yields the highest scores from the objective function.

* **指令提示优化**:在此方法中,优化器自动优化提示的核心指令。它使用 LLM 作为"元模型"迭代地变异和重新表述提示文本——调整措辞、语气或结构——以发现能获得目标函数最高评分的表述方式。

The ultimate goal for both strategies is to maximize the scores from the objective function, effectively "training" the prompt to produce results that are consistently closer to the high-quality goldset. By combining these two approaches, the system can simultaneously optimize *what instructions* to give the model and *which examples* to show it, leading to a highly effective and robust prompt that is machine-optimized for the specific task.

两种策略的最终目标都是最大化目标函数的分数,实质上"训练"提示以产生与高质量金标准集持续接近的结果。通过结合这两种方法,系统能同时优化*给予模型的指令*和*展示给模型的示例*,从而获得为特定任务机器优化的高效且强大的提示。

## Iterative Prompting / Refinement

## 迭代提示/改进

This technique involves starting with a simple, basic prompt and then iteratively refining it based on the model's initial responses. If the model's output isn't quite right, you analyze the shortcomings and modify the prompt to address them. This is less about an automated process (like APE) and more about a human-driven iterative design loop.

此技术涉及从简单的基础提示开始,然后根据模型的初始响应迭代改进。如果模型输出不理想,您分析不足之处并修改提示以解决问题。这更侧重于人工驱动的迭代设计循环,而非自动化过程(如 APE)。

* **Example:**  
  * *Attempt 1:* "Write a product description for a new type of coffee maker." (Result is too generic).  
  * *Attempt 2:* "Write a product description for a new type of coffee maker. Highlight its speed and ease of cleaning." (Result is better, but lacks detail).  
  * *Attempt 3:* "Write a product description for the 'SpeedClean Coffee Pro'. Emphasize its ability to brew a pot in under 2 minutes and its self-cleaning cycle. Target busy professionals." (Result is much closer to desired).

* **示例**:
  * *尝试 1*:"为新型咖啡机撰写产品描述。"(结果过于泛泛)。
  * *尝试 2*:"为新型咖啡机撰写产品描述。突出其速度和清洁便利性。"(结果改善,但缺乏细节)。
  * *尝试 3*:"为'SpeedClean Coffee Pro'撰写产品描述。强调其在 2 分钟内冲泡一壶咖啡的能力及自清洁循环。目标受众为忙碌的专业人士。"(结果更接近期望)。

## Providing Negative Examples

## 提供负面示例

While the principle of "Instructions over Constraints" generally holds true, there are situations where providing negative examples can be helpful, albeit used carefully. A negative example shows the model an input and an *undesired* output, or an input and an output that *should not* be generated. This can help clarify boundaries or prevent specific types of incorrect responses.

尽管"指令优于约束"的原则普遍适用,但在某些情况下谨慎使用负面示例可能有所帮助。负面示例向模型展示输入与*不期望的*输出,或输入与*不应*生成的输出。这有助于明确边界或防止特定类型的错误响应。

* **Example:**  
  Generate a list of popular tourist attractions in Paris. Do NOT include the Eiffel Tower.

  Example of what NOT to do:  
  Input: List popular landmarks in Paris.  
  Output: The Eiffel Tower, The Louvre, Notre Dame Cathedral.

* **示例**:
  生成巴黎热门旅游景点列表。不要包含埃菲尔铁塔。

  不应采取的做法示例:
  输入:列出巴黎著名地标。
  输出:埃菲尔铁塔、卢浮宫、巴黎圣母院。

## Using Analogies

## 使用类比

Framing a task using an analogy can sometimes help the model understand the desired output or process by relating it to something familiar. This can be particularly useful for creative tasks or explaining complex roles.

通过类比来框定任务,有时能通过将任务与熟悉概念关联,帮助模型理解期望的输出或过程。这对创意任务或解释复杂角色尤为有用。

* **Example:**  
  Act as a "data chef". Take the raw ingredients (data points) and prepare a "summary dish" (report) that highlights the key flavors (trends) for a business audience.

* **示例**:
  扮演"数据厨师"角色。取用原始食材(数据点),为商务受众烹制一份"摘要菜肴"(报告),突出关键风味(趋势)。

## Factored Cognition / Decomposition

## 分解式认知/任务分解(Factored Cognition / Decomposition)

For very complex tasks, it can be effective to break down the overall goal into smaller, more manageable sub-tasks and prompt the model separately on each sub-task. The results from the sub-tasks are then combined to achieve the final outcome. This is related to prompt chaining and planning but emphasizes the deliberate decomposition of the problem.

对于极其复杂的任务,将总体目标分解为更小、更易管理的子任务,并对每个子任务分别提示模型,可能是有效的方法。子任务的结果随后被组合以实现最终成果。这与提示词链和规划相关,但强调对问题的深思熟虑分解。

* **Example:** To write a research paper:  
  * Prompt 1: "Generate a detailed outline for a paper on the impact of AI on the job market."  
  * Prompt 2: "Write the introduction section based on this outline: [insert outline intro]."  
  * Prompt 3: "Write the section on 'Impact on White-Collar Jobs' based on this outline: [insert outline section]." (Repeat for other sections).  
  * Prompt N: "Combine these sections and write a conclusion."

* **示例**:撰写研究论文:
  * 提示 1:"生成关于 AI 对就业市场影响的论文详细大纲。"
  * 提示 2:"基于此大纲撰写引言部分:[插入大纲引言]。"
  * 提示 3:"基于此大纲撰写'对白领工作的影响'部分:[插入大纲相关部分]。"(对其他部分重复此过程)。
  * 提示 N:"整合这些部分并撰写结论。"

## Retrieval Augmented Generation (RAG)

## 检索增强生成(RAG)

RAG is a powerful technique that enhances language models by giving them access to external, up-to-date, or domain-specific information during the prompting process. When a user asks a question, the system first retrieves relevant documents or data from a knowledge base (e.g., a database, a set of documents, the web). This retrieved information is then included in the prompt as context, allowing the language model to generate a response grounded in that external knowledge. This mitigates issues like hallucination and provides access to information the model wasn't trained on or that is very recent. This is a key pattern for agentic systems that need to work with dynamic or proprietary information.

RAG 是一种强大技术,通过在提示过程中赋予语言模型访问外部、最新或领域特定信息的能力来增强模型。当用户提出问题时,系统首先从知识库(如数据库、文档集、网络)检索相关文档或数据。随后将此检索信息作为上下文纳入提示,使语言模型能够基于此外部知识生成响应。这有助于缓解幻觉问题,并提供模型未训练过或非常新的信息访问途径。这是需要处理动态或专有信息的 Agentic 系统的关键模式。

* **Example:**  
  * *User Query:* "What are the new features in the latest version of the Python library 'X'?"  
  * *System Action:* Search a documentation database for "Python library X latest features".  
  * *Prompt to LLM:* "Based on the following documentation snippets: [insert retrieved text], explain the new features in the latest version of Python library 'X'."

* **示例**:
  * *用户查询*:"Python 库'X'最新版本有哪些新功能?"
  * *系统操作*:在文档数据库中搜索"Python 库 X 最新功能"。
  * *对 LLM 的提示*:"基于以下文档片段:[插入检索到的文本],解释 Python 库'X'最新版本的新功能。"

## Persona Pattern (User Persona):

## 用户画像模式

While role prompting assigns a persona to the *model*, the Persona Pattern involves describing the user or the target audience for the model's output. This helps the model tailor its response in terms of language, complexity, tone, and the kind of information it provides.

虽然角色提示为*模型*分配角色,用户画像模式则涉及描述用户或模型输出的目标受众。这有助于模型在语言、复杂度、语气和提供信息类型方面定制其响应。

* **Example:**  
  You are explaining quantum physics. The target audience is a high school student with no prior knowledge of the subject. Explain it simply and use analogies they might understand.

  Explain quantum physics: [Insert basic explanation request]

* **示例**:
  你正在解释量子物理。目标受众是毫无该学科基础知识的高中生。请用简单语言解释,并使用他们可能理解的类比。

  解释量子物理:[插入基础解释请求]

These advanced and supplementary techniques provide further tools for prompt engineers to optimize model behavior, integrate external information, and tailor interactions for specific users and tasks within agentic workflows.

这些高级和补充技术为提示工程师提供了额外工具,以优化模型行为、整合外部信息,并为 Agentic 工作流中的特定用户和任务定制交互。

## Using Google Gems

## 使用 Google Gems

Google's AI "Gems" (see Fig. 1) represent a user-configurable feature within its large language model architecture. Each "Gem" functions as a specialized instance of the core Gemini AI, tailored for specific, repeatable tasks. Users create a Gem by providing it with a set of explicit instructions, which establishes its operational parameters. This initial instruction set defines the Gem's designated purpose, response style, and knowledge domain. The underlying model is designed to consistently adhere to these pre-defined directives throughout a conversation.

Google 的 AI"Gems"(见图 1)代表其大型语言模型架构中的用户可配置功能。每个"Gem"作为核心 Gemini AI 的专门实例运行,为特定可重复任务量身定制。用户通过提供一组明确指令来创建 Gem,这确立了其操作参数。此初始指令集定义了 Gem 的指定目标、响应风格和知识领域。底层模型设计为在整个对话过程中始终遵循这些预定义指令。

This allows for the creation of highly specialized AI agents for focused applications. For example, a Gem can be configured to function as a code interpreter that only references specific programming libraries. Another could be instructed to analyze data sets, generating summaries without speculative commentary. A different Gem might serve as a translator adhering to a particular formal style guide. This process creates a persistent, task-specific context for the artificial intelligence.

这允许为专注应用创建高度专业化的 AI Agent。例如,可配置 Gem 作为仅引用特定编程库的代码解释器。另一个可被指示分析数据集,生成摘要而不进行推测性评论。不同的 Gem 可能作为遵守特定正式风格指南的翻译器。此过程为 AI 创建了持久且特定于任务的上下文。

Consequently, the user avoids the need to re-establish the same contextual information with each new query. This methodology reduces conversational redundancy and improves the efficiency of task execution. The resulting interactions are more focused, yielding outputs that are consistently aligned with the user's initial requirements. This framework allows for applying fine-grained, persistent user direction to a generalist AI model. Ultimately, Gems enable a shift from general-purpose interaction to specialized, pre-defined AI functionalities.

因此,用户无需在每个新查询中重新建立相同上下文信息。这种方法减少了对话冗余,提升了任务执行效率。产生的交互更加专注,输出与用户初始要求保持高度一致。此框架允许对通用 AI 模型应用细粒度、持久的用户指导。最终,Gems 实现了从通用交互向专业化、预定义 AI 功能的转变。

![][image1]
图 1:Google Gem 使用示例。

## Using LLMs to Refine Prompts (The Meta Approach)

## 使用 LLM 改进提示(元方法)

We've explored numerous techniques for crafting effective prompts, emphasizing clarity, structure, and providing context or examples. This process, however, can be iterative and sometimes challenging. What if we could leverage the very power of large language models, like Gemini, to help us *improve* our prompts? This is the essence of using LLMs for prompt refinement – a "meta" application where AI assists in optimizing the instructions given to AI.

我们已经探讨了多种制作有效提示的技术,强调清晰性、结构以及提供上下文或示例的重要性。然而,这一过程往往是迭代的,有时颇具挑战性。如果我们能利用大型语言模型(如 Gemini)的强大能力来帮助我们*优化*提示呢?这正是使用 LLM 进行提示改进的核心思想——一种"元"应用,即 AI 协助优化给 AI 的指令。

This capability is particularly "cool" because it represents a form of AI self-improvement or at least AI-assisted human improvement in interacting with AI. Instead of solely relying on human intuition and trial-and-error, we can tap into the LLM's understanding of language, patterns, and even common prompting pitfalls to get suggestions for making our prompts better. It turns the LLM into a collaborative partner in the prompt engineering process.

这种能力尤为"精妙",因为它代表了 AI 自我改进的一种形式,或至少是 AI 辅助人类改进与 AI 交互的方式。我们不再仅仅依赖人类直觉和试错,而是能借助 LLM 对语言、模式乃至常见提示陷阱的理解,获得改进提示的建议。它将 LLM 转变为提示工程过程中的协作伙伴。

How does this work in practice? You can provide a language model with an existing prompt that you're trying to improve, along with the task you want it to accomplish and perhaps even examples of the output you're currently getting (and why it's not meeting your expectations). You then prompt the LLM to analyze the prompt and suggest improvements.

如何在实践中实现这一点?您可以为语言模型提供一个您正在尝试改进的现有提示,以及您希望它完成的任务,甚至可能包括您当前获得的输出示例(以及为什么它不符合您的期望)。然后提示 LLM 分析提示并提出改进建议。

A model like Gemini, with its strong reasoning and language generation capabilities, can analyze your existing prompt for potential areas of ambiguity, lack of specificity, or inefficient phrasing. It can suggest incorporating techniques we've discussed, such as adding delimiters, clarifying the desired output format, suggesting a more effective persona, or recommending the inclusion of few-shot examples.

像 Gemini 这样的模型,凭借其强大的推理和语言生成能力,可以分析您的现有提示,寻找潜在的歧义、缺乏具体性或措辞效率低下的区域。它可以建议结合我们讨论过的技术,例如添加分隔符、明确期望的输出格式、建议更有效的角色或推荐包含少样本示例。

The benefits of this meta-prompting approach include:

这种元级提示方法的优势包括:

* **Accelerated Iteration:** Get suggestions for improvement much faster than pure manual trial and error.  
* **Identification of Blind Spots:** An LLM might spot ambiguities or potential misinterpretations in your prompt that you overlooked.  
* **Learning Opportunity:** By seeing the types of suggestions the LLM makes, you can learn more about what makes prompts effective and improve your own prompt engineering skills.  
* **Scalability:** Potentially automate parts of the prompt optimization process, especially when dealing with a large number of prompts.

* **加速迭代**:相比纯手动试错,能更快获得改进建议。
* **识别盲点**:LLM 可能发现您忽略的提示中的歧义或潜在误解。
* **学习机会**:通过观察 LLM 提出的建议类型,您可更深入理解提示有效的要素,提升自身提示工程技能。
* **可扩展性**:可能自动化部分提示优化流程,尤其在处理大量提示时优势明显。

It's important to note that the LLM's suggestions are not always perfect and should be evaluated and tested, just like any manually engineered prompt. However, it provides a powerful starting point and can significantly streamline the refinement process.

需注意,LLM 的建议并非总是完美的,应像对待任何手动设计的提示一样进行评估和测试。然而,它提供了一个强有力的起点,能显著简化优化过程。

* **Example Prompt for Refinement:**  
  Analyze the following prompt for a language model and suggest ways to improve it to consistently extract the main topic and key entities (people, organizations, locations) from news articles. The current prompt sometimes misses entities or gets the main topic wrong.

  Existing Prompt:  
  "Summarize the main points and list important names and places from this article: [insert article text]"

  Suggestions for Improvement:

* **改进提示的示例**:
  分析以下语言模型提示,并提出改进建议,以使其能稳定地从新闻文章中提取主题和关键实体(人物、组织、地点)。当前提示有时会遗漏实体或错误判断主题。

  现有提示:
  "总结本文要点并列出重要名称和地点:[插入文章文本]"

  改进建议:

In this example, we're using the LLM to critique and enhance another prompt. This meta-level interaction demonstrates the flexibility and power of these models, allowing us to build more effective agentic systems by first optimizing the fundamental instructions they receive. It's a fascinating loop where AI helps us talk better to AI.

在此示例中,我们使用 LLM 来评审和增强另一个提示。这种元级交互展示了这些模型的灵活性与强大能力,使我们能通过首先优化给它们的基本指令来构建更有效的 Agentic 系统。这是一个迷人的循环:AI 帮助我们更有效地与 AI 对话。

## Prompting for Specific Tasks

## 特定任务的提示

While the techniques discussed so far are broadly applicable, some tasks benefit from specific prompting considerations. This is particularly relevant in the realm of code and multimodal inputs.

尽管前述技术具有广泛适用性,但某些任务仍受益于特定的提示考量。这在代码和多模态输入领域尤为相关。

## Code Prompting

## 代码提示

Language models, especially those trained on large code datasets, can be powerful assistants for developers. Prompting for code involves using LLMs to generate, explain, translate, or debug code. Various use cases exist:

语言模型,尤其是在大型代码数据集上训练的模型,可成为开发者的强大助手。代码提示涉及使用 LLM 生成、解释、翻译或调试代码。存在多种应用场景:

* **Prompts for writing code:** Asking the model to generate code snippets or functions based on a description of the desired functionality.  
  * **Example:** "Write a Python function that takes a list of numbers and returns the average."  
* **Prompts for explaining code:** Providing a code snippet and asking the model to explain what it does, line by line or in a summary.  
  * **Example:** "Explain the following JavaScript code snippet: [insert code]."  
* **Prompts for translating code:** Asking the model to translate code from one programming language to another.  
  * **Example:** "Translate the following Java code to C++: [insert code]."  
* **Prompts for debugging and reviewing code:** Providing code that has an error or could be improved and asking the model to identify issues, suggest fixes, or provide refactoring suggestions.  
  * **Example:** "The following Python code is giving a 'NameError'. What is wrong and how can I fix it? [insert code and traceback]."

* **代码编写提示**:要求模型基于功能描述生成代码片段或函数。
  * **示例**:"编写一个接受数字列表并返回平均值的 Python 函数。"
* **代码解释提示**:提供代码片段并要求模型逐行或整体解释其功能。
  * **示例**:"解释以下 JavaScript 代码片段:[插入代码]。"
* **代码翻译提示**:要求模型将代码从一种编程语言转换为另一种。
  * **示例**:"将以下 Java 代码翻译为 C++:[插入代码]。"
* **代码调试与审查提示**:提供存在错误或可优化代码,要求模型识别问题、建议修复或提供重构意见。
  * **示例**:"以下 Python 代码出现'NameError'。问题何在?如何修复?[插入代码和错误回溯]。"

Effective code prompting often requires providing sufficient context, specifying the desired language and version, and being clear about the functionality or issue.

有效的代码提示通常需要提供充分上下文、明确指定语言和版本,并清晰阐述功能需求或问题描述。

## Multimodal Prompting

## 多模态提示

While the focus of this appendix and much of current LLM interaction is text-based, the field is rapidly moving towards multimodal models that can process and generate information across different modalities (text, images, audio, video, etc.). Multimodal prompting involves using a combination of inputs to guide the model. This refers to using multiple input formats instead of just text.

尽管本附录重点及当前多数 LLM 交互基于文本,但该领域正迅速向能跨模态(文本、图像、音频、视频等)处理和生成信息的多模态模型发展。多模态提示涉及使用输入组合引导模型,即采用多种输入格式而非仅文本。

* **Example:** Providing an image of a diagram and asking the model to explain the process shown in the diagram (Image Input + Text Prompt). Or providing an image and asking the model to generate a descriptive caption (Image Input + Text Prompt -> Text Output).

* **示例**:提供图表图像并要求模型解释图中所示过程(图像输入 + 文本提示)。或提供图像并要求模型生成描述性标题(图像输入 + 文本提示 -> 文本输出)。

As multimodal capabilities become more sophisticated, prompting techniques will evolve to effectively leverage these combined inputs and outputs.

随着多模态能力日益复杂,提示技术将相应演进,以有效利用这些组合的输入与输出。

## Best Practices and Experimentation

## 最佳实践与实验

Becoming a skilled prompt engineer is an iterative process that involves continuous learning and experimentation. Several valuable best practices are worth reiterating and emphasizing:

成为熟练的提示工程师是一个需要持续学习和实验的迭代过程。值得重申和强调若干有价值的最佳实践:

* **Provide Examples:** Providing one or few-shot examples is one of the most effective ways to guide the model.  
* **Design with Simplicity:** Keep your prompts concise, clear, and easy to understand. Avoid unnecessary jargon or overly complex phrasing.  
* **Be Specific about the Output:** Clearly define the desired format, length, style, and content of the model's response.  
* **Use Instructions over Constraints:** Focus on telling the model what you want it to do rather than what you don't want it to do.  
* **Control the Max Token Length:** Use model configurations or explicit prompt instructions to manage the length of the generated output.  
* **Use Variables in Prompts:** For prompts used in applications, use variables to make them dynamic and reusable, avoiding hardcoding specific values.  
* **Experiment with Input Formats and Writing Styles:** Try different ways of phrasing your prompt (question, statement, instruction) and experiment with different tones or styles to see what yields the best results.  
* **For Few-Shot Prompting with Classification Tasks, Mix Up the Classes:** Randomize the order of examples from different categories to prevent overfitting.  
* **Adapt to Model Updates:** Language models are constantly being updated. Be prepared to test your existing prompts on new model versions and adjust them to leverage new capabilities or maintain performance.  
* **Experiment with Output Formats:** Especially for non-creative tasks, experiment with requesting structured output like JSON or XML.  
* **Experiment Together with Other Prompt Engineers:** Collaborating with others can provide different perspectives and lead to discovering more effective prompts.  
* **CoT Best Practices:** Remember specific practices for Chain of Thought, such as placing the answer after the reasoning and setting temperature to 0 for tasks with a single correct answer.  
* **Document the Various Prompt Attempts:** This is crucial for tracking what works, what doesn't, and why. Maintain a structured record of your prompts, configurations, and results.  
* **Save Prompts in Codebases:** When integrating prompts into applications, store them in separate, well-organized files for easier maintenance and version control.  
* **Rely on Automated Tests and Evaluation:** For production systems, implement automated tests and evaluation procedures to monitor prompt performance and ensure generalization to new data.

* **提供示例**:提供 one-shot 或 few-shot 示例是最有效的模型引导方法之一。
* **设计简洁**:保持提示简明、清晰且易于理解。避免不必要的专业术语或过度复杂措辞。
* **明确输出要求**:清晰定义模型响应的期望格式、长度、风格和内容。
* **指令优于约束**:聚焦于告知模型应做什么,而非不应做什么。
* **控制最大 Token 长度**:使用模型配置或明确提示指令管理生成输出的长度。
* **提示中使用变量**:对应用中使用的提示,采用变量使其动态可复用,避免硬编码特定值。
* **尝试输入格式与写作风格**:试验不同提示措辞方式(疑问、陈述、指令)并探索不同语气或风格,以寻找最佳效果。
* **Few-Shot 分类任务提示中混合类别**:随机化不同类别示例顺序,防止过拟合。
* **适应模型更新**:语言模型持续更新。准备在新模型版本上测试现有提示,并调整以利用新功能或维持性能。
* **尝试输出格式**:尤其对非创意任务,试验请求 JSON 或 XML 等结构化输出。
* **与其他提示工程师协作实验**:合作可提供不同视角,有助于发现更有效提示。
* **CoT 最佳实践**:牢记思维链特定实践,如答案置于推理后,以及对单一正确答案任务设置温度为 0。
* **记录各类提示尝试**:对追踪何者有效、无效及原因至关重要。维护提示、配置和结果的结构化记录。
* **代码库中保存提示**:集成提示至应用时,将其存储于独立、组织良好的文件中,便于维护和版本控制。
* **依赖自动化测试与评估**:对生产系统,实施自动化测试和评估流程,监控提示性能并确保对新数据的泛化能力。

Prompt engineering is a skill that improves with practice. By applying these principles and techniques, and by maintaining a systematic approach to experimentation and documentation, you can significantly enhance your ability to build effective agentic systems.

提示工程是一项通过实践持续提升的技能。应用这些原则与技术,并保持对实验和文档的系统性方法,您将显著增强构建高效 Agentic 系统的能力。

## Conclusion

## 结论

This appendix provides a comprehensive overview of prompting, reframing it as a disciplined engineering practice rather than a simple act of asking questions. Its central purpose is to demonstrate how to transform general-purpose language models into specialized, reliable, and highly capable tools for specific tasks. The journey begins with non-negotiable core principles like clarity, conciseness, and iterative experimentation, which are the bedrock of effective communication with AI. These principles are critical because they reduce the inherent ambiguity in natural language, helping to steer the model's probabilistic outputs toward a single, correct intention. Building on this foundation, basic techniques such as zero-shot, one-shot, and few-shot prompting serve as the primary methods for demonstrating expected behavior through examples. These methods provide varying levels of contextual guidance, powerfully shaping the model's response style, tone, and format. Beyond just examples, structuring prompts with explicit roles, system-level instructions, and clear delimiters provides an essential architectural layer for fine-grained control over the model.

本附录全面概述了提示工程,将其重新定位为一项有纪律的工程实践,而非简单的提问行为。其核心目标是展示如何将通用语言模型转化为针对特定任务的专业化、可靠且高度能干的工具。这一旅程始于不容妥协的核心原则:清晰性、简洁性和迭代实验,这些是与 AI 有效沟通的基石。这些原则至关重要,因其减少了自然语言固有的歧义,帮助引导模型的概率输出朝向明确正确的意图。在此基础上,基础技术(如 zero-shot、one-shot 和 few-shot 提示)作为通过示例展示预期行为的主要手段。这些方法提供不同层级的上下文指导,有力塑造模型的响应风格、语气和格式。超越示例范畴,使用明确角色、系统级指令和清晰分隔符构建提示,为精细控制模型提供了必要的架构层次。

The importance of these techniques becomes paramount in the context of building autonomous agents, where they provide the control and reliability necessary for complex, multi-step operations. For an agent to effectively create and execute a plan, it must leverage advanced reasoning patterns like Chain of Thought and Tree of Thoughts. These sophisticated methods compel the model to externalize its logical steps, systematically breaking down complex goals into a sequence of manageable sub-tasks. The operational reliability of the entire agentic system hinges on the predictability of each component's output. This is precisely why requesting structured data like JSON, and programmatically validating it with tools such as Pydantic, is not a mere convenience but an absolute necessity for robust automation. Without this discipline, the agent's internal cognitive components cannot communicate reliably, leading to catastrophic failures within an automated workflow. Ultimately, these structuring and reasoning techniques are what successfully convert a model's probabilistic text generation into a deterministic and trustworthy cognitive engine for an agent.

这些技术在构建自主智能体的背景下变得至关重要,它们为复杂多步骤操作提供了必要的控制与可靠性。为使智能体能够制定和执行计划,必须利用高级推理模式,如思维链和思维树。这些复杂方法迫使模型外化其逻辑步骤,系统地将复杂目标分解为可管理的子任务序列。整个 Agentic 系统的运营可靠性依赖于各组件输出的可预测性。这正是为何请求 JSON 等结构化数据,并使用 Pydantic 等工具进行程序化验证,不仅是一种便利,更是强大自动化的绝对必要条件。缺乏这种纪律,Agent 的内部认知组件无法可靠通信,导致自动化工作流中的灾难性故障。最终,这些结构化与推理技术成功将模型的概率文本生成转化为智能体的可靠认知引擎。

Furthermore, these prompts are what grant an agent its crucial ability to perceive and act upon its environment, bridging the gap between digital thought and real-world interaction. Action-oriented frameworks like ReAct and native function calling are the vital mechanisms that serve as the agent's hands, allowing it to use tools, query APIs, and manipulate data. In parallel, techniques like Retrieval Augmented Generation (RAG) and the broader discipline of Context Engineering function as the agent's senses. They actively retrieve relevant, real-time information from external knowledge bases, ensuring the agent's decisions are grounded in current, factual reality. This critical capability prevents the agent from operating in a vacuum, where it would be limited to its static and potentially outdated training data. Mastering this full spectrum of prompting is therefore the definitive skill that elevates a generalist language model from a simple text generator into a truly sophisticated agent, capable of performing complex tasks with autonomy, awareness, and intelligence.

此外,这些提示赋予智能体感知环境并与之交互的关键能力,弥合数字思维与现实世界行动间的鸿沟。ReAct 和原生工具调用等行动导向框架赋予智能体行动能力,使其能使用工具、查询 API 和操作数据。同时,检索增强生成(RAG)及更广泛的上下文工程学科则充当智能体的信息检索系统,使它们能主动从外部知识库检索相关实时信息,确保智能体的决策基于现实世界信息。这一关键能力防止智能体在信息真空中运作,并使其免受限于其静态且可能过时的训练数据。因此,掌握完整的提示技术谱系,是将通用语言模型从简单文本生成器提升为真正复杂智能体的决定性技能,使智能体具备自主性、情境意识和智能执行复杂任务的能力。

## References

## 参考文献

Here is a list of resources for further reading and deeper exploration of prompt engineering techniques:

以下是进一步阅读和深入探索提示工程技术的资源列表:

 1. Prompt Engineering, [https://www.kaggle.com/whitepaper-prompt-engineering](https://www.kaggle.com/whitepaper-prompt-engineering)
 2. Chain-of-Thought Prompting Elicits Reasoning in Large Language Models, [https://arxiv.org/abs/2201.11903](https://arxiv.org/abs/2201.11903)
 3. Self-Consistency Improves Chain of Thought Reasoning in Language Models,  [https://arxiv.org/pdf/2203.11171](https://arxiv.org/pdf/2203.11171)
 4. ReAct: Synergizing Reasoning and Acting in Language Models, [https://arxiv.org/abs/2210.03629](https://arxiv.org/abs/2210.03629)
 5. Tree of Thoughts: Deliberate Problem Solving with Large Language Models,  [https://arxiv.org/pdf/2305.10601](https://arxiv.org/pdf/2305.10601)
 6. Take a Step Back: Evoking Reasoning via Abstraction in Large Language Models, [https://arxiv.org/abs/2310.06117](https://arxiv.org/abs/2310.06117)
 7. DSPy: Programming—not prompting—Foundation Models [https://github.com/stanfordnlp/dspy](https://github.com/stanfordnlp/dspy)

[image1]: ../images/appendix-a/image1.png


## /bilingual/Appendix B - AI Agentic Interactions_ From GUI to Real world environment.md

# Appendix B - AI Agentic Interactions: From GUI to Real World environment

# 附录 B - AI 智能体交互:从图形用户界面到真实世界环境

AI agents are increasingly performing complex tasks by interacting with digital interfaces and the physical world. Their ability to perceive, process, and act within these varied environments is fundamentally transforming automation, human-computer interaction, and intelligent systems. This appendix explores how agents interact with computers and their environments, highlighting advancements and projects.

AI 智能体正日益通过与数字界面和物理世界的交互来执行复杂任务。它们在这些多样化环境中感知、处理和行动的能力,正在从根本上重塑自动化、人机交互和智能系统的格局。本附录深入探讨智能体如何与计算机及其环境交互,并重点介绍相关技术进展与代表性项目。

## Interaction: Agents with Computers

## 交互:智能体与计算机

The evolution of AI from conversational partners to active, task-oriented agents is being driven by Agent-Computer Interfaces (ACIs). These interfaces allow AI to interact directly with a computer's Graphical User Interface (GUI), enabling it to perceive and manipulate visual elements like icons and buttons just as a human would. This new method moves beyond the rigid, developer-dependent scripts of traditional automation that relied on APIs and system calls. By using the visual "front door" of software, AI can now automate complex digital tasks in a more flexible and powerful way, a process that involves several key stages:

AI 从对话伙伴向主动式任务导向型智能体演进,正由智能体-计算机界面(Agent-Computer Interfaces,ACIs)技术驱动。这些界面使 AI 能够直接与计算机的图形用户界面(Graphical User Interface,GUI)交互,使其能像人类一样感知并操作图标、按钮等视觉元素。这种新范式超越了依赖 API 和系统调用的传统自动化方法——后者往往受限于僵化的、依赖开发人员编写的脚本。通过利用软件的视觉"前门",AI 现能以更灵活、更强大的方式自动化复杂数字任务,该过程涉及以下关键阶段:

* **Visual Perception:** The agent first captures a visual representation of the screen, essentially taking a screenshot.  
* **GUI Element Recognition:** It then analyzes this image to distinguish between various GUI elements. It must learn to "see" the screen not as a mere collection of pixels, but as a structured layout with interactive components, discerning a clickable "Submit" button from a static banner image or an editable text field from a simple label.  
* **Contextual Interpretation:** The ACI module, acting as a bridge between the visual data and the agent's core intelligence (often a Large Language Model or LLM), interprets these elements within the context of the task. It understands that a magnifying glass icon typically means "search" or that a series of radio buttons represents a choice. This module is crucial for enhancing the LLM's reasoning, allowing it to form a plan based on visual evidence.  
* **Dynamic Action and Response:** The agent then programmatically controls the mouse and keyboard to execute its plan—clicking, typing, scrolling, and dragging. Critically, it must constantly monitor the screen for visual feedback, dynamically responding to changes, loading screens, pop-up notifications, or errors to successfully navigate multi-step workflows.

* **视觉感知**:智能体首先捕获屏幕的视觉呈现,本质上相当于截屏操作。
* **GUI 元素识别**:随后分析该图像以区分各类 GUI 元素。它必须学会将屏幕"解读"为具有交互组件的结构化布局,而非单纯的像素集合,能够辨别可点击的"提交"按钮与静态横幅广告,或区分可编辑文本框与普通标签。
* **上下文理解**:ACI 模块作为视觉数据与智能体核心智能(通常为大型语言模型 LLM)间的桥梁,在任务背景下解析这些元素。它能理解放大镜图标通常代表"搜索",或一组单选按钮表示选项。此模块对增强 LLM 推理能力至关重要,使其能基于视觉证据制定行动计划。
* **动态执行与响应**:智能体随后通过程序化控制鼠标和键盘执行计划——包括点击、输入、滚动和拖拽。关键在于,它必须持续监控屏幕以获取视觉反馈,动态响应界面变化、加载状态、弹窗通知或错误信息,从而成功驾驭多步骤工作流。

This technology is no longer theoretical. Several leading AI labs have developed functional agents that demonstrate the power of GUI interaction:

这项技术已不再停留在理论层面。多家领先 AI 实验室已开发出功能性智能体,充分展示了 GUI 交互的强大潜力:

**ChatGPT Operator (OpenAI):** Envisioned as a digital partner, ChatGPT Operator is designed to automate tasks across a wide range of applications directly from the desktop. It understands on-screen elements, enabling it to perform actions like transferring data from a spreadsheet into a customer relationship management (CRM) platform, booking a complex travel itinerary across airline and hotel websites, or filling out detailed online forms without needing specialized API access for each service. This makes it a universally adaptable tool aimed at boosting both personal and enterprise productivity by taking over repetitive digital chores.

**ChatGPT Operator(OpenAI)**:ChatGPT Operator 被构想为数字协作伙伴,旨在直接从桌面端自动化多种应用程序的任务。它能理解屏幕元素,从而执行诸如将电子表格数据导入客户关系管理(CRM)系统、在航空公司和酒店网站间规划复杂行程,或填写详尽在线表单等操作,无需为每个服务配置专用 API 访问权限。这使其成为通用性工具,旨在通过接管重复性数字任务提升个人与企业效率。

**Google Project Mariner:** As a research prototype, Project Mariner operates as an agent within the Chrome browser (see Fig. 1). Its purpose is to understand a user's intent and autonomously carry out web-based tasks on their behalf. For example, a user could ask it to find three apartments for rent within a specific budget and neighborhood; Mariner would then navigate to real estate websites, apply the filters, browse the listings, and extract the relevant information into a document. This project represents Google's exploration into creating a truly helpful and "agentive" web experience where the browser actively works for the user.

**Google Project Mariner**:作为研究原型,Project Mariner 作为智能体在 Chrome 浏览器内运行(见图 1)。其核心目标是理解用户意图并自主执行基于网络的任务。例如,用户可指令其在特定预算和区域内寻找三套出租公寓;Mariner 便会导航至房产网站,应用筛选条件,浏览房源列表,并将相关信息提取至文档中。该项目体现了 Google 对构建真正实用且具"代理性"网络体验的探索——让浏览器主动为用户服务。

![][image1]

Fig.1: Interaction between and Agent and the Web Browser

图 1:智能体与网络浏览器的交互示意图

**Anthropic's Computer Use:** This feature empowers Anthropic's AI model, Claude, to become a direct user of a computer's desktop environment. By capturing screenshots to perceive the screen and programmatically controlling the mouse and keyboard, Claude can orchestrate workflows that span multiple, unconnected applications. A user could ask it to analyze data in a PDF report, open a spreadsheet application to perform calculations on that data, generate a chart, and then paste that chart into an email draft—a sequence of tasks that previously required constant human input.

**Anthropic 的计算机使用功能**:该特性使 Anthropic 的 AI 模型 Claude 能够成为计算机桌面环境的直接操作用户。通过截屏感知界面并以程序化方式控制鼠标键盘,Claude 可编排跨多个独立应用的工作流。用户可要求其分析 PDF 报告中的数据,打开电子表格程序进行相关计算,生成图表,并将图表插入邮件草稿——这一系列任务以往需要持续的人工介入。

**Browser Use**: This is an open-source library that provides a high-level API for programmatic browser automation. It enables AI agents to interface with web pages by granting them access to and control over the Document Object Model (DOM). The API abstracts the intricate, low-level commands of browser control protocols, into a more simplified and intuitive set of functions. This allows an agent to perform complex sequences of actions, including data extraction from nested elements, form submissions, and automated navigation across multiple pages. As a result, the library facilitates the transformation of unstructured web data into a structured format that an AI agent can systematically process and utilize for analysis or decision-making.

**Browser Use**:这是一个提供程序化浏览器自动化高级 API 的开源库。它使 AI 智能体通过访问和控制文档对象模型(Document Object Model,DOM)与网页交互。该 API 将浏览器控制协议的复杂底层指令抽象为更简洁直观的函数集。这使得智能体能够执行复杂操作序列,包括从嵌套元素提取数据、提交表单以及跨页面自动导航。因此,该库助力将非结构化网络数据转化为 AI 智能体可以用于分析或决策的结构化格式。

## Interaction: Agents with the Environment

## 交互:智能体与环境

Beyond the confines of a computer screen, AI agents are increasingly designed to interact with complex, dynamic environments, often mirroring the real world. This requires sophisticated perception, reasoning, and actuation capabilities.

超越计算机屏幕的局限,AI 智能体正越来越多地被设计用于与复杂、动态的环境交互,这些环境往往模拟现实世界。这要求智能体具备复杂的感知、推理和执行能力。

Google's **Project Astra** is a prime example of an initiative pushing the boundaries of agent interaction with the environment. Astra aims to create a universal AI agent that is helpful in everyday life, leveraging multimodal inputs (sight, sound, voice) and outputs to understand and interact with the world contextually. This project focuses on rapid understanding, reasoning, and response, allowing the agent to "see" and "hear" its surroundings through cameras and microphones and engage in natural conversation while providing real-time assistance. Astra's vision is an agent that can seamlessly assist users with tasks ranging from finding lost items to debugging code, by understanding the environment it observes. This moves beyond simple voice commands to a truly embodied understanding of the user's immediate physical context.

Google 的 **Project Astra** 是推动智能体与环境交互边界的一个典范。Astra 致力于打造一个在日常生活中实用的通用 AI 智能体,它利用多模态输入(视觉、听觉、语音)和输出来理解世界并进行上下文交互。该项目聚焦于快速理解、推理与响应,使智能体通过摄像头和麦克风"看见"和"听见"周遭环境,并在提供实时协助的同时进行自然对话。Astra 的愿景是打造一个能无缝帮助用户完成从寻找失物到调试代码等各种任务的智能体,其核心在于理解所观察的环境。这超越了简单的语音指令,实现了对用户即时物理情境的真正具身化理解。

Google's **Gemini Live**, transforms standard AI interactions into a fluid and dynamic conversation. Users can speak to the AI and receive responses in a natural-sounding voice with minimal delay, and can even interrupt or change topics mid-sentence, prompting the AI to adapt immediately. The interface expands beyond voice, allowing users to incorporate visual information by using their phone's camera, sharing their screen, or uploading files for a more context-aware discussion. More advanced versions can even perceive a user's tone of voice and intelligently filter out irrelevant background noise to better understand the conversation. These capabilities combine to create rich interactions, such as receiving live instructions on a task by simply pointing a camera at it.

Google 的 **Gemini Live** 将标准 AI 交互转化为流畅且动态的对话体验。用户可与 AI 交谈,并以极低延迟收到自然语音回复,甚至能在语句中途打断或切换话题,AI 会立即适应。交互界面不限于语音,用户还可通过手机摄像头、屏幕共享或文件上传融入视觉信息,进行更具情境感知的讨论。更高级版本甚至能感知用户语调,并智能滤除无关背景噪音以提升对话理解。这些能力共同创造了丰富的交互场景,例如仅需将摄像头对准某物即可获得该任务的实时指导。

OpenAI's **GPT-4o model** is an alternative designed for "omni" interaction, meaning it can reason across voice, vision, and text. It processes these inputs with low latency that mirrors human response times, which allows for real-time conversations. For example, users can show the AI a live video feed to ask questions about what is happening, or use it for language translation. OpenAI provides developers with a "Realtime API" to build applications requiring low-latency, speech-to-speech interactions.

OpenAI 的 **GPT-4o 模型** 是专为"全向"交互设计的另一选择,意指其能跨语音、视觉和文本进行推理。该模型以接近人类响应速度的低延迟处理这些输入,从而实现实时对话。例如,用户可向 AI 展示实时视频流并询问画面内容,或用于语言翻译。OpenAI 为开发者提供了"实时 API",用于构建需要低延迟、语音到语音交互的应用。

OpenAI's **ChatGPT Agent** represents a significant architectural advancement over its predecessors, featuring an integrated framework of new capabilities. Its design incorporates several key functional modalities: the capacity for autonomous navigation of the live internet for real-time data extraction, the ability to dynamically generate and execute computational code for tasks like data analysis, and the functionality to interface directly with third-party software applications. The synthesis of these functions allows the agent to orchestrate and complete complex, sequential workflows from a singular user directive. It can therefore autonomously manage entire processes, such as performing market analysis and generating a corresponding presentation, or planning logistical arrangements and executing the necessary transactions. In parallel with the launch, OpenAI has proactively addressed the emergent safety considerations inherent in such a system. An accompanying "System Card" delineates the potential operational hazards associated with an AI capable of performing actions online, acknowledging the new vectors for misuse. To mitigate these risks, the agent's architecture includes engineered safeguards, such as requiring explicit user authorization for certain classes of actions and deploying robust content filtering mechanisms. The company is now engaging its initial user base to further refine these safety protocols through a feedback-driven, iterative process.

OpenAI 的 **ChatGPT Agent** 代表了相较于前代产品的重大架构升级,集成了新功能框架。其设计包含多项核心功能模式:自主浏览实时互联网以提取实时数据的能力、动态生成并执行计算代码以完成数据分析等任务的能力,以及直接与第三方软件应用交互的功能。这些能力的融合使智能体从单一用户指令出发,编排并完成复杂、有序的工作流。因此,它能自主管理整个流程,例如执行市场分析并生成对应演示文稿,或规划物流安排并执行必要交易。在发布同时,OpenAI 主动应对了此类系统固有的新兴安全问题。随附的"系统卡"文件阐明了具备在线操作能力的 AI 可能带来的潜在风险,承认了新的滥用途径。为降低这些风险,智能体架构内置了工程化保障措施,如要求特定操作类别需获得用户明确授权,并部署了强健的内容过滤机制。公司现正通过反馈驱动的迭代流程,邀请初期用户群体共同完善这些安全协议。

**Seeing AI,** a complimentary mobile application from Microsoft, empowers individuals who are blind or have low vision by offering real-time narration of their surroundings. The app leverages artificial intelligence through the device's camera to identify and describe various elements, including objects, text, and even people. Its core functionalities encompass reading documents, recognizing currency, identifying products through barcodes, and describing scenes and colors. By providing enhanced access to visual information, Seeing AI ultimately fosters greater independence for visually impaired users.

**Seeing AI** 是 Microsoft 推出的一款免费移动应用,它通过实时描述周围环境,为盲人或视力障碍人士赋能。该应用借助设备摄像头运用人工智能技术,识别并描述各类元素,包括物体、文字乃至人物。其核心功能涵盖文档阅读、货币识别、条形码产品辨识以及场景和颜色描述。通过增强对视觉信息的可及性,Seeing AI 最终提升了视障用户的独立生活能力。

**Anthropic's Claude 4 Series**: Anthropic's Claude 4 is another alternative with capabilities for advanced reasoning and analysis. Though historically focused on text, Claude 4 includes robust vision capabilities, allowing it to process information from images, charts, and documents. The model is suited for handling complex, multi-step tasks and providing detailed analysis. While the real-time conversational aspect is not its primary focus compared to other models, its underlying intelligence is designed for building highly capable AI agents.

**Anthropic 的 Claude 4 系列**:Anthropic 的 Claude 4 是另一款具备高级推理与分析能力的替代选择。尽管其传统强项在于文本处理,但 Claude 4 也包含了强大的视觉功能,能处理来自图像、图表和文档的信息。该模型适用于处理复杂的多步骤任务并提供详尽分析。虽然其实时对话特性并非主要焦点(相较于其他模型),但其底层智能专为构建高能力 AI 智能体而设计。

## Vibe Coding: Intuitive Development with AI

## Vibe 编码:使用 AI 的直观开发范式

Beyond direct interaction with GUIs and the physical world, a new paradigm is emerging in how developers build software with AI: "vibe coding." This approach moves away from precise, step-by-step instructions and instead relies on a more intuitive, conversational, and iterative interaction between the developer and an AI coding assistant. The developer provides a high-level goal, a desired "vibe," or a general direction, and the AI generates code to match.

除了与 GUI 和物理环境的直接交互外,开发人员使用 AI 构建软件的方式也涌现出新范式:"vibe 编码"。这种方法摒弃了精确的、逐步的指令,转而依赖开发者与 AI 编码助手之间更直观、对话式和迭代的协作。开发者提供高层次目标、期望的"氛围"或大致方向,AI 则生成与之匹配的代码。

This process is characterized by:

该过程具有以下特征:

* **Conversational Prompts:** Instead of writing detailed specifications, a developer might say, "Create a simple, modern-looking landing page for a new app," or, "Refactor this function to be more Pythonic and readable." The AI interprets the "vibe" of "modern" or "Pythonic" and generates the corresponding code.
* **Iterative Refinement:** The initial output from the AI is often a starting point. The developer then provides feedback in natural language, such as, "That's a good start, but can you make the buttons blue?" or, "Add some error handling to that." This back-and-forth continues until the code meets the developer's expectations.
* **Creative Partnership:** In vibe coding, the AI acts as a creative partner, suggesting ideas and solutions that the developer may not have considered. This can accelerate the development process and lead to more innovative outcomes.
* **Focus on "What" not "How":** The developer focuses on the desired outcome (the "what") and leaves the implementation details (the "how") to the AI. This allows for rapid prototyping and exploration of different approaches without getting bogged down in boilerplate code.
* **Optional Memory Banks:** To maintain context across longer interactions, developers can use "memory banks" to store key information, preferences, or constraints. For example, a developer might save a specific coding style or a set of project requirements to the AI's memory, ensuring that future code generations remain consistent with the established "vibe" without needing to repeat the instructions.

* **对话式提示**:开发者不再编写详细规格说明,而是用自然语言表达,如"为新应用创建一个简洁现代风格的登录页面",或"重构此函数使其更符合 Pythonic 风格并提升可读性"。AI 会解读"现代"或"Pythonic"的"氛围"内涵,生成相应代码。
* **迭代精炼**:AI 的初始输出通常只是起点。开发者随后以自然语言提供反馈,如"这个开头不错,但能把按钮改成蓝色吗?"或"为那段代码添加错误处理机制。"如此往复,直至代码符合预期。
* **创意伙伴关系**:在 vibe 编码中,AI 扮演创意伙伴角色,提出开发者可能未曾考虑的创意和解决方案。这能加速开发进程并催生更具创新性的成果。
* **聚焦"目标"而非"方法"**:开发者专注于期望成果("目标"),将实现细节("方法")交由 AI 处理。这使得快速原型设计和多方案探索成为可能,避免陷入样板代码的繁琐。
* **可选记忆库**:为在长对话中保持上下文连贯,开发者可使用"记忆库"存储关键信息、偏好或约束条件。例如,开发者可将特定编码风格或项目需求集保存至 AI 记忆库,确保后续代码生成与既定"氛围"保持一致,无需重复指令。

Vibe coding is becoming increasingly popular with the rise of powerful AI models like GPT-4, Claude, and Gemini, which are integrated into development environments. These tools are not just auto-completing code; they are actively participating in the creative process of software development, making it more accessible and efficient. This new way of working is changing the nature of software engineering, emphasizing creativity and high-level thinking over rote memorization of syntax and APIs.

随着 GPT-4、Claude 和 Gemini 等强大 AI 模型集成至开发环境,Vibe 编码日益流行。这些工具不仅是代码自动补全器;它们正积极参与软件开发的创意过程,使其更易用、更高效。这种新型工作方式正在改变软件工程的性质,强调创造力与高阶思维,而非对语法和 API 的死记硬背。

## Key takeaways

## 关键要点

* AI agents are evolving from simple automation to visually controlling software through graphical user interfaces, much like a human would.  
* The next frontier is real-world interaction, with projects like Google's Astra using cameras and microphones to see, hear, and understand their physical surroundings.  
* Leading technology companies are converging these digital and physical capabilities to create universal AI assistants that operate seamlessly across both domains.  
* This shift is creating a new class of proactive, context-aware AI companions capable of assisting with a vast range of tasks in users' daily lives.

* AI 智能体正从简单自动化演进为通过图形用户界面视觉控制软件,操作方式类人化。
* 下一前沿是真实世界交互,如 Google Astra 等项目利用摄像头和麦克风感知、聆听并理解物理环境。
* 领先科技公司正融合这些数字与物理能力,打造跨域无缝运行的通用 AI 助手。
* 这一转变催生了新型主动式、情境感知型 AI 伙伴,能协助用户处理日常生活中的大量任务。

## Conclusion

## 结论

Agents are undergoing a significant transformation, moving from basic automation to sophisticated interaction with both digital and physical environments. By leveraging visual perception to operate Graphical User Interfaces, these agents can now manipulate software just as a human would, bypassing the need for traditional APIs. Major technology labs are pioneering this space with agents capable of automating complex, multi-application workflows directly on a user's desktop. Simultaneously, the next frontier is expanding into the physical world, with initiatives like Google's Project Astra using cameras and microphones to contextually engage with their surroundings. These advanced systems are designed for multimodal, real-time understanding that mirrors human interaction.

智能体正经历重大转型,从基础自动化迈向与数字及物理环境的复杂交互。借助视觉感知操作图形用户界面,这些智能体能像人类一样操控软件,绕过了对传统 API 的依赖。主要技术实验室正引领这一领域,其开发的智能体可在桌面直接自动化复杂的多应用工作流。与此同时,下一前沿已扩展至物理世界,如 Google Project Astra 等项目利用摄像头和麦克风与周边环境进行情境化互动。这些先进系统旨在实现媲美人类交互的多模态实时理解。

The ultimate vision is a convergence of these digital and physical capabilities, creating universal AI assistants that operate seamlessly across all of a user's environments. This evolution is also reshaping software creation itself through "vibe coding," a more intuitive and conversational partnership between developers and AI. This new method prioritizes high-level goals and creative intent, allowing developers to focus on the desired outcome rather than implementation details. This shift accelerates development and fosters innovation by treating AI as a creative partner. Ultimately, these advancements are paving the way for a new era of proactive, context-aware AI companions capable of assisting with a vast array of tasks in our daily lives.

终极愿景是融合这些数字与物理能力,创建跨用户所有环境无缝运作的通用 AI 助手。这一演进也通过"vibe 编码"重塑了软件创作本身,形成开发者与 AI 间更直观、对话式的伙伴关系。该新方法优先考虑高层次目标与创意意图,让开发者聚焦于期望成果而非实现细节。通过将 AI 视为创意合作伙伴,这一转变加速了开发进程并激发了创新。最终,这些进步正为主动式、情境感知型 AI 伙伴的新时代铺平道路,使其能够协助我们应对日常生活中的大量任务。

## References

## 参考文献

 1. Open AI Operator, [https://openai.com/index/introducing-operator/](https://openai.com/index/introducing-operator/)
 2. Open AI ChatGPT Agent: [https://openai.com/index/introducing-chatgpt-agent/](https://openai.com/index/introducing-chatgpt-agent/)
 3. Browser Use: [https://docs.browser-use.com/introduction](https://docs.browser-use.com/introduction)
 4. Project Mariner, [https://deepmind.google/models/project-mariner/](https://deepmind.google/models/project-mariner/)
 5. Anthropic Computer use: [https://docs.anthropic.com/en/docs/build-with-claude/computer-use](https://docs.anthropic.com/en/docs/build-with-claude/computer-use)
 6. Project Astra, [https://deepmind.google/models/project-astra/](https://deepmind.google/models/project-astra/)
 7. Gemini Live, [https://gemini.google/overview/gemini-live/?hl=en](https://gemini.google/overview/gemini-live/?hl=en)
 8. OpenAI's GPT-4,  [https://openai.com/index/gpt-4-research/](https://openai.com/index/gpt-4-research/)
 9. Claude 4, [https://www.anthropic.com/news/claude-4](https://www.anthropic.com/news/claude-4)

[image1]: ../images/appendix-b/image1.png


## /bilingual/Appendix C - Quick overview of Agentic Frameworks.md

---
layout: bilingual
lang: bilingual
---

# Appendix C - Quick overview of Agentic Frameworks

# 附录 C - Agentic 框架快速概览

## LangChain

LangChain is a framework for developing applications powered by LLMs. Its core strength lies in its LangChain Expression Language (LCEL), which allows you to "pipe" components together into a chain. This creates a clear, linear sequence where the output of one step becomes the input for the next. It's built for workflows that are Directed Acyclic Graphs (DAGs), meaning the process flows in one direction without loops.

LangChain 是一个用于开发由大语言模型(LLM)驱动的应用程序的框架。其核心优势在于 LangChain 表达式语言(LCEL),它允许您使用管道操作符将组件连接成链。这种设计形成了清晰的线性序列,每一步的输出自动成为下一步的输入。该框架专为有向无环图(DAG)工作流构建,意味着处理流程单向流动且无循环。

Use it for:

适用场景:

* Simple RAG: Retrieve a document, create a prompt, get an answer from an LLM.  
* Summarization: Take user text, feed it to a summarization prompt, and return the output.  
* Extraction: Extract structured data (like JSON) from a block of text.

* 简单 RAG:检索文档,构建提示,从 LLM 获取答案。
* 文本摘要:接收用户文本,输入至摘要提示,返回摘要结果。
* 数据提取:从文本块中提取结构化数据(如 JSON 格式)。

```python
# A simple LCEL chain conceptually
# (This is not runnable code, just illustrates the flow)
chain = prompt | model | output_parser
```

### LangGraph

LangGraph is a library built on top of LangChain to handle more advanced agentic systems. It allows you to define your workflow as a graph with nodes (functions or LCEL chains) and edges (conditional logic). Its main advantage is the ability to create cycles, allowing the application to loop, retry, or call tools in a flexible order until a task is complete. It explicitly manages the application state, which is passed between nodes and updated throughout the process.

LangGraph 是构建于 LangChain 之上的库,专为处理更高级的 Agentic 系统设计。它允许您将工作流定义为包含节点(函数或 LCEL 链)和边(条件逻辑)的图结构。其主要优势在于支持循环创建,使应用程序能够循环执行、重试操作或以灵活顺序调用工具,直至任务完成。该库显式管理应用程序状态,状态在节点间传递并在整个流程中持续更新。

Use it for:

适用场景:

* Multi-agent Systems: A supervisor agent routes tasks to specialized worker agents, potentially looping until the goal is met.  
* Plan-and-Execute Agents: An agent creates a plan, executes a step, and then loops back to update the plan based on the result.  
* Human-in-the-Loop: The graph can wait for human input before deciding which node to go to next.

* 多智能体系统:监督智能体将任务路由给专业化工作智能体,可能循环执行直至目标达成。
* 规划与执行智能体:智能体制定计划,执行步骤,随后基于结果循环反馈以更新计划。
* 人机协同:图结构可等待人工输入,再决定后续执行节点。

| Feature | LangChain | LangGraph |
| :---- | :---- | :---- |
| Core Abstraction | Chain (using LCEL) | Graph of Nodes |
| Workflow Type | Linear (Directed Acyclic Graph) | Cyclical (Graphs with loops) |
| State Management | Generally stateless per run | Explicit and persistent state object |
| Primary Use | Simple, predictable sequences | Complex, dynamic, stateful agents |

| 特性 | LangChain | LangGraph |
| :---- | :---- | :---- |
| 核心抽象 | 链(使用 LCEL) | 节点图 |
| 工作流类型 | 线性(有向无环图) | 循环(支持循环的图) |
| 状态管理 | 通常单次运行无状态 | 显式且持久的状态对象 |
| 主要用途 | 简单、可预测的序列 | 复杂、动态、有状态的智能体 |

### Which One Should You Use?

### 如何选择?

* Choose LangChain when your application has a clear, predictable, and linear flow of steps. If you can define the process from A to B to C without needing to loop back, LangChain with LCEL is the perfect tool.  
* Choose LangGraph when you need your application to reason, plan, or operate in a loop. If your agent needs to use tools, reflect on the results, and potentially try again with a different approach, you need the cyclical and stateful nature of LangGraph.

* 当应用程序具备清晰、可预测的线性步骤流程时,选择 LangChain。若您能定义从 A 到 B 再到 C 的直连过程而无需回环,则采用 LCEL 的 LangChain 是理想工具。
* 当应用程序需进行推理、规划或循环操作时,选择 LangGraph。若您的智能体使用工具、反思结果并可能尝试不同策略,则需借助 LangGraph 的循环和有状态特性。

```python
# Graph state
class State(TypedDict):
    topic: str
    joke: str
    story: str
    poem: str
    combined_output: str

# Nodes
def call_llm_1(state: State):
    """First LLM call to generate initial joke"""
    msg = llm.invoke(f"Write a joke about {state['topic']}")
    return {"joke": msg.content}

def call_llm_2(state: State):
    """Second LLM call to generate story"""
    msg = llm.invoke(f"Write a story about {state['topic']}")
    return {"story": msg.content}

def call_llm_3(state: State):
    """Third LLM call to generate poem"""
    msg = llm.invoke(f"Write a poem about {state['topic']}")
    return {"poem": msg.content}

def aggregator(state: State):
    """Combine the joke and story into a single output"""
    combined = f"Here's a story, joke, and poem about {state['topic']}!\n\n"
    combined += f"STORY:\n{state['story']}\n\n"
    combined += f"JOKE:\n{state['joke']}\n\n"
    combined += f"POEM:\n{state['poem']}"
    return {"combined_output": combined}

# Build workflow
parallel_builder = StateGraph(State)

# Add nodes
parallel_builder.add_node("call_llm_1", call_llm_1)
parallel_builder.add_node("call_llm_2", call_llm_2)
parallel_builder.add_node("call_llm_3", call_llm_3)
parallel_builder.add_node("aggregator", aggregator)

# Add edges to connect nodes
parallel_builder.add_edge(START, "call_llm_1")
parallel_builder.add_edge(START, "call_llm_2")
parallel_builder.add_edge(START, "call_llm_3")
parallel_builder.add_edge("call_llm_1", "aggregator")
parallel_builder.add_edge("call_llm_2", "aggregator")
parallel_builder.add_edge("call_llm_3", "aggregator")
parallel_builder.add_edge("aggregator", END)

parallel_workflow = parallel_builder.compile()

# Show workflow
display(Image(parallel_workflow.get_graph().draw_mermaid_png()))

# Invoke
state = parallel_workflow.invoke({"topic": "cats"})
print(state["combined_output"])
```

This code defines and runs a LangGraph workflow that operates in parallel. Its main purpose is to simultaneously generate a joke, a story, and a poem about a given topic and then combine them into a single, formatted text output.

这段代码定义并运行了一个并行操作的 LangGraph 工作流。其主要目的是同时生成关于给定主题的笑话、故事和诗歌,然后将它们组合成单个格式化的文本输出。

## Google's ADK

Google's Agent Development Kit, or ADK, provides a high-level, structured framework for building and deploying applications composed of multiple, interacting AI agents. It contrasts with LangChain and LangGraph by offering a more opinionated and production-oriented system for orchestrating agent collaboration, rather than providing the fundamental building blocks for an agent's internal logic.

Google 的智能体开发工具包(ADK)提供了一个高级、结构化的框架,用于构建和部署由多个交互性 AI 智能体组成的应用程序。与 LangChain 和 LangGraph 相比,它提供了一个更具指导性和生产就绪的系统,用于编排智能体协作,而非提供智能体内部逻辑的基础构建块。

LangChain operates at the most foundational level, offering the components and standardized interfaces to create sequences of operations, such as calling a model and parsing its output. LangGraph extends this by introducing a more flexible and powerful control flow; it treats an agent's workflow as a stateful graph. Using LangGraph, a developer explicitly defines nodes, which are functions or tools, and edges, which dictate the path of execution. This graph structure allows for complex, cyclical reasoning where the system can loop, retry tasks, and make decisions based on an explicitly managed state object that is passed between nodes. It gives the developer fine-grained control over a single agent's thought process or the ability to construct a multi-agent system from first principles.

LangChain 在最基础层面运作,提供组件和标准化接口以创建操作序列,例如调用模型并解析其输出。LangGraph 通过引入更灵活强大的控制流对此进行扩展;它将智能体工作流视为有状态图。使用 LangGraph,开发者显式定义节点(函数或工具)和边(决定执行路径)。这种图结构支持复杂循环推理,系统可循环执行、重试任务,并基于节点间传递的显式管理状态对象做出决策。它为开发者提供了对单个智能体行为的细粒度控制,或从第一性原理构建多智能体系统。

Google's ADK abstracts away much of this low-level graph construction. Instead of asking the developer to define every node and edge, it provides pre-built architectural patterns for multi-agent interaction. For instance, ADK has built-in agent types like SequentialAgent or ParallelAgent, which manage the flow of control between different agents automatically. It is architected around the concept of a "team" of agents, often with a primary agent delegating tasks to specialized sub-agents. State and session management are handled more implicitly by the framework, providing a more cohesive but less granular approach than LangGraph's explicit state passing. Therefore, while LangGraph gives you the detailed tools to design the intricate wiring of a single robot or a team, Google's ADK gives you a factory assembly line designed to build and manage a fleet of robots that already know how to work together.

Google 的 ADK 抽象了大部分此类低级图构建工作。ADK 不要求开发者定义每个节点和边,而是为多智能体交互提供预构建的架构模式。例如,ADK 包含 SequentialAgent 或 ParallelAgent 等内置智能体类型,它们自动管理不同智能体间的控制流。其架构围绕智能体"团队"概念设计,通常由主智能体将任务委派给专业化子智能体。状态和会话管理由框架更隐式地处理,提供了比 LangGraph 显式状态传递更连贯但精细度稍低的方法。因此,若将 LangGraph 比作提供详细工具以设计单个机器人或团队复杂接线的工具箱,Google 的 ADK 则如同一个工厂装配线,旨在构建和管理一支已具备协同工作能力的机器人舰队。

```python
from google.adk.agents import LlmAgent
from google.adk.tools import google_search

dice_agent = LlmAgent(
    model="gemini-2.0-flash-exp",
    name="question_answer_agent",
    description="A helpful assistant agent that can answer questions.",
    instruction="""Respond to the query using google search""",
    tools=[google_search],
)
```

This code creates a search-augmented agent. When this agent receives a question, it will not just rely on its pre-existing knowledge. Instead, following its instructions, it will use the Google Search tool to find relevant, real-time information from the web and then use that information to construct its answer.

此代码创建了一个搜索增强型智能体。当该智能体接收问题时,不会仅依赖其既有知识。相反,遵循其指令,它将使用 Google 搜索工具从网络查找相关实时信息,并据此构建答案。

## Crew.AI

CrewAI offers an orchestration framework for building multi-agent systems by focusing on collaborative roles and structured processes. It operates at a higher level of abstraction than foundational toolkits, providing a conceptual model that mirrors a human team. Instead of defining the granular flow of logic as a graph, the developer defines the actors and their assignments, and CrewAI manages their interaction.

CrewAI 提供了一个编排框架,通过聚焦协作角色与结构化流程来构建多智能体系统。它在比基础工具包更高的抽象层级运作,提供模拟人类团队的概念模型。开发者无需将逻辑细粒度流程定义为图,而是定义参与者及其任务分配,由 CrewAI 管理其交互。

The core components of this framework are Agents, Tasks, and the Crew. An Agent is defined not just by its function but by a persona, including a specific role, a goal, and a backstory, which guides its behavior and communication style. A Task is a discrete unit of work with a clear description and expected output, assigned to a specific Agent. The Crew is the cohesive unit that contains the Agents and the list of Tasks, and it executes a predefined Process. This process dictates the workflow, which is typically either sequential, where the output of one task becomes the input for the next in line, or hierarchical, where a manager-like agent delegates tasks and coordinates the workflow among other agents.

该框架核心组件包括智能体、任务和团队。智能体不仅由功能定义,还通过角色、目标和背景故事等角色特征来定义,这些特征指导其行为与沟通风格。任务是具备明确描述和预期输出的离散工作单元,分配给特定智能体。团队是包含智能体和任务列表的协调单元,执行预定义的流程。此流程决定工作流模式,通常为顺序型(一个任务的输出成为下一任务的输入)或层级型(经理型智能体分配任务并协调其他智能体间的交互)。

When compared to other frameworks, CrewAI occupies a distinct position. It moves away from the low-level, explicit state management and control flow of LangGraph, where a developer wires together every node and conditional edge. Instead of building a state machine, the developer designs a team charter. While Google's ADK provides a comprehensive, production-oriented platform for the entire agent lifecycle, CrewAI concentrates specifically on the logic of agent collaboration and for simulating a team of specialists.

与其他框架相比,CrewAI 定位独特。它脱离了 LangGraph 的低层级、显式状态管理与控制流(后者要求开发者连接每个节点与条件边)。开发者不是构建状态机,而是设计团队章程。尽管 Google 的 ADK 为整个智能体生命周期提供了全面、生产就绪的平台,CrewAI 则专注于智能体协作与专家团队模拟。

```python
@crew
def crew(self) -> Crew:
    """Creates the research crew"""
    return Crew(
      agents=self.agents,
      tasks=self.tasks,
      process=Process.sequential,
      verbose=True,
    )
```

This code sets up a sequential workflow for a team of AI agents, where they tackle a list of tasks in a specific order, with detailed logging enabled to monitor their progress.

此代码为 AI 智能体团队配置了顺序工作流,智能体按特定顺序处理任务列表,并启用详细日志以监控进度。

## Other agent development framework

## 其他智能体框架

**Microsoft AutoGen**: AutoGen is a framework centered on orchestrating multiple agents that solve tasks through conversation. Its architecture enables agents with distinct capabilities to interact, allowing for complex problem decomposition and collaborative resolution. The primary advantage of AutoGen is its flexible, conversation-driven approach that supports dynamic and complex multi-agent interactions. However, this conversational paradigm can lead to less predictable execution paths and may require sophisticated prompt engineering to ensure tasks converge efficiently.

**Microsoft AutoGen**:AutoGen 是一个以对话方式编排多智能体任务为核心的框架。其架构使具备不同能力的智能体能够协作,支持复杂问题分解与协作解决。AutoGen 主要优势在于其灵活的对话驱动方法,可应对动态复杂的多智能体交互场景。这种对话范式可能导致执行路径预测性降低,且需复杂提示工程以确保任务高效收敛。

**LlamaIndex**: LlamaIndex is fundamentally a data framework designed to connect large language models with external and private data sources. It excels at creating sophisticated data ingestion and retrieval pipelines, which are essential for building knowledgeable agents that can perform RAG. While its data indexing and querying capabilities are exceptionally powerful for creating context-aware agents, its native tools for complex agentic control flow and multi-agent orchestration are less developed compared to agent-first frameworks. LlamaIndex is optimal when the core technical challenge is data retrieval and synthesis.

**LlamaIndex**:LlamaIndex 本质上是数据框架,旨在连接大语言模型与外部及私有数据源。它擅长构建复杂的数据摄取与检索管道,这对创建能执行 RAG 的知识型智能体至关重要。尽管其数据索引与查询能力对构建情境感知智能体非常关键,但与智能体优先的框架相比,其在复杂智能体控制流和多智能体编排方面提供的工具较少。当核心技术挑战为数据检索与综合时,LlamaIndex 是最佳选择。

**Haystack**: Haystack is an open-source framework engineered for building scalable and production-ready search systems powered by language models. Its architecture is composed of modular, interoperable nodes that form pipelines for document retrieval, question answering, and summarization. The main strength of Haystack is its focus on performance and scalability for large-scale information retrieval tasks, making it suitable for enterprise-grade applications. A potential trade-off is that its design, optimized for search pipelines, can be more rigid for implementing highly dynamic and creative agentic behaviors.

**Haystack**:Haystack 是专为构建语言模型驱动的可扩展、生产就绪搜索系统而设计的开源框架。其架构由模块化、可互操作的节点组成,这些节点构成文档检索、问答和摘要的管道。Haystack 主要优势在于其对大规模信息检索任务性能与可扩展性的专注,使其适用于企业级应用。潜在权衡在于,其针对搜索管道优化的设计在实现高度动态和创造性智能体行为时可能较为僵化。

**MetaGPT**: MetaGPT implements a multi-agent system by assigning roles and tasks based on a predefined set of Standard Operating Procedures (SOPs). This framework structures agent collaboration to mimic a software development company, with agents taking on roles like product managers or engineers to complete complex tasks. This SOP-driven approach results in highly structured and coherent outputs, which is a significant advantage for specialized domains like code generation. The framework's primary limitation is its high degree of specialization, making it less adaptable for general-purpose agentic tasks outside of its core design.

**MetaGPT**:MetaGPT 通过基于预定义标准操作程序(SOP)分配角色和任务来实现多智能体协作。该框架将智能体协作结构化为模拟一家软件开发公司,智能体承担产品经理或工程师等角色完成复杂任务。这种 SOP 驱动方法产生高度结构化且连贯的输出,对代码生成等专业领域是显著优势。该框架主要局限在于其高度专业化,使其在核心设计范畴外的通用智能体任务适应性较弱。

**SuperAGI**: SuperAGI is an open-source framework designed to provide a complete lifecycle management system for autonomous agents. It includes features for agent provisioning, monitoring, and a graphical interface, aiming to enhance the reliability of agent execution. The key benefit is its focus on production-readiness, with built-in mechanisms to handle common failure modes like looping and to provide observability into agent performance. A potential drawback is that its comprehensive platform approach can introduce more complexity and overhead than a more lightweight, library-based framework.

**SuperAGI**:SuperAGI 是旨在为自主智能体提供完整生命周期管理系统的开源框架。它包括智能体配置、监控和图形界面等功能,旨在提升智能体执行的可靠性。其关键优势在于对生产就绪性的关注,具备处理循环等常见故障模式的内置机制,并提供智能体性能可视化。其潜在缺点在于,与更轻量级库框架相比,其全面平台方法可能引入更多复杂性与开销。

**Semantic Kernel**: Developed by Microsoft, Semantic Kernel is an SDK that integrates large language models with conventional programming code through a system of "plugins" and "planners." It allows an LLM to invoke native functions and orchestrate workflows, effectively treating the model as a reasoning engine within a larger software application. Its primary strength is its seamless integration with existing enterprise codebases, particularly in .NET and Python environments. The conceptual overhead of its plugin and planner architecture can present a steeper learning curve compared to more straightforward agent frameworks.

**Semantic Kernel**:由 Microsoft 开发,Semantic Kernel 是通过"插件"和"规划器"系统将大语言模型与传统编程代码集成的 SDK。它允许 LLM 调用原生函数并编排工作流,有效将模型视为大型软件应用中的推理引擎。其主要优势是与现有企业代码库(尤其在 .NET 和 Python 环境)的无缝集成。其插件与规划器架构的概念开销可能带来比更直接的智能体框架更陡峭的学习曲线。

**Strands Agents:** An AWS lightweight and flexible SDK that uses a model-driven approach for building and running AI agents. It is designed to be simple and scalable, supporting everything from basic conversational assistants to complex multi-agent autonomous systems. The framework is model-agnostic, offering broad support for various LLM providers, and includes native integration with the MCP for easy access to external tools. Its core advantage is its simplicity and flexibility, with a customizable agent loop that is easy to get started with. A potential trade-off is that its lightweight design means developers may need to build out more of the surrounding operational infrastructure, such as advanced monitoring or lifecycle management systems, which more comprehensive frameworks might provide out of the box.

**Strands Agents**:AWS 的轻量级灵活 SDK,采用模型驱动方法构建和运行 AI 智能体。其设计简洁且可扩展,支持从基础对话助手到复杂多智能体系统的各类场景。该框架与模型无关,广泛支持多种 LLM 提供商,并包含与 MCP 的原生集成以便轻松访问外部工具。其核心优势是简洁性与灵活性,提供易于上手的可定制智能体构建模块。其权衡在于,其轻量级设计意味着开发者可能需要构建更多周边运营基础设施(如高级监控或生命周期管理系统),而更全面框架可能提供开箱即用功能。

## Conclusion

## 结论

The landscape of agentic frameworks offers a diverse spectrum of tools, from low-level libraries for defining agent logic to high-level platforms for orchestrating multi-agent collaboration. At the foundational level, LangChain enables simple, linear workflows, while LangGraph introduces stateful, cyclical graphs for more complex reasoning. Higher-level frameworks like CrewAI and Google's ADK shift the focus to orchestrating teams of agents with predefined roles, while others like LlamaIndex specialize in data-intensive applications. This variety presents developers with a core trade-off between the granular control of graph-based systems and the streamlined development of more opinionated platforms. Consequently, selecting the right framework hinges on whether the application requires a simple sequence, a dynamic reasoning loop, or a managed team of specialists. Ultimately, this evolving ecosystem empowers developers to build increasingly sophisticated AI systems by choosing the precise level of abstraction their project demands.

智能体框架生态提供了多样化工具,涵盖从定义智能体的低级库到编排多智能体协作的高级平台。在基础层,LangChain 支持简单线性工作流,而 LangGraph 引入有状态循环图以实现更复杂推理。如 CrewAI 和 Google ADK 等高级框架将重心转向编排具预定义角色的智能体团队,而 LlamaIndex 等其他框架则专注数据密集型应用。这种多样性为开发者带来了基于图系统的细粒度控制与更具指导性平台的简化开发之间的核心权衡。因此,框架选择取决于应用需求:简单序列、动态推理循环还是受管专家团队。最终,这一不断演进的技术生态系统使开发者能通过选择项目所需的精确抽象级别,构建日益复杂的 AI 系统。

## References

## 参考文献

1. LangChain, [https://www.langchain.com/](https://www.langchain.com/)
2. LangGraph, [https://www.langchain.com/langgraph](https://www.langchain.com/langgraph)
3. Google's ADK, [https://google.github.io/adk-docs/](https://google.github.io/adk-docs/)
4. Crew.AI, [https://docs.crewai.com/en/introduction](https://docs.crewai.com/en/introduction)


## /bilingual/Appendix D - Building an Agent with AgentSpace (on-line only).md

---
layout: bilingual
lang: bilingual
---

# Appendix D - Building an Agent with AgentSpace

# 附录 D - 使用 AgentSpace 构建智能体

## Overview

## 概述

AgentSpace is a platform designed to facilitate an "agent-driven enterprise" by integrating artificial intelligence into daily workflows. At its core, it provides a unified search capability across an organization's entire digital footprint, including documents, emails, and databases. This system utilizes advanced AI models, like Google's Gemini, to comprehend and synthesize information from these varied sources.

AgentSpace 是一个旨在通过将人工智能融入日常工作流程来推动"智能体驱动型企业"发展的平台。其核心能力在于为组织的整个数字资产(包括文档、电子邮件和数据库)提供统一的搜索功能。该系统利用先进的 AI 模型(如 Google 的 Gemini)来理解并整合来自这些多样化来源的信息。

The platform enables the creation and deployment of specialized AI "agents" that can perform complex tasks and automate processes. These agents are not merely chatbots; they can reason, plan, and execute multi-step actions autonomously. For instance, an agent could research a topic, compile a report with citations, and even generate an audio summary.

该平台支持创建和部署专业化的 AI "智能体",这些智能体执行复杂任务并实现流程自动化。它们不仅是聊天机器人,更具备自主推理、规划和执行多步骤操作的能力。例如,一个智能体可以研究特定主题,编纂带引用的报告,甚至生成音频摘要。

To achieve this, AgentSpace constructs an enterprise knowledge graph, mapping the relationships between people, documents, and data. This allows the AI to understand context and deliver more relevant and personalized results. The platform also includes a no-code interface called Agent Designer for creating custom agents without requiring deep technical expertise.

为了实现这一目标,AgentSpace 构建了企业知识图谱,映射人员、文档和数据之间的关联关系。这使得 AI 能够理解上下文,提供更相关且个性化的结果。平台还包含名为 Agent Designer(智能体设计器)的无代码界面,无需深厚技术专长即可创建自定义智能体。

Furthermore, AgentSpace supports a multi-agent system where different AI agents can communicate and collaborate through an open protocol known as the Agent2Agent (A2A) Protocol. This interoperability allows for more complex and orchestrated workflows. Security is a foundational component, with features like role-based access controls and data encryption to protect sensitive enterprise information. Ultimately, AgentSpace aims to enhance productivity and decision-making by embedding intelligent, autonomous systems directly into an organization's operational fabric.

此外,AgentSpace 支持多智能体系统,不同的 AI 智能体可通过名为 Agent2Agent(A2A)协议的开放协议进行通信与协作。这种互操作性支持更复杂、协调的工作流。安全性是其基础架构的核心组成部分,具备基于角色的访问控制和数据加密等功能,以保护企业敏感信息。最终,AgentSpace 旨在通过将智能自主系统直接嵌入组织运营架构,提升生产力与决策水平。

## How to build an Agent with AgentSpace UI

## 如何使用 AgentSpace UI 构建智能体

Figure 1 illustrates how to access AgentSpace by selecting AI Applications from the Google Cloud Console.

![How to use Google Cloud Console to access AgentSpace](../images/appendix-d/image1.png)

Fig. 1: How to use Google Cloud Console to access AgentSpace

图 1 展示了如何通过 Google Cloud Console 选择 AI Applications 来访问 AgentSpace。

Your agent can be connected to various services, including Calendar, Google Mail, Workday, Jira, Outlook, and Service Now (see Fig. 2).

![Integrate with diverse services, including Google and third-party platforms](../images/appendix-d/image2.png)

Fig. 2: Integrate with diverse services, including Google and third-party platforms.

您的智能体可以连接到多种服务,包括 Calendar、Google Mail、Workday、Jira、Outlook 和 Service Now(见图 2)。

The Agent can then utilize its own prompt, chosen from a gallery of pre-made prompts provided by Google, as illustrated in Fig. 3.

![Google's Gallery of Pre-assembled prompts](../images/appendix-d/image3.png)

Fig. 3: Google's Gallery of Pre-assembled prompts

随后,智能体可以使用自己的提示词,也可以从 Google 提供的预制提示词库中选择,如图 3 所示。

Alternatively, you can create your own prompt as in Fig. 4, which will then be used by your agent.

![Customizing the Agent's Prompt](../images/appendix-d/image4.png)

Fig. 4: Customizing the Agent's Prompt

或者,您可以创建自己的提示词,如图 4 所示,供您的智能体使用。

AgentSpace offers a number of advanced features such as integration with datastores to store your own data, integration with Google Knowledge Graph or with your private Knowledge Graph, Web interface for exposing your agent to the Web, and Analytics to monitor usage, and more (see Fig. 5).

![AgentSpace advanced capabilities](../images/appendix-d/image5.png)

Fig. 5: AgentSpace advanced capabilities

AgentSpace 提供多项高级功能,例如与数据存储集成以存储自有数据、与 Google 知识图谱或私有知识图谱集成、用于向 Web 公开智能体的 Web 界面、使用情况监控分析等(见图 5)。

Upon completion, the AgentSpace chat interface (Fig. 6) will be accessible.

![The AgentSpace User Interface for initiating a chat with your Agent](../images/appendix-d/image6.png)

Fig. 6: The AgentSpace User Interface for initiating a chat with your Agent.

配置完成后,即可访问 AgentSpace 聊天界面(图 6)。

## Conclusion

## 结论

In conclusion, AgentSpace provides a functional framework for developing and deploying AI agents within an organization's existing digital infrastructure. The system's architecture links complex backend processes, such as autonomous reasoning and enterprise knowledge graph mapping, to a graphical user interface for agent construction. Through this interface, users can configure agents by integrating various data services and defining their operational parameters via prompts, resulting in customized, context-aware automated systems.

综上所述,AgentSpace 为在组织现有数字基础设施中开发和部署 AI 智能体提供了实用框架。该系统的架构将复杂的后端流程(如自主推理和企业知识图谱映射)与用于构建智能体的图形用户界面相连接。通过该界面,用户可整合各类数据服务,并通过提示词定义操作参数,从而配置出定制化、情境感知的自动化系统。

This approach abstracts the underlying technical complexity, enabling the construction of specialized multi-agent systems without requiring deep programming expertise. The primary objective is to embed automated analytical and operational capabilities directly into workflows, thereby increasing process efficiency and enhancing data-driven analysis. For practical instruction, hands-on learning modules are available, such as the "Build a Gen AI Agent with Agentspace" lab on Google Cloud Skills Boost, which provides a structured environment for skill acquisition.

这种方法抽象了底层的技术复杂性,使得无需深厚编程知识即可构建专业化的多智能体系统。其主要目标是将自动化分析与操作能力直接嵌入工作流程中,从而提升流程效率、强化数据驱动分析。对于实践指导,现有实践学习模块可供使用,例如 Google Cloud Skills Boost 平台上的"使用 Agentspace 构建 Gen AI 智能体"实验,为技能习得提供了结构化环境。

## References

## 参考文献

1. Create a no-code agent with Agent Designer, [https://cloud.google.com/agentspace/agentspace-enterprise/docs/agent-designer](https://cloud.google.com/agentspace/agentspace-enterprise/docs/agent-designer)

2. Google Cloud Skills Boost, [https://www.cloudskillsboost.google/](https://www.cloudskillsboost.google/)


## /bilingual/Appendix E - AI Agents on the CLI.md

---
layout: bilingual
lang: bilingual
---

# Appendix E - AI Agents on the CLI

# 附录 E - 命令行界面中的 AI 智能体

## Introduction

## 引言

The developer's command line, long a bastion of precise, imperative commands, is undergoing a profound transformation. It is evolving from a simple shell into an intelligent, collaborative workspace powered by a new class of tools: AI Agent Command-Line Interfaces (CLIs). These agents move beyond merely executing commands; they understand natural language, maintain context about your entire codebase, and can perform complex, multi-step tasks that automate significant parts of the development lifecycle.

开发者的命令行界面,长期以来都是精确命令式指令的堡垒,如今正经历着深刻的变革。它正在从一个简单的 Shell 演变为由一类新型工具驱动的智能协作工作空间:AI 智能体命令行界面(CLI)。这些智能体不仅仅是执行命令;它们理解自然语言,维护整个代码库的上下文,并能执行复杂的多步骤任务,自动化开发生命周期的重要环节。

This guide provides an in-depth look at four leading players in this burgeoning field, exploring their unique strengths, ideal use cases, and distinct philosophies to help you determine which tool best fits your workflow. It is important to note that many of the example use cases provided for a specific tool can often be accomplished by the other agents as well. The key differentiator between these tools frequently lies in the quality, efficiency, and nuance of the results they are able to achieve for a given task. There are specific benchmarks designed to measure these capabilities, which will be discussed in the following sections.

本指南深入剖析了这一新兴领域中的四个主要参与者,探索它们的独特优势、理想用例和设计理念,以帮助您确定最适合您工作流的工具。需要注意的是,为特定工具提供的许多示例用例通常也可以由其他智能体完成。这些工具之间的关键区别往往在于它们为给定任务所能达成结果的质量、效率和精细度。后续章节将讨论专门设计用于衡量这些能力的基准测试。

## Claude CLI (Claude Code)

## Claude CLI (Claude Code)

Anthropic's Claude CLI is engineered as a high-level coding agent with a deep, holistic understanding of a project's architecture. Its core strength is its "agentic" nature, allowing it to create a mental model of your repository for complex, multi-step tasks. The interaction is highly conversational, resembling a pair programming session where it explains its plans before executing. This makes it ideal for professional developers working on large-scale projects involving significant refactoring or implementing features with broad architectural impacts.

Anthropic 的 Claude CLI 被设计为一款高级编码智能体,对项目架构具有深度的全局理解。其核心优势在于它的"智能体"特性,能够为复杂的多步骤任务构建代码库的心智模型。交互过程高度对话化,类似于结对编程会话,它会在执行前阐述其计划。这使其成为从事大型项目的专业开发者的理想选择,这些项目涉及重大重构或实现具有广泛架构影响的功能。

**Example Use Cases:**

1. **Large-Scale Refactoring:** You can instruct it: "Our current user authentication relies on session cookies. Refactor the entire codebase to use stateless JWTs, updating the login/logout endpoints, middleware, and frontend token handling." Claude will then read all relevant files and perform the coordinated changes.
2. **API Integration:** After being provided with an OpenAPI specification for a new weather service, you could say: "Integrate this new weather API. Create a service module to handle the API calls, add a new component to display the weather, and update the main dashboard to include it."
3. **Documentation Generation**: Pointing it to a complex module with poorly documented code, you can ask: "Analyze the ./src/utils/data_processing.js file. Generate comprehensive TSDoc comments for every function, explaining its purpose, parameters, and return value."

**示例用例:**

1. **大规模重构:** 您可以指示:"我们当前的用户认证依赖会话 cookie。请重构整个代码库以采用无状态 JWT,更新登录/登出端点、中间件及前端令牌处理逻辑。"Claude 将读取所有相关文件并执行协调一致的更改。
2. **API 集成:** 在提供新天气服务的 OpenAPI 规范后,您可以指令:"集成此新天气 API。创建服务模块处理 API 调用,新增组件展示天气信息,并更新主仪表板以包含该组件。"
3. **文档生成:** 指向文档匮乏的复杂模块,您可以要求:"分析 ./src/utils/data_processing.js 文件。为每个函数生成全面的 TSDoc 注释,阐明其用途、参数及返回值。"

Claude CLI functions as a specialized coding assistant, with inherent tools for core development tasks, including file ingestion, code structure analysis, and edit generation. Its deep integration with Git facilitates direct branch and commit management. The agent's extensibility is mediated by the Multi-tool Control Protocol (MCP), enabling users to define and integrate custom tools. This allows for interactions with private APIs, database queries, and execution of project-specific scripts. This architecture positions the developer as the arbiter of the agent's functional scope, effectively characterizing Claude as a reasoning engine augmented by user-defined tooling.

Claude CLI 作为专业化的编码助手,内置了核心开发任务工具,包括文件读取、代码结构分析和编辑生成。它与 Git 的深度集成支持直接进行分支和提交管理。该智能体的可扩展性通过多工具控制协议(MCP)实现,允许用户定义和集成自定义工具。这使其能够与私有 API 交互、执行数据库查询及运行项目特定脚本。这种架构将开发者定位为智能体功能范围的决策者,实质上是将 Claude 塑造为由用户定义工具增强的推理引擎。

## Gemini CLI

## Gemini CLI

Google's Gemini CLI is a versatile, open-source AI agent designed for power and accessibility. It stands out with the advanced Gemini 2.5 Pro model, a massive context window, and multimodal capabilities (processing images and text). Its open-source nature, generous free tier, and "Reason and Act" loop make it a transparent, controllable, and excellent all-rounder for a broad audience, from hobbyists to enterprise developers, especially those within the Google Cloud ecosystem.

Google 的 Gemini CLI 是一款功能强大的开源 AI 智能体,专为高性能和易用性而设计。它凭借先进的 Gemini 2.5 Pro 模型、超大上下文窗口以及多模态能力(可处理图像和文本)脱颖而出。其开源特性、慷慨的免费额度以及"推理与行动"循环机制,使其成为一款透明、可控且出色的全能型工具,受众广泛——从业余爱好者到企业开发者,尤其适合 Google Cloud 生态系统的用户。

**Example Use Cases:**

1. **Multimodal Development:** You provide a screenshot of a web component from a design file (gemini describe component.png) and instruct it: "Write the HTML and CSS code to build a React component that looks exactly like this. Make sure it's responsive."
2. **Cloud Resource Management:** Using its built-in Google Cloud integration, you can command: "Find all GKE clusters in the production project that are running versions older than 1.28 and generate a gcloud command to upgrade them one by one."
3. **Enterprise Tool Integration (via MCP):** A developer provides Gemini with a custom tool called get-employee-details that connects to the company's internal HR API. The prompt is: "Draft a welcome document for our new hire. First, use the get-employee-details --id=E90210 tool to fetch their name and team, and then populate the welcome_template.md with that information."
4. **Large-Scale Refactoring**: A developer needs to refactor a large Java codebase to replace a deprecated logging library with a new, structured logging framework. They can use Gemini with a prompt like: Read all *.java files in the 'src/main/java' directory. For each file, replace all instances of the 'org.apache.log4j' import and its 'Logger' class with 'org.slf4j.Logger' and 'LoggerFactory'. Rewrite the logger instantiation and all .info(), .debug(), and .error() calls to use the new structured format with key-value pairs.

**示例用例:**

1. **多模态开发:** 您提供设计稿中的 Web 组件截图(gemini describe component.png)并指示:"编写 HTML 和 CSS 代码,构建外观与此完全一致的 React 组件。确保具备响应式设计。"
2. **云资源管理:** 利用其内置 Google Cloud 集成,您可以命令:"查找生产项目中所有运行版本低于 1.28 的 GKE 集群,并生成逐个升级这些集群的 gcloud 命令。"
3. **企业工具集成(通过 MCP):** 开发者为 Gemini 配置名为 get-employee-details 的自定义工具,该工具连接公司内部 HR API。提示词为:"为新员工起草欢迎文档。首先使用 get-employee-details --id=E90210 工具获取其姓名与团队信息,随后用该信息填充 welcome_template.md。"
4. **大规模重构:** 开发者需重构大型 Java 代码库,以新型结构化日志框架替换已弃用的日志库。他们可对 Gemini 使用如下提示:读取 'src/main/java' 目录下所有 *.java 文件。针对每个文件,将 'org.apache.log4j' 导入及其 'Logger' 类实例替换为 'org.slf4j.Logger' 与 'LoggerFactory'。重写日志记录器实例化及所有 .info()、.debug() 和 .error() 调用,采用带键值对的新结构化格式。

Gemini CLI is equipped with a suite of built-in tools that allow it to interact with its environment. These include tools for file system operations (like reading and writing), a shell tool for running commands, and tools for accessing the internet via web fetching and searching. For broader context, it uses specialized tools to read multiple files at once and a memory tool to save information for later sessions. This functionality is built on a secure foundation: sandboxing isolates the model's actions to prevent risk, while MCP servers act as a bridge, enabling Gemini to safely connect to your local environment or other APIs.

Gemini CLI 配备了一套内置工具,使其能够与环境交互。这些工具包括用于文件系统操作(如读取和写入)的工具、用于运行命令的 Shell 工具,以及通过网页抓取和搜索访问互联网的工具。为获取更广泛的上下文,它使用专用工具批量读取文件,并利用内存工具保存信息供后续会话使用。这些功能构建在安全基础之上:沙箱机制隔离模型操作以防范风险,而 MCP 服务器充当桥梁,使 Gemini 能够安全连接至本地环境或其他 API。

## Aider

## Aider

Aider is an open-source AI coding assistant that acts as a true pair programmer by working directly on your files and committing changes to Git. Its defining feature is its directness; it applies edits, runs tests to validate them, and automatically commits every successful change. Being model-agnostic, it gives users complete control over cost and capabilities. Its git-centric workflow makes it perfect for developers who value efficiency, control, and a transparent, auditable trail of all code modifications.

Aider 是一款开源 AI 编码助手,通过直接操作文件并将变更提交至 Git,扮演真正的结对程序员角色。其标志性特征是直接性:它应用编辑、运行测试进行验证,并自动提交每个成功的变更。作为与模型无关的工具,它赋予用户对成本和能力的完全控制权。其以 Git 为中心的工作流,使其成为注重效率、控制力以及代码修改全程透明可审计的开发者的理想选择。

**Example Use Cases:**

1. **Test-Driven Development (TDD):** A developer can say: "Create a failing test for a function that calculates the factorial of a number." After Aider writes the test and it fails, the next prompt is: "Now, write the code to make the test pass." Aider implements the function and runs the test again to confirm.
2. **Precise Bug Squashing:** Given a bug report, you can instruct Aider: "The calculate_total function in billing.py fails on leap years. Add the file to the context, fix the bug, and verify your fix against the existing test suite."
3. **Dependency Updates:** You could instruct it: "Our project uses an outdated version of the 'requests' library. Please go through all Python files, update the import statements and any deprecated function calls to be compatible with the latest version, and then update requirements.txt."

**示例用例:**

1. **测试驱动开发(TDD):** 开发者可指令:"为计算数字阶乘的函数创建失败测试。"Aider 编写测试并确认失败后,后续提示为:"现在编写代码使测试通过。"Aider 实现函数后再次运行测试以验证。
2. **精准 Bug 修复:** 给定 bug 报告,您可以指示 Aider:"billing.py 中的 calculate_total 函数在闰年计算失败。将文件添加上下文,修复此 bug,并依据现有测试套件验证修复。"
3. **依赖项更新:** 您可以指令:"我们项目使用的 'requests' 库版本过时。请检查所有 Python 文件,更新导入语句及任何已弃用的函数调用以兼容最新版本,随后更新 requirements.txt。"

## GitHub Copilot CLI

## GitHub Copilot CLI

GitHub Copilot CLI extends the popular AI pair programmer into the terminal, with its primary advantage being its native, deep integration with the GitHub ecosystem. It understands the context of a project *within GitHub*. Its agent capabilities allow it to be assigned a GitHub issue, work on a fix, and submit a pull request for human review.

GitHub Copilot CLI 将广受欢迎的 AI 结对编程体验延伸至终端环境,其核心优势在于与 GitHub 生态系统的原生深度集成。它能理解项目*在 GitHub 中*的上下文。其智能体功能支持分配 GitHub issue、实施修复并提交拉取请求供人工审核。

**Example Use Cases:**

1. **Automated Issue Resolution:** A manager assigns a bug ticket (e.g., "Issue #123: Fix off-by-one error in pagination") to the Copilot agent. The agent then checks out a new branch, writes the code, and submits a pull request referencing the issue, all without manual developer intervention.
2. **Repository-Aware Q&A:** A new developer on the team can ask: "Where in this repository is the database connection logic defined, and what environment variables does it require?" Copilot CLI uses its awareness of the entire repo to provide a precise answer with file paths.
3. **Shell Command Helper:** When unsure about a complex shell command, a user can ask: gh? find all files larger than 50MB, compress them, and place them in an archive folder. Copilot will generate the exact shell command needed to perform the task.

**示例用例:**

1. **自动化 Issue 解决:** 管理者将 bug 工单(如"Issue #123:修复分页差一错误")分配给 Copilot 智能体。随后智能体创建新分支、编写代码并提交关联该 issue 的拉取请求,全程无需开发者手动介入。
2. **仓库感知问答:** 团队新成员可询问:"本仓库中数据库连接逻辑定义于何处?需要哪些环境变量?"Copilot CLI 利用其对整个仓库的认知提供包含文件路径的精确答案。
3. **Shell 命令助手:** 当面对复杂 shell 命令不确定时,用户可输入:gh? find all files larger than 50MB, compress them, and place them in an archive folder. Copilot 将生成执行该任务所需的确切 shell 命令。

## Terminal-Bench: A Benchmark for AI Agents in Command-Line Interfaces

## Terminal-Bench:命令行界面中 AI 智能体基准测试框架

Terminal-Bench is a novel evaluation framework designed to assess the proficiency of AI agents in executing complex tasks within a command-line interface. The terminal is identified as an optimal environment for AI agent operation due to its text-based, sandboxed nature. The initial release, Terminal-Bench-Core-v0, comprises 80 manually curated tasks spanning domains such as scientific workflows and data analysis. To ensure equitable comparisons, Terminus, a minimalistic agent, was developed to serve as a standardized testbed for various language models. The framework is designed for extensibility, allowing for the integration of diverse agents through containerization or direct connections. Future developments include enabling massively parallel evaluations and incorporating established benchmarks. The project encourages open-source contributions for task expansion and collaborative framework enhancement.

Terminal-Bench 是一套创新的评估框架,专用于衡量 AI 智能体在命令行界面中执行复杂任务的熟练程度。鉴于其基于文本的沙箱特性,终端被确认为 AI 智能体的理想环境。初始版本 Terminal-Bench-Core-v0 包含 80 项人工精选的任务,涵盖科学工作流与数据分析等领域。为确保公平对比,开发了极简智能体 Terminus 作为各类语言模型的标准化测试平台。该框架具备高度可扩展性,支持通过容器化或直接连接集成多样化智能体。未来规划包括实现大规模并行评估及整合现有基准测试。项目鼓励开源社区贡献任务扩展与框架协同优化。

## Conclusion

## 结论

The emergence of these powerful AI command-line agents marks a fundamental shift in software development, transforming the terminal into a dynamic and collaborative environment. As we've seen, there is no single "best" tool; instead, a vibrant ecosystem is forming where each agent offers a specialized strength. The ideal choice depends entirely on the developer's needs: Claude for complex architectural tasks, Gemini for versatile and multimodal problem-solving, Aider for git-centric and direct code editing, and GitHub Copilot for seamless integration into the GitHub workflow. As these tools continue to evolve, proficiency in leveraging them will become an essential skill, fundamentally changing how developers build, debug, and manage software.

这些功能强大的 AI 命令行智能体的出现,标志着软件开发范式的根本性转变——将终端转化为动态协作环境。正如我们所见,不存在单一的"最佳"工具;相反,一个生机勃勃的生态系统正在成型,每个智能体都有其独特专长。理想选择完全取决于开发者需求:Claude 擅长复杂架构任务,Gemini 强于多功能多模态问题求解,Aider 专注 Git 中心化直接代码编辑,GitHub Copilot 则无缝融入 GitHub 工作流。随着这些工具的持续演进,熟练运用它们将成为核心技能,从根本上重塑开发者构建、调试与管理软件的方式。

## References

## 参考文献

 1. Anthropic. *Claude*. [https://docs.anthropic.com/en/docs/claude-code/cli-reference](https://docs.anthropic.com/en/docs/claude-code/cli-reference)
 2. Google Gemini Cli [https://github.com/google-gemini/gemini-cli](https://github.com/google-gemini/gemini-cli)
 3. Aider. [https://aider.chat/](https://aider.chat/)
 4. GitHub *Copilot CLI* [https://docs.github.com/en/copilot/github-copilot-enterprise/copilot-cli](https://docs.github.com/en/copilot/github-copilot-enterprise/copilot-cli)
 5. Terminal Bench: [https://www.tbench.ai/](https://www.tbench.ai/)


## /bilingual/Appendix G -  Coding agents.md

# Appendix G - Coding Agents

# 附录 G - 编码智能体

## Vibe Coding: A Starting Point

## Vibe 编码:入门路径

"Vibe coding" has become a powerful technique for rapid innovation and creative exploration. This practice involves using LLMs to generate initial drafts, outline complex logic, or build quick prototypes, significantly reducing initial friction. It is invaluable for overcoming the "blank page" problem, enabling developers to quickly transition from a vague concept to tangible, runnable code. Vibe coding is particularly effective when exploring unfamiliar APIs or testing novel architectural patterns, as it bypasses the immediate need for perfect implementation. The generated code often acts as a creative catalyst, providing a foundation for developers to critique, refactor, and expand upon. Its primary strength lies in its ability to accelerate the initial discovery and ideation phases of the software lifecycle. However, while vibe coding excels at brainstorming, developing robust, scalable, and maintainable software demands a more structured approach, shifting from pure generation to a collaborative partnership with specialized coding agents.

"Vibe 编码"已发展为快速创新与创意探索的高效技术。该实践通过运用 LLM 生成初始草稿、梳理复杂逻辑或构建快速原型,显著降低启动门槛。它能有效帮助开发者克服"空白页"困境,从模糊概念快速过渡到可运行的具体代码。在探索陌生 API 或测试新型架构模式时,Vibe 编码尤为高效,因为它无需一开始就追求完美实现。生成的代码往往作为创意催化剂,为开发者提供可批判、重构和扩展的基础。其核心优势在于加速软件生命周期中的初始探索与概念形成阶段。然而,尽管 Vibe 编码在头脑风暴方面表现出色,构建稳健、可扩展且可维护的软件仍需要更结构化的方法——从纯粹生成转向与专业化编码智能体的协作伙伴关系。

## Agents as Team Members

## 智能体团队成员

While the initial wave focused on raw code generation—the "vibe code" perfect for ideation—the industry is now shifting towards a more integrated and powerful paradigm for production work. The most effective development teams are not merely delegating tasks to Agent; they are augmenting themselves with a suite of sophisticated coding agents. These agents act as tireless, specialized team members, amplifying human creativity and dramatically increasing a team's scalability and velocity.

尽管初期浪潮聚焦于原始代码生成——适合概念构思的"vibe 代码"——但行业如今正转向更集成、更强大的生产工作范式。最高效的开发团队不仅将任务委托给智能体,更是通过整套复杂的编码智能体来增强自身能力。这些智能体充当不知疲倦的专业团队成员,放大人类创造力,并显著提升团队的可扩展性和开发速度。

This evolution is reflected in statements from industry leaders. In early 2025, Alphabet CEO Sundar Pichai noted that at Google, **"over 30% of new code is now assisted or generated by our Gemini models, fundamentally changing our development velocity."** Microsoft made a similar claim.  This industry-wide shift signals that the true frontier is not replacing developers, but empowering them. The goal is an augmented relationship where humans guide the architectural vision and creative problem-solving, while agents handle specialized, scalable tasks like testing, documentation, and review.

这一演进趋势体现在行业领袖的公开声明中。2025 年初,Alphabet CEO Sundar Pichai 指出,在 Google 内部,**"超过 30% 的新代码现由 Gemini 模型辅助或生成,从根本上改变了我们的开发节奏。"** Microsoft 也发表了类似声明。这一全行业转型表明,真正的前沿并非替代开发者,而是为其赋能。目标是建立一种增强型协作关系:人类主导架构愿景和创造性问题解决,而智能体处理专业化、可扩展的任务,如测试、文档编制和代码审查。

This chapter presents a framework for organizing a human-agent team based on the core philosophy that human developers act as creative leads and architects, while AI agents function as force multipliers. This framework rests upon three foundational principles:

本章提出一个人机协作团队的组织框架,其核心理念是:人类开发者担任创意领导和架构师,而 AI 智能体充当能力倍增器。该框架基于三大基本原则:

1. **Human-Led Orchestration:** The developer is the team lead and project architect. They are always in the loop, orchestrating the workflow, setting the high-level goals, and making the final decisions. The agents are powerful, but they are supportive collaborators. The developer directs which agent to engage, provides the necessary context, and, most importantly, exercises the final judgment on any Agent-generated output, ensuring it aligns with the project's quality standards and long-term vision.
2. **The Primacy of Context:** An agent's performance is entirely dependent on the quality and completeness of its context. A powerful LLM with poor context is useless. Therefore, our framework prioritizes a meticulous, human-led approach to context curation. Automated, black-box context retrieval is avoided. The developer is responsible for assembling the perfect "briefing" for their Agent team member. This includes:
   * **The Complete Codebase:** Providing all relevant source code so the agent understands the existing patterns and logic.
   * **External Knowledge:** Supplying specific documentation, API definitions, or design documents.
   * **The Human Brief:** Articulating clear goals, requirements, pull request descriptions, and style guides.
3. **Direct Model Access:** To achieve state-of-the-art results, the agents must be powered by direct access to frontier models (e.g., Gemini 2.5 PRO, Claude Opus 4, OpenAI, DeepSeek, etc). Using less powerful models or routing requests through intermediary platforms that obscure or truncate context will degrade performance. The framework is built on creating the purest possible dialogue between the human lead and the raw capabilities of the underlying model, ensuring each agent operates at its peak potential.

1. **人类主导的流程编排:** 开发者是团队领导和项目架构师。他们始终处于决策闭环中,负责编排工作流、设定高层目标并做出最终决策。智能体虽然强大,但只是支持性协作者。开发者指导调用哪个智能体、提供必要的上下文,最重要的是——对智能体生成的任何输出行使最终裁决权,确保其符合项目的质量标准和长期愿景。
2. **上下文的核心地位:** 智能体的表现完全取决于其上下文的质量和完整性。一个强大的 LLM 如果缺乏优质上下文将毫无用处。因此,本框架优先采用人类主导的精细化上下文管理策略,避免自动化黑盒式上下文检索。开发者负责为智能体团队成员精心准备完美的"任务简报",包括:
   * **完整代码库:** 提供所有相关源代码,使智能体理解现有的模式和逻辑结构。
   * **外部知识:** 补充特定文档、API 定义或设计规范。
   * **人工任务简报:** 明确阐述目标、需求、拉取请求描述和编码规范。
3. **直接模型访问机制:** 为实现尖端效果,智能体必须通过直接访问前沿模型(如 Gemini 2.5 PRO、Claude Opus 4、OpenAI、DeepSeek 等)来驱动。使用性能较弱的模型或经由会模糊或截断上下文的中介平台转发请求将降低性能。本框架致力于在人类领导与底层模型的原始能力之间建立最纯净的对话通道,确保每个智能体以峰值潜力运行。

The framework is structured as a team of specialized agents, each designed for a core function in the development lifecycle. The human developer acts as the central orchestrator, delegating tasks and integrating the results.

该框架构建为一个专业化智能体团队,每个智能体专为开发生命周期中的核心功能而设计。人类开发者担任中央编排者,负责任务委派和成果整合。

## Core Components

## 核心组件

To effectively leverage a frontier Large Language Model, this framework assigns distinct development roles to a team of specialized agents. These agents are not separate applications but are conceptual personas invoked within the LLM through carefully crafted, role-specific prompts and contexts. This approach ensures that the model's vast capabilities are precisely focused on the task at hand, from writing initial code to performing a nuanced, critical review.

为有效利用前沿大语言模型,本框架将不同的开发角色分配给专业化智能体团队。这些智能体不是独立的应用程序,而是通过精心设计的角色特定提示和上下文在 LLM 中调用的概念化人格。这种方法确保模型的强大能力精准聚焦于手头的任务——从编写初始代码到进行细致的批判性审查。

**The Orchestrator: The Human Developer:** In this collaborative framework, the human developer acts as the Orchestrator, serving as the central intelligence and ultimate authority over the AI agents.

**流程编排者:人类开发者:** 在此协作框架中,人类开发者担任编排者,作为 AI 智能体的中央智能节点和最终权威。

* **Role:** Team Lead, Architect, and final decision-maker. The orchestrator defines tasks, prepares the context, and validates all work done by the agents.
  * **Interface:** The developer's own terminal, editor, and the native web UI of the chosen Agents.

* **角色定位:** 团队领导、架构师和最终决策者。编排者负责定义任务、准备上下文,并验证智能体完成的所有工作。
  * **交互界面:** 开发者自己的终端、编辑器,以及所选智能体的原生 Web 界面。

**The Context Staging Area:** As the foundation for any successful agent interaction, the Context Staging Area is where the human developer meticulously prepares a complete and task-specific briefing.

**上下文准备区:** 作为任何成功智能体交互的基础,上下文准备区是人类开发者精心准备完整且任务特定简报的专用空间。

* **Role:** A dedicated workspace for each task, ensuring agents receive a complete and accurate briefing.
  * **Implementation:** A temporary directory (task-context/) containing markdown files for goals, code files, and relevant docs

* **功能定位:** 为每项任务提供独立工作环境,确保智能体获得完整准确的简报材料。
  * **技术实现:** 临时目录(task-context/)包含目标说明的 markdown 文件、相关代码文件及配套文档。

**The Specialist Agents:** By using targeted prompts, we can build a team of specialist agents, each tailored for a specific development task.

**专业化智能体:** 通过使用定向提示,我们可以构建一个专业化智能体团队,每个成员针对特定开发任务量身定制。

* **The Scaffolder Agent: The Implementer**
  * **Purpose:** Writes new code, implements features, or creates boilerplate based on detailed specifications.
  * **Invocation Prompt:** "You are a senior software engineer. Based on the requirements in 01_BRIEF.md and the existing patterns in 02_CODE/, implement the feature..."

* **脚手架智能体:代码实施专家**
  * **核心职能:** 依据详细规范编写新代码、实现功能特性或创建基础模板。
  * **调用提示模板:**
    ```markdown
    你是一名资深软件工程师。请基于 01_BRIEF.md 中的需求说明与 02_CODE/ 目录下的现有模式,实现指定功能...
    ```

* **The Test Engineer Agent: The Quality Guard**
  * **Purpose:** Writes comprehensive unit tests, integration tests, and end-to-end tests for new or existing code.
  * **Invocation Prompt:** "You are a quality assurance engineer. For the code provided in 02_CODE/, write a full suite of unit tests using [Testing Framework, e.g., pytest]. Cover all edge cases and adhere to the project's testing philosophy."

* **测试工程师智能体:质量守护者**
  * **核心职能:** 为新代码或现有代码编写全面的单元测试、集成测试及端到端测试套件。
  * **调用提示模板:**
    ```markdown
    你是一名质量保证工程师。针对 02_CODE/ 中提供的代码,使用 [测试框架,如 pytest] 编写完整单元测试套件。需覆盖所有边界情况并遵循项目测试规范。
    ```

* **The Documenter Agent: The Scribe**
  * **Purpose:** Generates clear, concise documentation for functions, classes, APIs, or entire codebases.
  * **Invocation Prompt:** "You are a technical writer. Generate markdown documentation for the API endpoints defined in the provided code. Include request/response examples and explain each parameter."

* **文档编写智能体:技术文档专员**
  * **核心职能:** 为函数、类、API 或完整代码库生成清晰、简洁的技术文档。
  * **调用提示模板:**
    ```markdown
    你是一名技术文档工程师。为指定代码中定义的 API 端点生成 markdown 格式文档。需包含请求/响应示例并对各参数进行详细说明。
    ```

* **The Optimizer Agent: The Refactoring Partner**
  * **Purpose:** Proposes performance optimizations and code refactoring to improve readability, maintainability, and efficiency.
  * **Invocation Prompt:** "Analyze the provided code for performance bottlenecks or areas that could be refactored for clarity. Propose specific changes with explanations for why they are an improvement."

* **优化智能体:代码重构顾问**
  * **核心职能:** 提出性能优化方案与代码重构建议,以提升可读性、可维护性及执行效率。
  * **调用提示模板:**
    ```markdown
    分析提供代码中的性能瓶颈与可重构区域。提出具体改进方案并阐述各项更改的优化价值。
    ```

* **The Process Agent: The Code Supervisor**
  * **Critique:** The agent performs an initial pass, identifying potential bugs, style violations, and logical flaws, much like a static analysis tool.
  * **Reflection:** The agent then analyzes its own critique. It synthesizes the findings, prioritizes the most critical issues, dismisses pedantic or low-impact suggestions, and provides a high-level, actionable summary for the human developer.
  * **Invocation Prompt:** "You are a principal engineer conducting a code review. First, perform a detailed critique of the changes. Second, reflect on your critique to provide a concise, prioritized summary of the most important feedback."

* **流程智能体:代码质量监督员**
  * **批判分析:** 智能体执行初步审查,识别潜在缺陷、编码规范违规及逻辑漏洞,功能类似静态分析工具。
  * **深度反思:** 智能体对自身批判进行元分析。综合各项发现,优先处理关键问题,过滤琐碎或低价值建议,为人类开发者提供高层级、可执行的总结报告。
  * **调用提示模板:**
    ```markdown
    你是一名首席工程师执行代码审查。首先对变更进行详细批判分析,随后进行反思总结,提供关键反馈的优先级排序摘要。
    ```

Ultimately, this human-led model creates a powerful synergy between the developer's strategic direction and the agents' tactical execution. As a result, developers can transcend routine tasks, focusing their expertise on the creative and architectural challenges that deliver the most value.

最终,这种人类主导的模式在开发者的战略方向与智能体的战术执行之间建立了强大的协同效应。因此,开发者可以超越常规任务,将专业知识聚焦于创造最大价值的创意和架构挑战上。

## Practical Implementation

## 实践实施

### Setup Checklist

### 配置清单

To effectively implement the human-agent team framework, the following setup is recommended, focusing on maintaining control while improving efficiency.

为有效实施人机协作团队框架,建议采用以下配置,核心目标是在提升效率的同时保持完全控制。

1. **Provision Access to Frontier Models** Secure API keys for at least two leading large language models, such as Gemini 2.5 Pro and Claude 4 Opus. This dual-provider approach allows for comparative analysis and hedges against single-platform limitations or downtime. These credentials should be managed securely as you would any other production secret.
2. **Implement a Local Context Orchestrator** Instead of ad-hoc scripts, use a lightweight CLI tool or a local agent runner to manage context. These tools should allow you to define a simple configuration file (e.g., context.toml) in your project root that specifies which files, directories, or even URLs to compile into a single payload for the LLM prompt. This ensures you retain full, transparent control over what the model sees on every request.
3. **Establish a Version-Controlled Prompt Library** Create a dedicated /prompts directory within your project's Git repository. In it, store the invocation prompts for each specialist agent (e.g., reviewer.md, documenter.md, tester.md) as markdown files. Treating your prompts as code allows the entire team to collaborate on, refine, and version the instructions given to your AI agents over time.
4. **Integrate Agent Workflows with Git Hooks** Automate your review rhythm by using local Git hooks. For instance, a pre-commit hook can be configured to automatically trigger the Reviewer Agent on your staged changes. The agent's critique-and-reflection summary can be presented directly in your terminal, providing immediate feedback before you finalize the commit and baking the quality assurance step directly into your development process.

1. **前沿模型访问权限配置** 获取至少两个领先大语言模型(如 Gemini 2.5 Pro 与 Claude 4 Opus)的 API 访问密钥。这种双供应商策略便于性能对比分析,同时规避单一平台限制或服务中断风险。此类凭证应按照生产环境密钥管理规范进行安全存储。
2. **本地上下文编排器部署** 采用轻量级 CLI 工具或本地智能体运行器来管理上下文,而非临时脚本方案。此类工具应支持在项目根目录定义简明配置文件(如 context.toml),明确指定需编译至 LLM 提示词统一载荷的文件、目录或 URL 资源。这确保您对模型每次请求所见内容保持完全透明的控制。
3. **版本化提示词库构建** 在项目 Git 仓库内创建专用 /prompts 目录。以 markdown 文件形式存储各专业智能体的调用提示词(如 reviewer.md、documenter.md、tester.md)。将提示词视同代码资产管理,支持团队持续协作优化、版本追踪及 AI 智能体的迭代演进。
4. **智能体工作流与 Git 钩子集成** 通过本地 Git 钩子实现审查流程自动化。例如,配置 pre-commit 钩子自动在暂存变更上触发审查者智能体。智能体生成的批判与反思摘要将直接输出至终端,在提交确认前提供即时质量反馈,将质量保障环节深度嵌入开发流程。

**![][image1]**

Fig. 1:  Coding Specialist Examples

图 1:编码专家角色示例

## Principles for Leading the Augmented Team

## 增强型团队领导原则

Successfully leading this framework requires evolving from a sole contributor into the lead of a human-AI team, guided by the following principles:

成功驾驭此框架需要实现从独立贡献者向人机协作团队领导者的角色转型,遵循以下核心原则:

* **Maintain Architectural Ownership** Your role is to set the strategic direction and own the high-level architecture. You define the "what" and the "why," using the agent team to accelerate the "how." You are the final **arbiter** of design, ensuring every component aligns with the project's long-term vision and quality standards.
* **Master the Art of the Brief** The quality of an agent's output is a direct reflection of the quality of its input. Master the art of the brief by providing clear, unambiguous, and comprehensive context for every task. Think of your prompt not as a simple command, but as a complete briefing package for a new, highly capable team member.
* **Act as the Ultimate Quality Gate** An agent's output is always a proposal, never a command. Treat the Reviewer Agent's feedback as a powerful signal, but you are the ultimate quality gate. Apply your domain expertise and project-specific knowledge to validate, challenge, and approve all changes, acting as the final guardian of the codebase's integrity.
* **Engage in Iterative Dialogue** The best results emerge from conversation, not monologue. If an agent's initial output is imperfect, don't discard it—refine it. Provide corrective feedback, add clarifying context, and prompt for another attempt. This iterative dialogue is crucial, especially with the Reviewer Agent, whose "Reflection" output is designed to be the start of a collaborative discussion, not just a final report.

* **坚守架构主导权** 您的核心职责是制定战略方向并掌控高层架构设计。您定义"目标"和"设计理念",借助智能体团队加速"实施方案"落地。作为设计决策的最终**仲裁者**,确保各组件严格遵循项目长期愿景与质量标准。
* **精研任务简报技艺** 智能体的输出质量直接映射输入信息质量。通过为每项任务提供清晰无歧义、内容完备的上下文掌握简报艺术。应将提示词视为面向高能力新团队成员的完整任务简报包,而非简单指令。
* **担当终极质量关口** 智能体的输出始终属于建议方案,绝非强制命令。将审查者智能体的输出作为重要参考信号,但您承担最终质量决策责任。运用领域专业知识与项目特定认知验证、质询并核准所有变更,担当代码库完整性的终极守护者。
* **践行迭代对话模式** 最优成果源于双向对话而非单向指令。若智能体输出存在不足,应导向完善而非弃用。提供修正反馈、补充澄清上下文、引导二次尝试。此迭代对话机制至关重要,尤其针对审查者智能体——其"反思"输出设计为协作讨论起点,而非终态报告。

## Conclusion

## 结论

The future of code development has arrived, and it is augmented. The era of the lone coder has given way to a new paradigm where developers lead teams of specialized AI agents. This model doesn't diminish the human role; it elevates it by automating routine tasks, scaling individual impact, and achieving a development velocity previously unimaginable.

代码开发的未来图景已然呈现——它是增强协同的崭新范式。独行编码者的时代正演进为开发者引领专业化 AI 智能体的新纪元。这种模式非但没有削弱人类角色,反而通过自动化常规任务、放大个体影响力以及实现前所未有的开发效能将其提升至新高度。

By offloading tactical execution to Agents, developers can now dedicate their cognitive energy to what truly matters: strategic innovation, resilient architectural design, and the creative problem-solving required to build products that delight users. The fundamental relationship has been redefined; it is no longer a contest of human versus machine, but a partnership between human ingenuity and AI, working as a single, seamlessly integrated team.

通过将战术执行委派予智能体,开发者得以将认知资源聚焦于真正核心的领域:战略创新、韧性架构设计,以及打造令用户惊喜的产品所需的创造性问题破解。根本性协作关系已被重新定义:这不再是人与机器的对抗竞赛,而是人类智慧与人工智能作为无缝集成团队的深度伙伴关系。

## References

## 参考文献

1. AI is responsible for generating more than 30% of the code at Google [https://www.reddit.com/r/singularity/comments/1k7rxo0/ai_is_now_writing_well_over_30_of_the_code_at/](https://www.reddit.com/r/singularity/comments/1k7rxo0/ai_is_now_writing_well_over_30_of_the_code_at/)
2. AI is responsible for generating more than 30% of the code at Microsoft [https://www.businesstoday.in/tech-today/news/story/30-of-microsofts-code-is-now-ai-generated-says-ceo-satya-nadella-474167-2025-04-30](https://www.businesstoday.in/tech-today/news/story/30-of-microsofts-code-is-now-ai-generated-says-ceo-satya-nadella-474167-2025-04-30)

[image1]: ../images/appendix-g/image1.png


## /chapters/README.md

# 章节目录

本目录用于存放翻译后的章节文件。

## 文件命名规范

- 使用格式:`chapter-XX.md`,其中 XX 为章节编号(01-25)
- 例如:`chapter-01.md`、`chapter-02.md` 等

## 翻译流程

1. 从 `original/` 目录获取原文
2. 在此目录创建对应的翻译文件
3. 保持原文的结构和格式
4. 更新图片引用路径为 `../images/chapter-XX/`

## 注意事项

- 文件编码使用 UTF-8
- 保持 Markdown 格式规范
- 代码块使用正确的语言标识符

## /images/README.md

# 图片资源目录

本目录用于存放书籍中使用的所有图片资源。

## 目录结构

- `common/` - 公共图片资源(如 logo、图标等)
- `chapter-XX/` - 各章节的图片资源(01-25)

## 文件命名规范

- 使用英文命名,小写字母,单词间用连字符分隔
- 格式:`descriptive-name.png` 或 `.jpg` 等
- 示例:`architecture-diagram.png`、`code-example-01.png`

## 图片格式

- 优先使用 PNG 格式(透明背景、高质量)
- 照片类图片可使用 JPG 格式
- 图表建议使用 SVG 格式(可缩放)

## 引用方式

在 Markdown 文件中引用图片:

```markdown
![图片描述](../images/chapter-01/example-image.png)
```

## 注意事项

- 图片文件大小尽量控制在合理范围内
- 确保图片清晰度适合阅读
- 如图片包含文字需要翻译,请创建中文版本

## /images/appendix-a/image1.png

Binary file available at https://raw.githubusercontent.com/xindoo/agentic-design-patterns/refs/heads/main/images/appendix-a/image1.png

## /images/appendix-b/image1.png

Binary file available at https://raw.githubusercontent.com/xindoo/agentic-design-patterns/refs/heads/main/images/appendix-b/image1.png

## /images/appendix-d/image1.png

Binary file available at https://raw.githubusercontent.com/xindoo/agentic-design-patterns/refs/heads/main/images/appendix-d/image1.png

## /images/appendix-d/image2.png

Binary file available at https://raw.githubusercontent.com/xindoo/agentic-design-patterns/refs/heads/main/images/appendix-d/image2.png


The content has been capped at 50000 tokens. The user could consider applying other filters to refine the result. The better and more specific the context, the better the LLM can follow instructions. If the context seems verbose, the user can refine the filter using uithub. Thank you for using https://uithub.com - Perfect LLM context for any GitHub repo.
Copied!