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…

Что это?Учебный репозиторий с практическими заданиями, который учит собирать ИИ-агентов с первых принципов на локальных LLM через node-llama-cpp, без всяких фреймворков, чтобы вы поняли function calling, память и ReAct ещё до использования production-фреймворков.
Это фреймворк или просто набор учебных примеров?Это учебный ресурс, а не фреймворк: 15 всё более сложных самостоятельных примеров на JavaScript, у каждого свой файл кода .js плюс CODE.md (объяснение построчно) и CONCEPT.md (архитектурные концепции).
Как запустить примеры?Склонируйте репозиторий, установите зависимости Node, скачайте нужные GGUF-модели в папку ./models/, как описано в DOWNLOAD.md, затем запускайте файлы .js каждого примера по порядку, начиная с intro/.
Что нужно установить, прежде чем пробовать это?Node.js 18+ и не менее 8 ГБ ОЗУ (рекомендуется 16 ГБ) для запуска локальных GGUF-моделей; необязательному примеру openai-intro также нужен доступ к облачной модели OpenAI вместо локальной.
Это production-код, который можно взять и вставить в приложение?Нет, это прямо учебный ресурс, призванный объяснять концепции, а не укреплённая библиотека; собственный тестовый скрипт репозитория — заглушка, а примечание к лицензии говорит использовать и изменять его только в учебных целях.
Что добавляет пример ReAct-агента по сравнению с простым агентом?Он вводит цикл Reason-Act-Observe, позволяющий агенту итеративно вызывать инструменты, наблюдать результаты и самокорректироваться на протяжении нескольких шагов вместо одного вызова инструмента.
О чём пример Atom of Thought (AoT)?Он показывает метод планирования, который разбивает многошаговые вычисления на атомарные операции с явными зависимостями и создаёт структурированный JSON-план, исполняемый детерминированно.
В чём разница между Tree of Thought и Graph of Thought здесь?Tree of Thought выполняет beam search по конкурирующим ветвям рассуждений в поисках одного лучшего пути, а 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