今日已更新 166 条资讯 | 累计 20138 条内容
关于我们

标签:#python

找到 613 篇相关文章

AI 资讯

A Deactivated Admin Could Still Use Their Token. That's When Dual-Mode JWT Stopped Being About Speed.

What building cross-service RBAC taught me about the difference between a fast check and a correct one VaultPay is a wallet microservice I built on top of AuthShield. Previous parts: Part 1 is here: I Built AuthShield and Immediately Knew It Wasn't Enough Part 2 is here: The Silent Failure I Never Saw Coming: What VaultPay Taught Me About Consistency Under Failure Part 3 is here: I Started With a Blocklist. That Was the Wrong Instinct and VaultPay Taught Me Why. Part 4 is here: I Watched Money Move Twice From the Same Request. That's When I Understood Idempotency. Part 5 is here: I Almost Hashed a Document Number That Needed to Be Read Again When I designed JWT validation for VaultPay, the only thing I was optimising for was speed. Local verification, no network call, decode the token with the shared secret, read the claims, move on. Every request gets this. It's fast - no round trip to AuthShield, no added latency on the hot path. That felt like the obvious right answer for a system processing financial transactions, where every millisecond on the request path matters. Then I asked myself a question I hadn't thought through properly: what happens if an admin gets deactivated in AuthShield right now, this second, while they still have a valid token sitting in their browser? The answer, with pure local validation, is uncomfortable. Nothing happens. The token is still cryptographically valid. The signature checks out. The claims say role: admin . VaultPay has no way of knowing that AuthShield revoked this person's access thirty seconds ago, because VaultPay never asked AuthShield. It just trusted the token. That's the moment dual-mode validation stopped being a performance optimisation and became a correctness requirement. Two Services, No Shared Database VaultPay and AuthShield are separate microservices with separate databases. AuthShield owns user accounts, login, JWT issuance, and role management. VaultPay owns wallets, transactions, KYC, and admin operations on t

2026-06-29 原文 →
开发者

How I Explored a US Health Dataset with Python — EDA + Hypothesis Testing

I recently completed an exploratory data analysis project on the NHANES (National Health and Nutrition Examination Survey) dataset from Kaggle. It's a real-world health survey collected by the CDC covering body measurements, lifestyle habits, and demographic data from thousands of US adults. In this article I'll walk you through exactly what I did — from loading and cleaning the data all the way to running statistical tests — and share what I found along the way. The Dataset The dataset has 5,735 rows and 28 columns , but for this project I focused on 8 columns that were relevant to the questions I wanted to answer: Column Description smoking Has the person smoked at least 100 cigarettes? gender Male or Female age Age in years education Highest level of education weight Weight in kg height Height in cm bmi Body Mass Index Step 1 — Loading and Selecting Columns import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns db = pd . read_csv ( ' NHANES.csv ' ) data = db . loc [:, ( ' SEQN ' , ' SMQ020 ' , ' RIAGENDR ' , ' RIDAGEYR ' , ' DMDEDUC2 ' , ' BMXWT ' , ' BMXHT ' , ' BMXBMI ' )] data = data . rename ( columns = { ' SEQN ' : ' id ' , ' SMQ020 ' : ' smoking ' , ' RIAGENDR ' : ' gender ' , ' RIDAGEYR ' : ' age ' , ' DMDEDUC2 ' : ' education ' , ' BMXWT ' : ' weight ' , ' BMXHT ' : ' height ' , ' BMXBMI ' : ' bmi ' }) One thing worth knowing about NHANES: all the columns come in as numeric codes. 1 means Male, 2 means Female. 1 means the person smoked, 2 means they didn't. You have to map these to readable labels before doing any analysis, otherwise your charts are meaningless. Step 2 — Cleaning the Data Drop the ID column and remove nulls data . drop ( ' id ' , axis = 1 , inplace = True ) data . dropna ( inplace = True ) This brought us from 5,735 rows down to 5,406 — about 6% lost, which is acceptable. Remove outliers using the IQR method The IQR (Interquartile Range) method flags values that fall too far outside the middle 50% of

2026-06-29 原文 →
AI 资讯

How I Built an AI Exam App in 8 Months to outsource studying

