ai-agents-from-scratch README

The project's README from github.com/pguso/ai-agents-from-scratch. As one markdown file: README.md.

AI Agents From Scratch

Learn to build AI agents locally without frameworks. Understand what happens under the hood before using production frameworks.

Agent architecture overview

Purpose

This repository teaches you to build AI agents from first principles using local LLMs and node-llama-cpp. By working through these examples, you'll understand:

A Python version of this tutorial is available here: https://github.com/pguso/agents-from-scratch

Philosophy: Learn by building. Understand deeply, then use frameworks wisely.

Companion Website

This repository now has a matching companion website:

https://agentsfromscratch.com

The website is not a replacement for this repo, but a conceptual companion that:

Recommended workflow:

Think of the site as the map and this repo as the terrain.

Agent Fundamentals - From LLMs to ReAct

Prerequisites

Installation

npm install

Run Examples

node intro/intro.js
node simple-agent/simple-agent.js
node react-agent/react-agent.js

Learning Path

Follow these examples in order to build understanding progressively:

1. Introduction - Basic LLM Interaction

intro/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: Model loading, context, inference pipeline, token generation


2. (Optional) OpenAI Intro - Using Proprietary Models

openai-intro/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: Inference endpoints, network latency, cost vs control, data privacy, vendor dependence


3. Translation - System Prompts & Specialization

translation/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: System prompts, agent specialization, behavioral constraints, prompt engineering


4. Think - Reasoning & Problem Solving

think/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: Reasoning agents, problem decomposition, cognitive tasks, reasoning limitations


5. Batch - Parallel Processing

batch/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: Parallel execution, sequences, batch size, throughput optimization


6. Coding - Streaming & Response Control

coding/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: Streaming, token-by-token generation, response control, real-time feedback


7. Simple Agent - Function Calling (Tools)

simple-agent/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: Function calling, tool definitions, agent decision making, action-taking

This is where text generation becomes agency!


8. Simple Agent with Memory - Persistent State

simple-agent-with-memory/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: Persistent memory, state management, memory systems, context augmentation


9. ReAct Agent - Reasoning + Acting

react-agent/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: ReAct pattern, iterative reasoning, observation-action cycles, multi-step agents

This is the foundation of modern agent frameworks!


10. AoT Agent - Atom of Thought Planning

aot-agent/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: AoT planning, atomic operations, dependency resolution, plan validation, structured reasoning


11. Error Handling - Resilience for LLM + Tools

error-handling/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: Error taxonomy, retry policies, timeouts, fallbacks, degraded mode, observability, user-safe messaging


12. Tree of Thought - Search over reasoning branches

tree-of-thought/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: Tree of Thought, beam search, branch pruning, verifiable objectives, search controllers


13. Graph of Thought - DAG merge for multi-source outputs

graph-of-thought/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: Graph of Thought, DAG orchestration, multi-source fusion, merge-before-generate, policy reconciliation

Decision guide: use ToT when you need to search competing paths; use GoT when you need to combine multiple sources into one consistent policy. Compare both in:


14. Chain of Thought - Auditable stepwise decisioning

chain-of-thought/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: Chain of Thought, structured reasoning traces, policy-constrained decisions, explainability, review-ready workflows


15. Tool routing (embeddings) - Narrow the tool catalog per request

tool-routing-embeddings/ | Code | Code Explanation | Concepts

What you'll learn:

Key concepts: Tool routing, embedding similarity, exemplar design, context/token savings, pinned tools, retrieval-style agent design


Documentation Structure

Each example folder contains:

Core Concepts

What is an AI Agent?

AI Agent = LLM + System Prompt + Tools + Memory + Reasoning Pattern
           ─┬─   ──────┬──────   ──┬──   ──┬───   ────────┬────────
            │          │           │       │              │
         Brain      Identity    Hands   State         Strategy

Evolution of Capabilities

1. intro          → Basic LLM usage
2. translation    → Specialized behavior (system prompts)
3. think          → Reasoning ability
4. batch          → Parallel processing
5. coding         → Streaming & control
6. simple-agent   → Tool use (function calling)
7. memory-agent   → Persistent state
8. react-agent    → Strategic reasoning + tool use

Architecture Patterns

Simple Agent (Steps 1-5)

User → LLM → Response

Tool-Using Agent (Step 6)

User → LLM ⟷ Tools → Response

Memory Agent (Step 7)

User → LLM ⟷ Tools → Response
       ↕
     Memory

ReAct Agent (Step 8)

