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

标签:#python

找到 615 篇相关文章

AI 资讯

From Blood Tests to Meal Plans: Building a Self-Correcting Health Agent with LangGraph

Ever felt like your fitness app is just a fancy spreadsheet? You log a high uric acid result from your latest blood test, yet it still suggests a high-protein steak dinner for "gains." In the world of AI Agents , we are moving past static prompts. Today, we’re building a Self-Correcting Health Agent using LangGraph , LangChain , and OpenAI . This agent doesn't just chat; it monitors laboratory biomarkers like cholesterol and uric acid, maintains a long-term memory via SQLite , and dynamically rewrites your lifestyle plan using advanced OpenAI Function Calling . If you've been looking to master autonomous health agents and complex state management, you're in the right place. Let's dive into the future of personalized wellness. The Architecture: State-Driven Personalization Unlike a standard linear chain, a health agent needs to "loop" and "reason." If the agent detects an abnormal lab value, it must trigger a specific logic branch to revise existing plans. Here is how the data flows through our LangGraph system: graph TD A[User Input/Lab Report] --> B{Analyze Biomarkers} B -- Abnormal Found --> C[Tool: Plan Rewriter] B -- All Normal --> D[Tool: Maintenance Plan] C --> E[Update SQLite Memory] D --> E[Update SQLite Memory] E --> F[Output Final Recommendation] F --> G[Wait for Next Input] G -- New Data --> B Prerequisites To follow along, you'll need: LangGraph & LangChain : For orchestration. OpenAI API : For the reasoning engine (GPT-4o recommended). SQLite : To handle persistent state and "memory" of your health journey. Step 1: Defining the Agent State In LangGraph, the State is the source of truth. We need to track the user's current health metrics and their active diet plan. from typing import Annotated , TypedDict , List from langgraph.graph import StateGraph , END import operator class HealthState ( TypedDict ): # We use operator.add to keep a history of logs logs : Annotated [ List [ str ], operator . add ] biomarkers : dict current_diet_plan : str revision_req

2026-06-05 原文 →
AI 资讯

Build Your Own MCP Server from Scratch

Every AI agent ships with the same bottleneck: it can only reason over what it can reach. MCP servers dissolve that boundary. They expose tools, resources, and prompts to any compliant client over a JSON-RPC wire format so lean you can implement it in an afternoon. Yet most developers grab a framework, copy a template, and ship something they can barely debug. Forge starts differently. You will build an MCP server from the bare protocol up, understand every byte on the wire, and gain the mental model that makes every future server trivial. The Idea (60 Seconds) MCP is a JSON-RPC 2.0 protocol. A client sends a request. Your server returns a response. Three request types power the core loop: initialize , handshake. Client and server exchange capabilities. tools/list , discovery. Server returns every tool it offers, each with a JSON Schema describing its inputs. tools/call , execution. Client names a tool and passes arguments. Server runs the handler and returns structured content. Transport is either stdio (JSON-RPC over stdin/stdout) or HTTP (Streamable HTTP). Stdio is the simplest place to start: read a line from stdin, parse it, dispatch, write a line to stdout. That is the entire architecture. Everything else is error handling, schema validation, and ergonomics. Why This Matters MCP servers are the new APIs. Where REST gave machines endpoints, MCP gives agents tools with typed inputs and structured outputs. Every integration layer from IDE assistants to autonomous workflows converges on this protocol. The standard is young. The primitives are stable. The surface area is small enough to hold in your head all at once. Knowing the wire format gives you three advantages frameworks obscure: Debugging , when a tool call fails, you can read the raw JSON-RPC message and pinpoint the fault in seconds. Portability , any language, any runtime, any transport. Write a server in Bash if you want. The protocol is the contract. Evolution , MCP will add capabilities. Understanding

2026-06-05 原文 →
AI 资讯

Rust Ownership System Explained for JavaScript Developers

