惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
Blog — PlanetScale
Blog — PlanetScale
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
爱范儿
爱范儿
量子位
博客园 - 聂微东
Engineering at Meta
Engineering at Meta
WordPress大学
WordPress大学
GbyAI
GbyAI
MyScale Blog
MyScale Blog
IT之家
IT之家
P
Proofpoint News Feed
M
MIT News - Artificial intelligence
The Cloudflare Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Hugging Face - Blog
Hugging Face - Blog
The Register - Security
The Register - Security
Microsoft Security Blog
Microsoft Security Blog
博客园_首页
MongoDB | Blog
MongoDB | Blog
F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
Y
Y Combinator Blog
雷峰网
雷峰网
V
Visual Studio Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Last Week in AI
Last Week in AI
博客园 - 叶小钗
D
DataBreaches.Net
B
Blog
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
Recent Announcements
Recent Announcements
阮一峰的网络日志
阮一峰的网络日志
小众软件
小众软件
腾讯CDC
T
Threat Research - Cisco Blogs
SecWiki News
SecWiki News
Martin Fowler
Martin Fowler
D
Docker
Cisco Talos Blog
Cisco Talos Blog
T
Tenable Blog
Webroot Blog
Webroot Blog
宝玉的分享
宝玉的分享

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Demystifying AI Agents: Building an Agentic Pipeline From Scratch in Pure Python
Rafael Tedes · 2026-05-21 · via DEV Community

Most AI demos look impressive until you ask a simple question: What is actually happening under the hood?

Frameworks like LangChain, CrewAI, and Microsoft AutoGen make it incredibly easy to spin up an “AI agent” in a few lines of code. But abstractions come with a cost. Many developers can build agents using frameworks without fully understanding the runtime architecture powering them.

At their core, most agent frameworks are built around surprisingly simple primitives:

  • Prompt orchestration
  • Stateful memory
  • Tool execution
  • Control loops
  • Structured outputs

This week I was talking with a friend who wanted to understand how AI agents actually work under the hood. During that conversation, I realized something: most tutorials make AI agents feel far more mysterious than they really are.

Frameworks are great for moving fast, but they also hide many of the core mechanics behind layers of abstractions. You import a library, initialize an “agent,” attach a tool, and suddenly everything looks autonomous and intelligent. But underneath those abstractions, most agent systems are built on a surprisingly small set of concepts:

  • Prompts
  • Memory
  • Tool execution
  • Structured outputs
  • Control loops

So I decided to write the article I wish I had found when I first started exploring agentic systems. No heavy frameworks. No orchestration libraries. No hidden runtime magic. Just the core ideas, built step-by-step from scratch in pure Python.

In this article, we will strip away the abstractions and build a production-inspired agentic pipeline entirely from scratch using:

  • Pure Python
  • The standard library only
  • Native HTTP requests
  • No SDKs
  • No orchestration frameworks

By the end, you will understand the core mechanics behind modern AI agents and why most frameworks are essentially layered convenience abstractions over a deterministic execution loop.


What Is an Agentic Pipeline?

A standard LLM interaction is usually a single-shot transaction:

User Prompt ──> Model Response

Enter fullscreen mode Exit fullscreen mode

The model receives context once and generates a static response. An agent, however, behaves differently. Instead of generating a single response, it operates inside a continuous execution cycle:

       ┌───────────────────────────────────────┐
       │                                       │
       ▼                                       │
[ THINK ] ───> (Decision) ───> [ ACT ] ───> [ OBSERVE ]
                               (Tool Call)   (Tool Result)

Enter fullscreen mode Exit fullscreen mode

Think

The model evaluates the user objective, available tools, prior observations, and current memory state. It then decides what to do next.

Act

The agent executes an action. This could be calling a function, querying a database, searching the web, reading files, or returning a final answer.

Observe

The system captures the result of the action and feeds it back into the context window. The cycle repeats until the objective is complete.


A Helpful Mental Model

Think of an agent like a developer debugging a production issue:

Observe error logs
        │
        ▼
Form a hypothesis
        │
        ▼
  Run a command
        │
        ▼
 Inspect output
        │
        ▼
    Repeat

Enter fullscreen mode Exit fullscreen mode

That iterative feedback loop is exactly how agentic systems operate.


Project Structure

We will organize the codebase into small, focused modules.

agentic-pipeline/
├── config.json       # Runtime configuration
├── llm_client.py     # Low-level HTTP client
├── memory.py         # Context/state manager
├── agent.py          # Agent orchestration engine
└── main.py           # Runtime execution loop

Enter fullscreen mode Exit fullscreen mode

This separation mirrors how production systems are commonly structured.


Step 1 — Configuration Management

Avoid hardcoding runtime variables directly in code. For this demo we’re going to Create a config.json file just for demonstration purposes:

{
  "llm": {
    "provider": "openai",
    "model": "gpt-4o",
    "api_key": "sk-your-api-key",
    "temperature": 0.2,
    "max_tokens": 1024
  }
}