Eight months ago, a CS exam forced me to write pseudocode when I already knew how to code. Instead of studying, I rage-built an app. Today examintelligence.app is live. Here’s exactly how I got here—from vibe-coded POCs to a production hybrid AI pipeline—without the curated startup gloss. The Philosophy Behind the Build I’ve always believed studying for marks ≠ actually learning. When I was first introduced to organic chemistry, I hated it. Then I ran into GNNs in Machine Learning with PyTorch and Scikit-Learn , paired with the MoleculeNet dataset. Suddenly, everything clicked. I wanted to learn everything about it. That’s the core problem: exams optimize for pattern recognition, not curiosity. You’re forced down one prescribed path, and it rm -rf s the fun of learning in most cases. So one week before my first prelims, I decided to build exam intelligence. The plan was simple: introduce brutal efficiency using AI for what it’s actually built for: pattern recognition Parse every past paper, mark scheme, and examiner report. Distill it down to precisely what matters. Free up time for coding and creative work. Vibe-Coding the POC (and Why It Collapsed) I’m generally against vibe-coding. It’s unreliable, hard to maintain, and a security nightmare. But with prelims staring me in the face, I had no choice. I opened Claude and vibe-coded it module by module. The only code review I had time for was checking for suspicious os.system or subprocess calls. That was it. I shipped anyway. Initial stack: Gemini API (no agent frameworks, no LangGraph) Streamlit frontend PostgreSQL It validated my idea but functionally, it barely held together. After prelims, I finally looked at what the AI had actually built: Dashboard showing random stats Asked Gemini for a JSON response with 5 keys, saved only 2 Randomly created DB tables while trying to read subjects The kind of code you end up with when you let an AI cook unsupervised for a week. So I did the only reasonable thing: opened Neov

2026-06-28 原文 →
AI 资讯

Multi-Agent Systems in Production: When One Agent Isn't Enough and How We Coordinate Them

We built our first "multi-agent system" by accident. What started as a single agent that could research a topic, draft a report, check it against source data, and send a summary email had grown into a 2,000-token system prompt and a function list so long that the model kept forgetting tools existed. It wasn't a system — it was a monolith pretending to be intelligent. Breaking it apart into coordinated agents fixed most of the problems. It also introduced a new category of problems we hadn't thought about. Here's what we actually learned. When One Agent Is Enough (and When It Isn't) The temptation to add more agents is real, but the overhead isn't free. Every agent boundary you add is a place where context can get lost, latency increases, and errors compound. One agent is the right call when: The task fits in a single LLM context window without crowding The steps are sequential and each depends heavily on the prior output You need tight reasoning across all the information (summarising a document, for example) You need multiple agents when: A single agent's context window is being maxed out with tool definitions, history, or data Different steps require genuinely different "personas" or instruction sets (research vs. writing vs. fact-checking) Steps can run in parallel and the latency saving matters You want to isolate failure — if the data extraction agent fails, the report-writing agent shouldn't be affected The key question we ask: Is this one job or a pipeline of jobs? If you'd describe it to a human as "first do X, then Y takes that and does Z", you probably have a pipeline, not a single task. The Three Patterns We Actually Use 1. Supervisor-Worker A thin orchestrator agent decides what needs doing, dispatches to specialised worker agents, and stitches the results together. The workers are narrow — they do one thing and don't need to know about the rest of the workflow. This is our most common pattern. The supervisor's system prompt stays small because it's rout

2026-06-28 原文 →
AI 资讯

I Built a Free Apache Kafka Course from Scratch — Here's the Full Curriculum (and What I Got Wrong)

I Built a Free Apache Kafka Course from Scratch — Here's the Full Curriculum (and What I Got Wrong) I spent months building a free Apache Kafka course covering everything from first principles to a real-time analytics platform final project. No paywall. No "premium tier." 9 modules, 470 minutes of content, completely free. Here's the full syllabus, the Python code that actually works, and the honest mistakes I made building the curriculum — so you don't repeat them. Why I Built This Every time someone asked me "how do I learn Kafka?", I sent them to the same 3 places: The official Confluent docs (dense, assumes you already know what you're doing) A $15 Udemy course that spends Module 1 explaining what a computer is A YouTube playlist where half the videos are deleted None of them answered the real question beginners have: why does Kafka exist, and what problem does it actually solve before I write a single line of code? That's the gap I built for. The Problem With Most Kafka Tutorials Most tutorials start with: "Kafka is a distributed event streaming platform..." And then they immediately show you a Docker Compose file with 6 services. Beginners copy-paste it, something breaks, they don't know why, they quit. The real problem is that Kafka is an answer to a specific architectural problem — and if you don't understand the problem first, the solution makes no sense. So Module 1 and 2 of this course don't touch Kafka at all. They build the problem statement from scratch. The Full Syllabus (9 Modules, 470 Minutes) Module 1: Introduction to Kafka — 35 min Not "what is Kafka" — but why event streaming exists at all. What breaks in traditional request-response architectures at scale. Module 2: The Problem Statement — 30 min A real-world scenario: you're building an e-commerce platform. Orders, inventory, notifications, analytics — all tightly coupled. What happens when one service goes down? This module makes the pain visceral before Kafka enters the picture. Module 3: How