Rust Ownership System Explained for JavaScript Developers Quick context (why you're writing this) I was trying to rewrite a small utility I’d written in JavaScript—a function that takes a string, splits it into words, and returns the longest one. In JS it’s trivial: you pass the string around, mutate arrays, and nothing blows up. When I attempted the same thing in Rust, the compiler kept yelling at me about “use of moved value” and “cannot borrow as mutable because it is also borrowed as immutable”. I spent a good chunk of an afternoon staring at those errors, thinking I’d missed some syntax detail, only to realize the real issue was a completely different way of thinking about data. If you’ve ever felt that Rust’s compiler is being overly pedantic, you’re not alone—but once you grasp what it’s protecting you from, the frustration turns into appreciation. The Insight Rust doesn’t treat variables like JavaScript’s loosely‑typed references. Instead, it enforces ownership at compile time. Three ideas tend to surprise developers coming from a garbage‑collected world: Move semantics – assigning a value to another variable moves it; the original is no longer usable unless you explicitly clone it. Borrowing rules – you can have either many immutable references or exactly one mutable reference to a piece of data, but never both at the same time. Lifetimes – the compiler tracks how long references are valid, preventing dangling pointers without a garbage collector. The first two are the ones that trip people up most often, and they directly address the class of bugs JavaScript developers know all too well: accidental shared‑state mutations and use‑after‑free‑like mistakes (though in JS they show up as weird undefined values rather than crashes). Let’s look at each with a concrete example, show the common mistake, and then see how to do it right. How (with code) Move semantics – the “you can’t use it after you give it away” surprise fn main () { let greeting = String :: from

2026-06-05 原文 →
开发者

Python Number Programs Using While Loop: Step-by-Step Guide

Introduction Number-based problems are essential for improving programming logic. Using Python's while loop, we can solve different types of problems involving divisibility, counting, and special numbers. This article demonstrates step-by-step solutions using simple logic and structured code. Basic Practice 1. Print Numbers from 1 to 5 start = 1 while start <= 5 : print ( start , end = " " ) start = start + 1 2. Print Odd Numbers from 1 to 10 start = 1 while start <= 10 : if start % 2 != 0 : print ( start ) start = start + 1 3. Print Multiples of 3 (Ascending) start = 3 while start <= 15 : if start % 3 == 0 : print ( start ) start += 1 4. Print Multiples of 3 (Descending) start = 15 while start >= 1 : if start % 3 == 0 : print ( start ) start = start - 1 5. Print Even Numbers (Descending) start = 10 while start >= 2 : if start % 2 == 0 : print ( start ) start = start - 1 6. Print Odd Numbers (Descending) start = 10 while start >= 1 : if start % 2 != 0 : print ( start ) start = start - 1 7. Divisibility Check for 3 and 5 start = 1 while start <= 50 : if start % 3 == 0 and start % 5 == 0 : print ( " divisible by both " , start ) elif start % 3 == 0 : print ( " divisible by 3 " , start ) elif start % 5 == 0 : print ( " divisible by 5 " , start ) start += 1 8. Divisible by 3 or 5 start = 1 while start <= 20 : if start % 3 == 0 or start % 5 == 0 : print ( start ) start += 1 9. Finding Divisors of a Number num = 12 i = 1 while i <= num : if num % i == 0 : print ( i ) i += 1 10. Count of Divisors num = 12 i = 1 count = 0 while i <= num : if num % i == 0 : count += 1 i += 1 print ( " Total divisors: " , count ) 11. Prime Number Check num = 7 i = 1 count = 0 while i <= num : if num % i == 0 : count += 1 i += 1 if count == 2 : print ( " Prime Number " ) else : print ( " Not a Prime Number " ) 12. Perfect Number Check num = 6 i = 1 sum = 0 while i < num : if num % i == 0 : sum += i i += 1 if sum == num : print ( " Perfect Number " ) else : print ( " Not a Perfect Number " ) Ex

2026-06-04 原文 →
AI 资讯

Cyber SH Agent — Goated AI for Hackers

Who I Am I’m neo4 — a red teamer with ~3 years of offensive security experience, a hardcore Linux/Arch culture operator, and a Python developer who thrives in the terminal. My workflow is pure hacker logic: OPSEC first, root‑level control always. I’ve been recognized by Disney’s Vulnerability Disclosure Program for responsible disclosure, and I build tools that merge hacker culture with AI. Why I Built Cyber SH Agent Most AI tools today are cloud‑locked, API‑dependent, and surveillance‑heavy. That doesn’t fit hacker culture. So I built Cyber SH Agent — an offline AI CLI operator that runs locally, no servers, no API keys, no data leaks. Repo: https://github.com/neo4-svg/cybersh.git 🔧 Core Features Agent Mode → AI controls your CLI with system access. Sec Mode → Bug bounty & penetration testing expert. Vibe Mode → Creative coding & UI/UX assistance. Code Mode → Production‑ready code generation. Chat Mode → General AI assistant. All 100% offline — runs GGUF models via llama-cpp-python. No servers, no API keys, no data leaving your machine. hope you like it!

2026-06-04 原文 →
AI 资讯

Context Engineering: The Skill Replacing Prompt Engineering in 2026

If you've been calling yourself a "prompt engineer" for the past two years, it's time to update your vocabulary — and your mental model. In 2026, the real leverage when building LLM-powered systems isn't in crafting the perfect sentence. It's in context engineering : designing everything an LLM sees before it ever generates a response. Andrej Karpathy coined the term in mid-2025, and it's since taken over serious AI engineering discussions. This article breaks down what context engineering actually is, why it matters more than prompt writing, and gives you concrete techniques you can apply today. What Is Context Engineering? Context engineering is the discipline of systematically designing the information environment that surrounds a prompt. Where prompt engineering asks "what should I tell the model to do?", context engineering asks "what does the model need to know to do it well?" Think of it this way: a doctor doesn't just answer the question you ask on the spot. They look at your chart, your history, your vitals, and then respond. Context engineering is building that chart for your LLM. The context window is the LLM's working memory — everything it can "see" at once. In 2026, these windows are massive: Claude Opus 4.x : 200K tokens GPT-4o : 128K tokens Gemini 2.5 Flash : Up to 1M tokens But bigger isn't automatically better. More tokens = more cost, more latency, and a real risk of what researchers call the "lost-in-the-middle" problem — where models process information at the beginning and end of the context more reliably than content buried in the middle. Why This Matters for Data Engineers Data engineers are increasingly building pipelines that feed LLMs: RAG systems, AI copilots for data quality, agents that write and review SQL, tools that summarize data lineage. In every one of these systems, the quality of what lands in the context window directly determines output quality. A poorly designed context is like feeding a senior analyst a jumbled mess of raw l

2026-06-04 原文 →
AI 资讯

I Built a CLI Tool to Delete Default VPCs Across All AWS Regions

This article is a machine translation of the contents of the following URL, which I wrote in Japanese: AWS 全リージョンのデフォルト VPC を一括削除する CLI ツールを作った #Python - Qiita はじめに こんにちは、ほうき星 @H0ukiStar です。 AWS アカウントを作成すると、デフォルト VPC と呼ばれる VPC が各リージョンに 1 つずつ作成されます。 このデフォルト VPC はパブリックサブネットのみで構成されており、これらのサブネットでは E... qiita.com Introduction Hello, I’m @H0ukiStar . When you create an AWS account, a VPC called the default VPC is automatically created in each region. This default VPC consists only of public subnets, and the default subnets are configured to automatically assign public IP addresses when launching EC2 instances. When launching an EC2 instance from the AWS Management Console, this default VPC is also selected by default, which can lead to resources being created with unintended network configurations depending on your environment. For this reason, if the default VPC is not needed in your organization’s network design, some teams choose to delete it in advance as part of their operational baseline. In this article, I’ll introduce a CLI tool I created to delete default VPCs across all available regions in an AWS account. CLI Tool for Deleting Default VPCs: aws-default-vpc-cleaner The tool is available in the following repository: H0ukiStar / aws-default-vpc-cleaner A tool to delete default VPCs and related resources across all AWS regions. AWS Default VPC Cleaner A tool to delete default VPCs and related resources across all AWS regions. AWSアカウント上のすべてのリージョンに存在するデフォルトVPCと関連リソースを削除するツール。 Features / 機能 Multi-Region Support / 複数リージョン対応 : Delete default VPCs across all AWS regions or specific regions / すべてのAWSリージョンまたは特定のリージョンのデフォルトVPCを削除 Dry Run Mode / ドライランモード : List resources without deleting them / 削除せずにリソースをリスト表示 Safe Deletion / 安全な削除 : Deletes resources in the correct order to avoid dependency issues / 依存関係の問題を回避するために正しい順序でリソースを削除 Multi-Language / 多言語対応 : Supports English and Japanese output / 英語と日本語の出力をサポート Verbose Mode / 詳細モード : Detailed logging of operations / 操作の詳細なログ出力 De

2026-06-04 原文 →
AI 资讯

I built a Windows tool that turns screenshots into one searchable PDF — here's what I learned

For months I had the same annoying problem: folders full of screenshots I couldn't actually use. Lecture slides, PDFs I own, scanned pages — all just images . I couldn't Ctrl-F them, couldn't copy a line out, couldn't get my OS to index them. A picture of text is useless the moment you need to find something in it. So I built CapDrop to automate the whole chain on Windows. This is a write-up of how it works under the hood and the bugs that nearly broke me. The core idea You draw a capture box over a page, pick a page key (Page Down, arrow keys), set an interval, and walk away. CapDrop then: Captures each page on the interval Presses the page key for you to advance Auto-crops margins and toolbars out of every shot Runs OCR locally Binds everything into a single PDF with a real text layer The result is one document you can search, not a pile of images. The stack Electron for the app shell and capture/UI (I already had window management, hotkeys, and floating-bubble export working — no reason to rewrite). A Python OCR sidecar (RapidOCR) spawned as a child process. OCR runs 100% locally; nothing is ever uploaded. jimp for auto-crop, with a 12px safety pad so edge text never gets clipped. pdf-lib to bind the pages and inject the OCR text layer. The Electron + Python-sidecar split was a deliberate choice. People kept telling me to rewrite the whole thing in Python "for the OCR," but the Electron app already had everything except OCR. Adding a sidecar was a few hundred lines; a rewrite would've been months. The bug that cost me two days After adding the OCR pipeline, my global capture hotkey developed a 4-second delay on the first press. Cold, every time. I guessed wrong twice — thumbnail size, then a race condition. Both were dead ends. The only thing that actually found it was instrumenting the hot path with timing logs. The culprit: a fs.readFile of a tiny 749-byte settings.json on every hotkey press. On a cold start that read was taking 2–4 seconds — Windows Defender's

2026-06-04 原文 →
AI 资讯

GSoC Community Bonding Period: Getting Ready to Code

Hey everyone! Welcome back to my Google Summer of Code (GSoC) journey. In my last post, I shared the story of how I got into open source and was selected for GSoC with NumFOCUS to work on the Neural Network Builder API Refactor project for sbi (Simulation-Based Inference). Since the official announcement, the past three weeks have been dedicated to the Community Bonding Period . It is designed to help contributors get to know their mentors, understand the community culture, and familiarize themselves with the codebase and tools. Here is exactly what I did during these past three weeks to get ready for the main coding phase! The Kickoff Meeting We started the bonding period with a great kickoff call on Google Meet. It was a joint meeting that included the mentors for both of the selected sbi projects, the selected GSoC candidates. We were also joined by the mentee who successfully completed the GSoC project for sbi last year! Everyone introduced themselves, and it was incredibly inspiring to meet the team face-to-face (virtually!) and hear about everyone's backgrounds. Having a former GSoC student there was a huge bonus, as they shared some great insights into what to expect in the coming months. Setting Up the Machine A big part of getting started is making sure the development environment is properly configured. During our meetings, we discussed the machine setup in detail to ensure both candidates had everything required to run and test the sbi codebase locally without any hiccups. Embracing AI Coding Assistants One of the most interesting discussions we had was about using AI coding assistants. In the modern development world, tools like these are becoming standard, and our mentors actually encouraged us to use them! However, they emphasized using them carefully and strictly following project guidelines. To help us get the most out of these tools without compromising code quality, the mentors shared some excellent Claude code tutorials and provided us with resour

2026-06-04 原文 →
AI 资讯

Cloudflare Turnstile in Playwright: Why Your Tests Stall and How to Solve It in 8 Lines

Cloudflare Turnstile in Playwright: Why Your Tests Stall and How to Solve It in 8 Lines If you're running Playwright or Selenium against any site behind Cloudflare, you've already met Turnstile. It's the new "managed challenge" widget Cloudflare started shipping in 2023, and it now appears in front of login flows, contact forms, signup pages, and increasingly the entire site root. Here's the part most teams miss: Turnstile doesn't always show a checkbox. A lot of the time it just sits invisible, runs its scoring loop, and either issues a token silently or stalls forever. Your test doesn't crash. It just times out at the next page.click("button[type=submit]") . The CI log says "element not interactable." Nobody knows why. I work on CaptchaAI. I'm going to show you exactly what's happening, then drop in 8 lines that fix it. The real scenario You have a Playwright suite that runs every PR. One day a test starts failing on the signup flow. You re-run it. It fails again. Locally on your laptop it passes. On CI it doesn't. What's actually happening: Cloudflare flagged your CI runner's IP block (GitHub Actions, GitLab runners, Hetzner, OVH, DO — all of them are on Cloudflare's "elevated risk" list). Turnstile decides to switch from invisible mode to "managed challenge" mode. Now there's a widget in the DOM that needs a real token before the form submit will accept. Your test never interacted with the widget because last week it didn't exist. Why retries don't help The instinct is to add a retry: 2 and move on. Don't. Cloudflare's scoring is per-IP-per-fingerprint, and each retry from the same runner makes the next challenge harder, not easier. After ~3 attempts you'll get full block pages instead of the widget. The right move is to solve the widget once, inject the token, and submit normally — exactly what a human user does, just faster. How Turnstile actually issues a token The widget renders an iframe pointing at challenges.cloudflare.com . Inside the iframe it runs a fi