User → LLM → Think → Act → Observe
       ↑      ↓      ↓      ↓
       └──────┴──────┴──────┘
           Iterate until solved

️ Helper Utilities

PromptDebugger

helper/prompt-debugger.js

Utility for debugging prompts sent to the LLM. Shows exactly what the model sees, including:

Usage example in simple-agent/simple-agent.js

️ Project Structure - Fundamentals

ai-agents/
├── README.md                          ← You are here
├─ examples/
├── 01_intro/
│   ├── intro.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 02_openai-intro/
│   ├── openai-intro.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 03_translation/
│   ├── translation.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 04_think/
│   ├── think.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 05_batch/
│   ├── batch.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 06_coding/
│   ├── coding.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 07_simple-agent/
│   ├── simple-agent.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 08_simple-agent-with-memory/
│   ├── simple-agent-with-memory.js
│   ├── memory-manager.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 09_react-agent/
│   ├── react-agent.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 10_aot-agent/
│   ├── aot-agent.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 11_error-handling/
│   ├── error-handling.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 12_tree-of-thought/
│   ├── tree-of-thought.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 13_graph-of-thought/
│   ├── graph-of-thought.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 14_chain-of-thought/
│   ├── chain-of-thought.js
│   ├── CODE.md
│   └── CONCEPT.md
├── 15_tool-routing-embeddings/
│   ├── tool-routing-embeddings.js
│   ├── CODE.md
│   └── CONCEPT.md
├── helper/
│   └── prompt-debugger.js
├── models/                             ← Place your GGUF models here
└── logs/                               ← Debug outputs

Additional Resources

Contributing

This is a learning resource. Feel free to:

License

Educational resource - use and modify as needed for learning.


Built with ❤️ for people who want to truly understand AI agents

Start with intro/ and work your way through. Each example builds on the previous one. Read both CODE.md and CONCEPT.md for full understanding.

Happy learning!


Working with me

If this repo was useful and you have a project that needs ai workflows, context engineering, RAG, or local/production LLM work done properly, I'm open to freelance or contract engagements.

No pressure either way - glad if the repo was useful on its own.

ai-agents-from-scratch (pguso/ai-agents-from-scratch)

Searching Database…

这是什么?一个动手教程仓库,教你通过 node-llama-cpp 用本地大语言模型从第一性原理构建 AI 代理,不借助任何框架,让你在使用生产级框架之前先理解函数调用、记忆和 ReAct。
这是一个框架,还是只是一套教程示例?它是学习资源而不是框架:15 个难度递进的独立 JavaScript 示例,每个都有自己的 .js 代码文件,外加 CODE.md(逐行讲解)和 CONCEPT.md(架构概念)。
怎么运行这些示例?克隆仓库,安装 Node 依赖,按 DOWNLOAD.md 的说明把所需的 GGUF 模型下载到 ./models/ 文件夹,然后从 intro/ 开始按顺序运行每个示例的 .js 文件。
尝试之前需要装好什么?需要 Node.js 18+ 和至少 8GB 内存(推荐 16GB)来运行本地 GGUF 模型;可选的 openai-intro 示例还需要能访问托管的 OpenAI 模型,而不是本地模型。
这是可以直接放进应用的生产级代码吗?不是,它明确是一个用于讲解概念的教育资源,不是经过加固的库;仓库自带的测试脚本只是个占位符,许可说明也写明仅可用于学习目的的使用和修改。
ReAct 代理示例比简单代理多了什么?它引入了“推理-行动-观察”(Reason-Act-Observe)循环,让代理可以跨多个步骤迭代地调用工具、观察结果并自我修正,而不是只做单次工具调用。
思维原子(Atom of Thought,AoT)示例讲的是什么?它展示了一种规划方法:把多步计算拆解为带显式依赖的原子操作,生成结构化的 JSON 计划,并以确定性的方式执行。
这里的思维树和思维图有什么区别?思维树(Tree of Thought)对相互竞争的推理分支做束搜索,找出一条最佳路径;思维图(Graph of Thought)则把推理建模为 DAG,把多个并行来源合并成一个一致的结果。
除了代码还有配套资源吗?有,一个配套网站将学习路径可视化并解释每个示例背后的概念,而仓库本身则用于运行和研究实际代码。
What are similar projects?agentscope, NeoHorse, brigade, gitagent, evolver, ruflo, Baize, tau
Creator
pguso
Size
1.8 MB
Stars
4.9K
Updated
CommitJul 24
Age
11mo
Commits · 90 Days