2026-06-28 原文 →
AI 资讯

From Regex Hell to AI: How I Finally Tamed Messy PDF Invoices

Last month, I spent three days wrestling with 500 PDF invoices. Each one had the same data—vendor name, invoice number, total amount—but the layouts were all over the place. Different fonts, missing headers, tables that somehow broke across pages. I tried regex. I tried OCR with layout analysis. I even tried building a rule-based parser that looked for keywords like "Total:" . Nothing worked reliably. Every time I fixed one pattern, another invoice broke. I was one commit away from throwing my laptop out the window. Then I took a step back. I realized I didn't need to understand every layout variation. I just needed to understand the data . And that's where AI came in. What didn’t work Let me be clear: I tried the usual suspects first. Regex. Classic. I wrote patterns like r"Total\s*:\s*\$?(\d+\.\d{2})" . Worked on 60% of invoices. The rest had "Total Due" or "Amount Total" or the dollar sign in a different place. Regex is great when you control the input. I didn't. OCR with layout parsing. I used Tesseract with --psm 6 and tried to extract lines by bounding boxes. It helped a bit, but tables with merged cells or rotated text threw it off. Plus, I had to write code to guess which box was a field name and which was a value. Rule-based parser. I built a dictionary of known vendors and their layouts. That worked … until I got an invoice from a new vendor. Maintenance became a nightmare. I was solving the wrong problem. Instead of fighting formatting, I needed to focus on meaning . The AI approach that saved me I remembered that large language models are surprisingly good at understanding context. If I could give the model the raw text from a PDF and a description of what I wanted, maybe it could extract the fields directly. Here’s the core idea: treat extraction as a structured generation task. Provide a prompt with a few examples (few-shot) or just describe the schema, and let the model output JSON. I found an API that did exactly this with a simple HTTP call. (Full d

2026-06-28 原文 →
AI 资讯

Why your Cloudflare Turnstile token works in the browser but 403s from requests

Why your Cloudflare Turnstile token works in the browser but 403s from requests You solved the Turnstile widget. You can see the token in the page. You copy it into your script, POST the form from requests, and the server hands you back a 403 — or a JSON body with "success": false. The token clearly worked a second ago in the browser, so what changed? Short answer: a Turnstile token is not a password you can carry around. It's a one-time, short-lived proof bound to a very specific context, and replaying it from a different context is exactly what it's designed to reject. Below is what that context is, how to tell which constraint you're hitting, and the fix for each. The real scenario You're automating a flow on a Cloudflare-protected site. There's a cf-turnstile widget on the form. You get a token one of two ways: you render the page in a real browser (Playwright/Selenium) and read cf-turnstile-response, or you hand the sitekey + page URL to a solving service and get a token back. Either way, you then submit the form with a plain HTTP client requests, httpx, axios) and it fails. The frustrating part: it's intermittent-looking. The reason it feels random is that there are four separate constraints, and you're usually tripping a different one each time. The four things a Turnstile token is bound to 1. It's single-use Once Cloudflare validates a token server-side (the siteverify call your target makes), that token is spent. Submit twice, retry, or test it once by hand, and the second use returns false. You get a fresh one per submission. 2. It has a short TTL Turnstile tokens expire fast — a few minutes. Solve early, do other work, submit later, and the token can be dead on arrival. The widget auto-refreshes in the browser precisely because tokens go stale; a script that grabs the token and sits on it loses that refresh. 3. It's bound to the sitekey and the page URL Multiple widgets. Some pages embed more than one Turnstile (login + newsletter). Solving the wrong site

2026-06-28 原文 →
AI 资讯

I Built 3 MCP Servers for AI Agents — Here's How They Work