2026-06-04 原文 →
开源项目

🔥 0x4m4 / hexstrike-ai - HexStrike AI MCP Agents is an advanced MCP server that lets

GitHub热门项目 | HexStrike AI MCP Agents is an advanced MCP server that lets AI agents (Claude, GPT, Copilot, etc.) autonomously run 150+ cybersecurity tools for automated pentesting, vulnerability discovery, bug bounty automation, and security research. Seamlessly bridge LLMs with real-world offensive security capabilities. | Stars: 9,216 | 38 stars today | 语言: Python

2026-06-04 原文 →
AI 资讯

Why Your LLM Agent Gives a Different P-Value Every Time (And What to Build Instead)

Hand the same paired before/after dataset (n = 25) to ChatGPT five times. Same prompt: "These are the same subjects measured before and after an intervention. Did their scores change significantly?" Four of the five runs return p = 0.009 from a paired t-test. The fifth run does a Shapiro–Wilk normality check on the differences first, decides they're non-normal, switches to a Wilcoxon signed-rank test, and reports p = 0.000018 . All five reach the same conclusion (significant). But notice what happened: only one run out of five thought to check an assumption you'd want it to check. The other four skipped it. The choice of method — and the test statistic, and the p-value — depended on whether the LLM happened to run an assumption check that time. On borderline data, this is the difference between reject and don't reject. If you're using LLMs for exploratory data analysis on a weekend project, you might shrug. If you're using them for anything that gets cited, gets submitted to a regulator, or gets handed to a clinician, this is a problem. It's a known problem — Cui & Alexander (2026) documented exactly this kind of method-divergence empirically; AIRepr (Zeng et al., 2025) shows the same thing across reproducibility metrics. The current answer in the literature is to constrain the agent so its execution is replayable. But replayability fixes "did we run the same code." It doesn't fix "did we run the right analysis." I've spent the last two months building a different fix. The more interesting half is the architecture. Let me walk through it. The real problem isn't temperature The first reflex is "set temperature=0 ." It's not enough. temperature=0 doesn't make a tool-using agent deterministic across runs. Three reasons: Inference isn't bitwise deterministic, even at temperature=0. Production LLM serving batches requests dynamically, and the attention kernels aren't batch-invariant — so the same input produces different output tokens depending on what other requests it