Enter fullscreen mode Exit fullscreen mode

⚠️ Note: In production systems, credentials should come from environment variables or a secrets manager rather than static configuration files.


Step 2 — Building the Infrastructure Layer

Most SDKs hide the reality that every LLM interaction is just an HTTP request. Underneath the abstraction, the process is straightforward:

Serialize payload ──> Send HTTPS POST request ──> Receive JSON response ──> Parse output

Enter fullscreen mode Exit fullscreen mode

Let’s implement that manually in llm_client.py.

import json
import urllib.request
import urllib.error
from typing import Dict, List

class LLMClient:
    def __init__(self, config: Dict):
        self.config = config["llm"]
        self.api_key = self.config["api_key"]

    def chat_completion(
        self,
        messages: List[Dict],
        temperature: float = None
    ) -> str:
        payload = {
            "model": self.config["model"],
            "messages": messages,
            "temperature": temperature or self.config.get("temperature", 0.2),
            "max_tokens": self.config.get("max_tokens", 1024)
        }

        data = json.dumps(payload).encode("utf-8")

        req = urllib.request.Request(
     "https://api.openai.com/v1/chat/completions",
            data=data,
            method="POST"
        )

        req.add_header("Content-Type", "application/json")
        req.add_header("Authorization", f"Bearer {self.api_key}")

        try:
            with urllib.request.urlopen(req) as response:
                result = json.loads(response.read().decode())
                return result["choices"][0]["message"]["content"].strip()
        except urllib.error.HTTPError as e:
            error_body = e.read().decode()
            raise Exception(f"LLM API error: {e.code} - {error_body}")

Enter fullscreen mode Exit fullscreen mode

To understand what LLMClient is doing here, it helps to think of it like an old-school telegraph operator. This layer has no concept of reasoning, planning, or executing tools. It doesn't even manage memory. Its only job is to package up a stack of text, send it down the wire to the model, and hand you back the raw response. It moves the messages back and forth reliably without needing to understand a single word written inside them.


Step 3 — Managing Agent Memory

LLMs are stateless. They do not remember previous interactions unless the entire history is resent with every request. As the execution loop progresses, the context window continuously grows. We therefore need a lightweight memory manager in memory.py.

from typing import List, Dict

class AgentMemory:
    def __init__(self, max_messages: int = 20):
        self.messages: List[Dict] = []
        self.max_messages = max_messages

    def add(self, role: str, content: str):
        self.messages.append({
            "role": role,
            "content": content
        })

        if len(self.messages) > self.max_messages:
            # Preserve system prompt
            system_prompt = self.messages[0]

            # Slide conversation window
            active_history = self.messages[1:]
            self.messages = (
                [system_prompt] + 
                active_history[-(self.max_messages - 1):]
            )

    def get_messages(self) -> List[Dict]:
        return self.messages.copy()

    def clear(self):
        self.messages.clear()

Enter fullscreen mode Exit fullscreen mode

If the LLM client is our telegraph operator, you can picture this memory manager like a detective's notebook. As the agent investigates a task, every tiny detail gets written down: the original user request, internal reasoning, tool choices, and the clues discovered along the way. Because the notebook can't hold infinite pages, the detective eventually has to archive old details while keeping the core investigation context front and center. That sliding window logic is exactly how we keep the context manageable.


Step 4 — Building the Agent Engine

This is where the orchestration logic lives. The agent must understand available tools, decide when to use them, parse structured outputs, execute functions, and feed observations back into memory. Let's write agent.py:

from llm_client import LLMClient
from memory import AgentMemory
from typing import Dict, Callable
import json

class Agent:
    def __init__(self, system_prompt: str, config_path: str = "config.json"):
        with open(config_path) as f:
            self.config = json.load(f)
        self.llm = LLMClient(self.config)
        self.memory = AgentMemory()
        self.system_prompt = system_prompt
        self.tools: Dict[str, dict] = {}

        self.memory.add("system", system_prompt)

    def register_tool(self, name: str, func: Callable, description: str):
        self.tools[name] = {
            "func": func,
            "description": description
        }

    def _get_tool_descriptions(self) -> str:
        if not self.tools:
            return "No tools available."
        return "\n".join([
            f"- {name}: {info['description']}"
            for name, info in self.tools.items()
        ])

    def think(self, user_input: str) -> str:
        self.memory.add("user", user_input)
        messages = self.memory.get_messages()
        tool_info = self._get_tool_descriptions()

        if self.tools:
            messages = messages.copy()
            enhanced_content = (
                f"{user_input}\n\n"
                f"AVAILABLE TOOLS:\n"
                f"{tool_info}\n\n"
                f"If you need a tool, respond ONLY with JSON:\n"
                f'{{"tool":"tool_name","args":{{}}}}\n\n'
                f"If the task is complete, respond naturally and include 'FINAL ANSWER'."
            )
            messages[-1]["content"] = enhanced_content

        response = self.llm.chat_completion(messages)
        self.memory.add("assistant", response)
        return response

    def act(self, response: str):
        if "{" in response and "}" in response:
            try:
                start = response.find("{")
                end = response.rfind("}") + 1
                tool_json = json.loads(response[start:end])

                tool_name = tool_json.get("tool")
                args = tool_json.get("args", {})

                if tool_name in self.tools:
                    result = self.tools[tool_name]<a href="**args">func</a>
                    self.memory.add(
                        "system", 
                        f"Observation from '{tool_name}': {result}"
                    )
                    return result
            except Exception as e:
                error_msg = f"Tool execution failed: {str(e)}"
                self.memory.add("system", error_msg)
                return error_msg
        return None