What are MCP Servers? The Model Context Protocol (MCP) is an open standard that lets AI agents use external tools through a unified interface. Think of it as USB-C for AI — one protocol connects any AI client (Claude Desktop, Cursor, VS Code with Cline) to any tool or data source. I built three production-ready MCP servers and published them to PyPI and GitHub. Here's what they do and how to use them. 1. Web Search MCP Server uvx crewai-web-search-mcp Two tools: web_search(query) — Searches Google/SerpAPI and returns ranked results with snippets extract_content(url) — Fetches and extracts readable content from any web page Use cases: Ask your AI about current events, research competitors, pull documentation, verify facts in real time. { "mcpServers" : { "web-search" : { "command" : "uvx" , "args" : [ "crewai-web-search-mcp" ] } } } 2. Code Review Automation MCP uvx code-review-automation Three tools: review_code(diff) — Analyzes code changes for bugs, security issues, anti-patterns, style violations check_quality(path) — Runs static analysis and returns a quality report analyze_pr(diff) — Produces a structured review: what changed, what's risky, suggestions Use cases: Paste a PR diff and get an instant review. Catch issues before they reach production. 3. Document Intelligence Server uvx document-intelligence-server Three tools: extract_document(path) — OCR and text extraction from PDFs, scanned docs, images classify_document(path) — Identifies document type (invoice, report, contract, article) summarize_document(path) — Generates a structured summary from extracted content Use cases: Process uploaded PDFs, extract data from scanned forms, summarize long reports. Pricing All three servers use a shared credit system: Tier Price Credits Free $0 50 calls/day Starter $20 2,000 calls Pro $100 12,000 calls Buy credits once, use them across any server. Credits never expire. How it works: Install with uvx crewai-web-search-mcp Use 50 free calls per day — no key needed For u

2026-06-28 原文 →
AI 资讯

Why I Built Aegis Pulse - Part 1

Why did I build Aegis Pulse? As always, it started with a simple thought that keeps getting me time and time again: "I should automate this." So, I announced Aegis Stack publicly on Reddit on December 3rd. From that very moment, I became great friends with the Unique Clones / Total Clones & Unique Visitors / Total Views charts in GitHub's analytics page. Due to the nature of aegis-stack, every stack that is spun up will clone the actual repo itself (outside of caching situations, which may vary from user to user). I didn't realize it at the time, but those clone numbers, especially the Unique Clones, would become the most important metric for me to track usage. There's this funny thing that happens when you release an OSS tool. You expect people to say something, maybe tell others, ask questions... just... something... Instead, the person looks at the tool, sees if it makes their life easier, and puts it in their bag of other tools. I know this, because this is me! I never thought about it until I'm on the other side. I had to mentally go through all the tools I had used over the years, and realized I never cared about anything other than the tool itself. And if it didn't work, I would try to make it work, and if not, just move on. Time is money, and all of that. All of that is to say, clones are something I have been tracking since day one. Now... GitHub has a 14-day rolling window period in which they have daily values, and the 14-day rolling totals. And when I say 14 days, I mean it. That's all you get, and it's on you to keep track of everything outside of that. Fair enough. Thus began the daily ritual of going and grabbing the latest numbers from the previous day, and pasting the data into 3 separate AI chats: ChatGPT, Claude Opus, and Google Gemini. I figured that since I was already storing all of this data, I might as well see what type of insights I could get from these chats (which were preloaded with enough context to know what's going on). It was a great

2026-06-28 原文 →
AI 资讯

Stop Guessing Why Your Shopify Product CSV Import Failed