2026-06-03 原文 →
AI 资讯

How I Shaved 10 MB Off My Portfolio in One Command

PageSpeed Insights had been staring at me for weeks. Desktop was holding at 91. Mobile was stuck at 63. I'd already fixed the obvious stuff — non-blocking fonts, preconnects, fetchpriority on the hero image. But there it was, every single run: Improve image delivery — Est savings of 985 KiB Nearly a megabyte of wasted transfer, just from six project screenshots. And that was just the images visible above the fold. The full list across all projects was worse. The culprit: every image I'd ever uploaded through the Django admin was a PNG. Some of them were over 1 MB. WebP would have cut most of them by 80%. I knew this. I just hadn't done anything about it. So I wrote a management command to fix the backlog, and then made the model auto-convert on every future upload so I'd never have to think about it again. The Problem With PNGs in a Portfolio When you're building a portfolio, you screenshot your work and drag it into the admin. That screenshot is usually a PNG — lossless, full-size, straight from your display. Nobody optimises it because the admin accepts it and it shows up fine in the browser. But "shows up fine" isn't the same as "loads fast." A 1.4 MB PNG of a law firm homepage does not need to be 1.4 MB. Served as WebP at quality 85, it's 175 KB. Same visual result. Eight times smaller. Multiply that across 28 projects and you're looking at tens of megabytes that mobile users on slow 4G are downloading just to scroll past thumbnails. The One-Time Backlog Fix: A Management Command First, I needed a way to convert everything that was already in S3. A management command was the right tool — it runs in the production container with full access to the Django ORM and the configured storage backend, so it can read and rewrite files without needing to know whether they're on S3, local disk, or anywhere else. # backend/projects/management/commands/convert_images_to_webp.py from io import BytesIO from django.core.files.base import ContentFile from django.core.management.b

2026-06-03 原文 →