Enter fullscreen mode Exit fullscreen mode

This structural handoff brings up one of the most misunderstood parts of modern AI agents: the model does not execute your Python functions directly.

Instead, you are providing plain text descriptions of your local code inside the prompt. When the model reads these descriptions and decides it needs help, it simply formats its text output into a raw JSON block specifying a tool name and parameters. Your host application then catches that JSON, reads it, runs the native Python code locally, and passes the results back into the text history. The LLM itself remains entirely isolated—your local application serves as the actual execution environment.


Step 5 — The Runtime Control Loop

Without a runtime loop, the agent cannot perform multi-step reasoning. The host application must continuously drive execution forward. Let's look at main.py:

from agent import Agent
import time

def web_search(query: str) -> str:
    print(f"🔍 Searching index for: '{query}'")
    time.sleep(1)
    if "agentic ai" in query.lower():
        return (
            "Found: Modern agentic systems are moving away from rigid chains "
            "toward lightweight control loops and modular tools."
        )
    return (
        "Found: Building agents from scratch reveals implementation details "
        "often hidden by frameworks."
    )

if __name__ == "__main__":
    system_prompt = (
        "You are an autonomous operations assistant. "
        "Reason step-by-step. "
        "Use tools when necessary. "
        "When the task is fully complete, include the phrase FINAL ANSWER."
    )

    agent = Agent(system_prompt)
    agent.register_tool(
        name="search",
        func=web_search,
        description="Queries an index database. Input schema: {'query': str}"
    )

    task = "Research trends in agentic AI and explain why building from scratch is valuable."
    print(f"🎯 Objective: {task}")

    max_steps = 5
    for step in range(max_steps):
        print(f"\n[Cycle {step + 1}]")
        prompt = task if step == 0 else "Analyze previous observations and continue."

        response = agent.think(prompt)
        print(f"\n🤖 Agent:\n{response}")

        tool_output = agent.act(response)
        if tool_output:
            print(f"\n🛠 Observation:\n{tool_output}")

        if "final answer" in response.lower():
            print("\n✅ Objective completed.")
            break

Enter fullscreen mode Exit fullscreen mode


Tracing the Runtime Execution

Here is a look at what happens internally during execution over two separate cycles:

Cycle 1

  • Think: The model receives the task, tool descriptions, and the initial system memory state. It realizes it lacks direct information about current trends.
  • Act: The model emits structured JSON:

    {
      "tool": "search",
      "args": {
        "query": "latest trends in agentic AI"
      }
    }
    

The runtime parses this block and executes the local Python web_search function.

  • Observe: The tool output gets appended back into memory. The model now has additional context to continue reasoning.

Cycle 2

The model reviews the original objective, prior observations, and tool outputs. It synthesizes a complete response and emits:


text
FINAL ANSWER


Enter fullscreen mode Exit fullscreen mode

The control loop detects this completion keyword and exits gracefully.


What You Actually Built

Underneath all the abstractions, you implemented a fully working pipeline:

  • Stateful memory
  • Tool registration
  • Structured tool calling
  • Runtime orchestration
  • Multi-step execution
  • Context management
  • Deterministic control flow

That is the foundation of nearly every modern agent framework.


Production Considerations

This implementation is intentionally minimal. Real production systems typically add:

Domain Operational Mechanics
Resilience & Tracking Retry policies, Token accounting, Observability & tracing
Data & Run Management Parallel tool execution, Sandboxed runtimes, Rate limiting
Architecture Scaling Distributed orchestration, Long-term memory persistence layers
Security & Safety Guardrails and validation, Human approval checkpoints

Frameworks become valuable once these operational concerns grow large enough. But understanding the core loop first changes how you design AI systems.


Final Thoughts

AI agents can appear magical when hidden behind high-level abstractions. But once you strip away the layers, most systems reduce to a small set of deterministic building blocks: prompts, memory, tools, parsing, and loops.

Understanding those primitives gives you far more architectural control than blindly composing frameworks. Before introducing another dependency into your stack, it is worth asking:

“Do I actually need a framework here, or do I just need a well-designed control loop?”

If you can answer that question confidently, you already understand more about agentic systems than most developers using them today.