You exported a product CSV, edited it in Excel or Google Sheets, and uploaded it to Shopify. Shopify shows a generic error — or worse, it silently imports the wrong thing: a handle gets overwritten, a variant attaches to the wrong product, half your rows go missing. You find out days later from a customer. Shopify CSV Preflight Validator checks the file before you upload it. It runs locally on your machine, never touches your store, needs no API key, and returns three things: fixed_products.csv — a safe copy with the unambiguous, mechanical mistakes already corrected. errors.csv — a machine-readable list of every finding (row, rule, severity, suggested fix). report.md — a human-readable report you can read in 30 seconds. No login. No upload of your catalog to a third party. Just a file in, a verdict out. Why CSV imports fail (and why the error message doesn't help) Shopify's product CSV import is a two-stage process: it validates the file, then applies rows. A file can pass the upload dialog and still misbehave on apply. The most common ways merchants get burned: A spreadsheet adds a UTF-8 BOM to the first cell. The first header ( Title ) becomes invisible-garbage + Title , so Shopify can't find the title column. Header case / legacy names drift. title instead of Title , Handle instead of URL handle . Some get ignored, some get rejected. A variant row loses its parent handle. Shopify can't tell which product the variant belongs to. Two product rows share one handle. Shopify silently keeps one and overwrites/merges the other. Image alt text with no image URL, negative prices, compare-at prices below the real price — small data bugs that ship to your live storefront. These are not exotic. They're what happens every time a human edits a CSV in a spreadsheet. What the tool actually does — a real run Here is a messy export with several of the problems above. Running: csv-preflight check messy-product-import-sample.csv --out-dir ./out --lang en produces this report.md (ve

2026-06-28 原文 →
AI 资讯

CDP Browser Control: Driving Real Chromium from Python

Playwright and Selenium are great until you hit bot detection. Google OAuth, Cloudflare, and Vercel checkpoints all flag headless browsers. Here's how to control a real Chromium instance via CDP using Python and websockets. Why Not Playwright? Playwright launches a headless browser with automation flags. Even in headed mode with Xvfb, Google detects it. The CDP Approach Launch Chromium with remote debugging: chromium-browser --user-data-dir = /path/to/profile --remote-debugging-port = 9222 --no-first-run Connect via WebSocket in Python: import asyncio , json , websockets , urllib . request async def get_page_ws (): resp = urllib . request . urlopen ( ' http://localhost:9222/json ' ) targets = json . loads ( resp . read ()) for t in targets : if t [ ' type ' ] == ' page ' : return t [ ' webSocketDebuggerUrl ' ] async def cdp_call ( ws , method , params = None ): msg_id = cdp_call . id = getattr ( cdp_call , ' id ' , 0 ) + 1 msg = { ' id ' : msg_id , ' method ' : method } if params : msg [ ' params ' ] = params await ws . send ( json . dumps ( msg )) while True : resp = json . loads ( await ws . recv ()) if resp . get ( ' id ' ) == msg_id : return resp Key Advantages Real browser fingerprint, no automation flags Persistent sessions, cookies survive across runs Google OAuth works, existing sessions carry over No bot detection, it IS a real browser Follow for more tutorials on browser automation and AI agent architecture.

2026-06-28 原文 →
AI 资讯

Building a RAG System from Scratch with pgvector and Gemini — Introduction

What This Guide Covers When you start building LLM-powered applications, one pattern becomes unavoidable: RAG (Retrieval-Augmented Generation) . LLMs only know what they were trained on. Your company's internal documents, the latest spec sheets, project-specific information — none of that exists in the model. To handle data the model doesn't know, you need a system that retrieves relevant knowledge in real time and injects it into the context. That's RAG. In this guide, we'll implement a RAG system from scratch using pgvector and Gemini, then extend it step by step through Tool Use, AI Agents, MCP, and cloud deployment. Step 1: Embedding · Vector DB · RAG — core implementation Step 2: AI Architect perspective — design decisions explained Step 3: Tool Use — LLM autonomously searches the DB Step 4: AI Agents — combining multiple tools Step 5: MCP — exposing tools as a server Step 6: Cloud deployment — Render × Supabase Three Concepts to Understand First Embedding Computers can't measure "semantic similarity" from raw text. Embedding converts text into a list of numbers (a vector), and semantically similar words produce numerically similar patterns. "dog" → [ 0.82 , 0.75 , 0.10 , ... ] 768 numbers "cat" → [ 0.78 , 0.72 , 0.12 , ... ] ← similar pattern to "dog" "bank" → [ 0.08 , 0.10 , 0.85 , ... ] ← completely different Gemini's embedding model handles this conversion. Vector DB A regular DB searches by keyword matching. A vector DB searches by numeric distance — meaning it finds semantically related documents even when the exact words don't match. -- Regular search (misses if keywords don't match) SELECT * FROM docs WHERE body LIKE '%F1 score%' ; -- Vector search (finds semantically related docs) SELECT * FROM docs ORDER BY embedding <=> query_vector LIMIT 3 ; Search for "how to measure model performance" and it finds "F1 score calculation" — even without matching words. We use pgvector , a PostgreSQL extension, for this. RAG LLMs are limited to their training data. R

2026-06-28 原文 →
AI 资讯

Agents Are Learning to Write Their Own SKILL.md Files

The Agent Skills open standard today, and the 2026 research on agents that write their own skills. TL;DR: In late 2025, "Agent Skills" became a thing — a dead-simple way to teach an AI agent a task: a folder with a SKILL.md file (some instructions in Markdown). It's already an open standard. The wild part is what's coming next: agents that write their own skills. I built a demo where an agent solves a task the hard way once, saves a real SKILL.md , and then reuses it — cutting its total effort almost in half. ~130 lines, no API key. First, what's a "skill"? If you've used Claude Code or similar tools lately, you've probably seen SKILL.md files. The idea is refreshingly low-tech. A "skill" is just a folder with a Markdown file that says how to do something : --- name : csv-to-markdown description : Turn comma-separated text into a Markdown table. Use when the input looks like CSV and the user wants a table. --- # CSV to Markdown ## Instructions Split the text into rows on newlines and columns on commas. Make the first row the header, add a `---` divider row, then format every row as `| a | b | c |`. That's it. No SDK, no config. Anthropic introduced this in October 2025 and then published it as an open standard ( agentskills.io ) in December 2025, so the same skill folder now works across ~30+ different agent tools (Claude Code, Cursor, Copilot, and more). The full rules are short ( agentskills.io/specification ): the only required fields are name (1–64 chars, lowercase-with-hyphens, and it must match the folder name) and description (≤1024 chars, saying what it does and when to use it ). Everything else — license , metadata , compatibility , allowed-tools — is optional. That's the whole spec. The SKILL.md files my demo writes follow it to the letter, so they'd load unmodified in any compatible CLI. The clever trick: progressive disclosure Here's the smart part. If you just dumped 50 skills' worth of instructions into the agent's context, you'd fill it up and leave n

2026-06-28 原文 →
AI 资讯

I Built an AI Agent That Gets Curious On Its Own

Active inference: curiosity emerges for free from minimizing surprise — 48% vs 100% on a foraging task. TL;DR: Most AI agents chase rewards — they pick whatever action scores the most points. I tried a different, brain-inspired goal: avoid surprises . Something neat happened — the agent became curious without being told to. It goes looking for information before acting, and that takes it from 48% to 100% on a simple task. ~100 lines. Two different ways to make decisions Most AI agents are "reward chasers." Give them points for doing well, and they'll pick whatever action they expect to score highest. Simple and effective. There's another idea from brain science: instead of chasing points, try to avoid being surprised — act so the world matches what you expected. It sounds almost too simple, but it leads to a surprising bonus: when you're trying not to be surprised, going and finding out what you don't know becomes valuable all by itself. In other words, curiosity isn't something you have to bolt on. It comes for free. This is called active inference , and in 2026 it jumped from neuroscience into AI as a serious approach ( here's a 2026 paper ). Here's the smallest demo that makes it click. The 10-second version The task: a reward is hidden behind either the LEFT door or the RIGHT door (50/50). There's also a hint you can check that tells you which door — if you bother to look. ❌ Reward-chaser ✅ Curious agent What it cares about getting the reward, right now getting the reward + not being unsure What it does guesses a door checks the hint first, then opens the right door Success (400 tries) 48% 100% Nobody told the second agent "go check the hint." It did it on its own, because being unsure bothered it. How it works Before acting, the agent scores each option on two things: Does this get me closer to the reward? Does this make me less unsure about what's going on? value_of_checking_the_hint = how_unsure_am_i # high when it's a total coin-flip value_of_just_guessing =

2026-06-28 原文 →
AI 资讯

Can an AI Agent Pass the Test We Give 4-Year-Olds?

Theory of Mind and the Sally-Anne false-belief test, in ~60 lines of Python. TL;DR: There's a famous test that kids pass around age 4. It checks whether you understand that other people can believe things that aren't true. I built two AI agents: one that only knows "what's actually happening" (fails, like a toddler) and one that keeps track of what each person believes (passes). It's ~110 lines, and it's the foundation for agents that can actually work together . The test Sally puts her marble in the basket , then leaves the room. While she's gone, Anne moves the marble to the box . Sally comes back. Where will she look for her marble? If you said basket , nice — you just used something called "theory of mind." Sally never saw the marble move, so in her head it's still in the basket. What's actually true (it's in the box) and what Sally believes (it's in the basket) are two different things, and you kept them separate without even thinking about it. A 3-year-old says "box" — they can't yet separate what they know from what Sally knows. A 4-year-old says "basket." It's one of the most famous tests in child psychology, and in 2026 it's become a real test for AI agents too. The 10-second version ❌ Agent with no "theory of mind" ✅ Agent that models other minds What it tracks only what's actually true what each person believes, separately Where will Sally look? "box" "basket" Result FAIL (only knows reality) PASS How it works (the whole trick) The only difference between the two agents is one rule: a person's belief only updates when that person is actually in the room to see it happen. def someone_moves_the_marble ( new_place , who_is_watching ): for person in who_is_watching : # only people in the room beliefs [ person ] = new_place # update THEIR mental picture So when Anne moves the marble while Sally is out, only Anne's mental picture updates. Sally's is frozen at "basket." Ask the simple agent and it just reports reality ("box"). Ask the smarter agent and it answer

2026-06-28 原文 →
AI 资讯

Do AI Agents Need to Sleep? I Built One That Does

A sleep-like phase that consolidates noisy daily experience into durable memory — 75% vs 100% recall. TL;DR: There's a wave of 2026 research giving AI a "sleep" phase — time spent not answering questions, just tidying up what it learned that day. I built a 90-line demo of the idea. The agent that "sleeps" remembers 100% of what it learned. The exact same agent without sleep remembers only 75% and gets confused by bad info. Runs on a laptop. The memory problem every AI app hits If you've built anything with an LLM, you know the pain: the model only "remembers" what's in its current context window. Once the conversation gets long enough, the oldest stuff scrolls off the top and is just... gone. Forgotten. The usual fix is "make the context window bigger." But that's like fixing a messy desk by buying a bigger desk. It's expensive, and the model still gets worse as you cram more in (a real, measured effect — more text in the window can actually lower accuracy). Your brain doesn't work this way. You don't remember every sentence anyone said today. While you sleep, your brain replays the day, keeps the important bits as long-term memory, and dumps the rest. That's how you remember "I like coffee" without remembering every single cup. A couple of 2026 papers ask the obvious question: Do Language Models Need Sleep? Their answer: giving an AI a quiet "offline" phase to consolidate memories makes it remember better. So I built the simplest version that shows why. The 10-second version ❌ Agent with no sleep ✅ Agent that sleeps How it remembers keeps only the last N messages saves a tidy summary every night After 30 noisy days 75% recall 100% recall Tricked by bad info? yes no — it goes with what it saw most often Same experiences, same noise, same memory test. The only difference is whether the agent sleeps. How it works Each "day," the agent hears facts like Alice → drinks → coffee . To make it realistic, about 1 in 5 facts is wrong (people misremember, logs have errors). Th

2026-06-28 原文 →
AI 资讯

I Built an AI Agent That Rewrites Its Own Code (in ~150 lines)

A tiny Darwin Gödel Machine that edits itself and keeps only changes that verifiably score higher. TL;DR: I built a small program that improves itself . It looks at the tasks it's failing, edits its own code to fix them, and keeps a change only if the change actually makes it score better on a test. It goes from passing 1 of 8 tasks to 8 of 8 — and nobody wrote those fixes but the program itself. It runs on a laptop in under a second. No fancy hardware, no API key. The old dream: software that improves itself Normally, software only gets better when we make it better. You write code, you find a bug, you fix it, you ship again. The program never improves on its own. People have wanted "software that improves itself" for decades. The classic version (called a "Gödel Machine") had one rule that made it impossible to build: before the program could change a line of its own code, it had to mathematically prove the change would help. Proving that about real code is basically impossible, so the idea never worked. In 2025, researchers found a way around it with the Darwin Gödel Machine . They dropped the "prove it first" rule and replaced it with something every engineer already trusts: Try the change. Run the tests. If the score went up, keep it. If not, throw it away. That's it. It's basically how we all work — make an edit, run the test suite, keep what passes. The twist is that the program is the one making the edits. In the real paper, this let an AI coding assistant improve its own tooling and jump from solving 20% to 50% of a hard benchmark of real GitHub issues. I wanted to actually see this happen, so I built the tiniest version I could. The 10-second version Start After improving itself What it can do only uppercase learned 6 more skills on its own Test score 🔴 1 / 8 🟢 8 / 8 Who wrote the fixes? — the program did Start: ███░░░░░░░░░░░░░░░░░░░░░ 1/8 (only knows: uppercase) +reverse ██████░░░░░░░░░░░░ 2/8 +dedup_csv █████████░░░░░░░░░ 3/8 +sum_csv ████████████░░░░░░

2026-06-28 原文 →