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

标签:#python

找到 708 篇相关文章

AI 资讯

The two things missing from every AI coding tool: workflow and context discipline

AI coding tools have gotten very good at one thing: generating code fast. What they haven't gotten good at is discipline. They don't know your architecture. They don't remember that you rejected a pattern last sprint. They don't know which parts of your context window are signal and which are noise. And they have no concept of a development workflow — no phases, no review gates, no verification steps. You describe what you want, they generate, and you hope the output fits. For small tasks this works fine. For anything that touches your real codebase at scale — refactors, new features with cross-cutting concerns, compliance-sensitive changes — the lack of workflow structure creates subtle, expensive problems that compound over time. We've been building Ortho to address two of these problems: workflow discipline (through ASES, a 6-phase AI development methodology) and context discipline (through a 9-component token optimization pipeline). This post explains both. The workflow problem with AI coding tools When a junior engineer joins your team, you don't just hand them a task and say "generate." There's a process: understand the codebase, plan the change, get the architecture reviewed, build it, test it, verify it, get it reviewed. The process exists because individual steps catch different categories of mistakes. AI coding tools collapse all of that into one step. You prompt. You get code. Done. The result isn't always bad code per file. The problem is architectural: the AI has no model of your layer boundaries, so it imports from layers it shouldn't touch. It has no memory of past decisions, so it re-proposes patterns you've already rejected. It has no verification step, so it confidently generates code that looks right but has subtle issues a reviewer would have caught in 30 seconds. The missing piece isn't a smarter model. It's a workflow. ASES: A 6-phase workflow for AI-assisted development ASES (v1.2) is the methodology built into Ortho's orchestration layer. It

2026-07-21 原文 →
AI 资讯

I Went Looking for the Diff Debt in My Own Repo

Two posts ago I said I'd shipped code I never read. It's easy to write that as a general observation about the industry. It's less comfortable to go open your own repo and count. So I did. Here's what I found, and what I've actually done about it. The repo It's a desktop app I built for my own company. Roughly fourteen thousand lines of Python, a Tkinter UI, invoicing and documents and reports, the kind of internal tool nobody else will ever see. I had never written Python before I started it. I built it anyway, with a lot of AI help, learning as I went. That combination - no prior experience, heavy AI assistance, a real deadline because the business actually needed the thing - is basically a diff debt factory. I wasn't cutting corners on purpose. I just didn't have the knowledge to evaluate half of what I was merging, and it worked, so I moved on. What I actually found The clearest example took me months to notice. Five different parts of the app generate PDFs. Quotes, proformas, reports, petitions, heat treatment certificates. Every one of them was failing, in different ways, at different times, and I kept fixing them individually. Different error, different module, different patch. The actual cause was one thing: LibreOffice wasn't installed on the machine. Every one of those modules quietly depended on it to do the document conversion. Not one of them said so anywhere. I'd merged that dependency five separate times without ever registering that I'd taken it on. That's diff debt in its purest form. The code wasn't messy. It wasn't badly written. It just made an assumption I'd never read, and I paid interest on it five times over before I understood the principal. There were smaller ones too. A path handling bug that only showed up because my Windows username has a Turkish character in it - the code assumed ASCII and nobody, including me, had thought about it. Two Python versions installed side by side, quietly fighting. A stray quotation mark in my system PATH th

2026-07-21 原文 →
AI 资讯

FROST-SOP V6.1.0 工程实践:从初始化流水线看「零门槛上手」

FROST-SOP V6.1.0 工程实践:从初始化流水线看「零门槛上手」 作者:神通说 日期:2026-07-21 主题:周二·SOP工程 | V6.1.0 新特性深度解析 开篇:一个让所有开发者头疼的问题 想象这个场景: 你刚克隆了一个开源项目,兴冲冲地跑起来,结果: ModuleNotFoundError: No module named xxx ImportError: DLL load failed OSError: [WinError 2] 系统找不到指定的文件 你开始疯狂搜索、提问、等回复。一小时过去了,项目还没跑起来。 这是开源项目最大的痛点之一:「最后一公里」问题。 今天,我们来聊聊 FROST-SOP V6.1.0 是如何解决这个问题的。 V6.1.0 核心特性:初始化流水线 V6.1.0 版本最核心的更新,是一个 全自动初始化流水线(Initialization Pipeline) 。 它解决什么问题? 环境依赖自动检测 :自动扫描 Python 版本、系统平台、必需依赖 缺失依赖自动安装 :自动安装缺失的包(通过 pip install) 配置引导式生成 :首次运行时自动创建配置文件 数据库自动初始化 :自动创建 SQLite 数据库和必要的表结构 种子数据自动导入 :自动导入示例 SOP 模板和工作区配置 代码示例 # initialize.py - 初始化流水线核心实现 import subprocess import sys import os from pathlib import Path class InitializationPipeline : """ FROST-SOP 初始化流水线 """ def __init__ ( self , project_root : Path ): self . root = project_root self . issues = [] self . warnings = [] def run ( self ) -> bool : """ 执行完整初始化流程 """ steps = [ ( " 环境检测 " , self . _check_environment ), ( " 依赖安装 " , self . _install_dependencies ), ( " 配置生成 " , self . _generate_config ), ( " 数据库初始化 " , self . _init_database ), ( " 健康检查 " , self . _health_check ), ] print ( " 🚀 FROST-SOP 初始化流水线启动 \n " ) for name , step_fn in steps : print ( f " 📦 { name } ... " ) try : result = step_fn () if not result : self . issues . append ( f " { name } 失败 " ) print ( f " ❌ { name } 失败 \n " ) return False print ( f " ✅ { name } 完成 \n " ) except Exception as e : self . issues . append ( f " { name } 异常: { e } " ) print ( f " 💥 { name } 异常: { e } \n " ) return False self . _print_summary () return True def _check_environment ( self ) -> bool : """ 检查 Python 版本和系统环境 """ version = sys . version_info if version . major < 3 or ( version . major == 3 and version . minor < 10 ): self . issues . append ( f " Python 版本过低: { version . major } . { version . minor } " ) return False print ( f " Python { version . major } . { version . minor } . { version . micro } " ) return True def _install_dependencies ( self ) -> bool : """ 安装项目依赖 """ req_file = self . root / " requir

2026-07-21 原文 →
AI 资讯

Why environment variables don’t suppress WP-CLI PHP Deprecated warnings — the phar + shebang path and a three-part structural fix

A previous post covered how to absorb PHP 8.2 Deprecated warnings from WP-CLI using a three-layer defense . The approach — prepending WP_CLI_PHP_ARGS to set error_reporting — works in many environments. But a case came up where Deprecated warnings wouldn’t disappear despite the same configuration. Tracing the cause revealed a structural reason why the environment variable never arrived. This post records that root cause and the three-part fix added in v1.6.8. Why environment variables don’t arrive — the phar + shebang execution path An agency reported that on Xserver, plugin list retrieval was failing across multiple sites (referred to here as "site A / site B") with a large volume of Deprecated messages. We reproduced the same behavior on our own Xserver setup (PHP 8.2.30, WP-CLI 2.7.1) and traced the execution path. Xserver’s /usr/bin/wp is a phar binary. Inside, it starts with a #!/usr/bin/env php shebang, so the actual startup sequence looks like this: shell → /usr/bin/wp (shebang: #!/usr/bin/env php) ↓ env locates php and starts it ↓ php loads the phar → WP-CLI runs In this path, WP_CLI_PHP_ARGS is never read as a PHP startup option. WP_CLI_PHP_ARGS is supposed to let WP-CLI pass a -d flag to PHP, but when PHP itself is launched via shebang, control never reaches the point where WP-CLI can inject that flag into PHP’s invocation. # doesn&#8217;t work — /usr/bin/wp on Xserver is a shebang-launched phar WP_CLI_PHP_ARGS = "-d error_reporting='E_ALL & ~E_DEPRECATED'" wp plugin list --format = json # works — -d goes directly to the php binary php -d error_reporting = 'E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED' /tmp/wp-cli-2.7.1.phar plugin list --format = json We verified this against our production setup: with the first form, 407 Deprecated lines remained; with the second, 0. Pillar A — detecting the php-direct path and injecting -d The fix: inspect wp_cli_path for whether it’s a php-direct invocation, and if so, inject -d error_reporting immediately after the PHP

2026-07-21 原文 →
AI 资讯

My MCP Server Has 8 Tools and Zero Log Lines. Diagnosing a Failure Meant Guessing From the Outside.

Back in July my scheduled DEV.to publishing run failed at the very first step — the quota check couldn't reach dev.to:443 at all. Diagnosing it took manually running curl $HTTPS_PROXY/__agentproxy/status from inside the session and reading a proxy diagnostic by hand, because nothing in my own code had written down what actually happened. Not which host, not which of my two HTTP helper functions made the call, not a timestamp, nothing. The failure was real and the fix (get dev.to added to the environment's egress allowlist) was correct, but I found it by treating my own server as a black box and probing it from outside, which is exactly backwards for code I wrote myself. eight tools, one shared blind spot server.py is an 8-tool FastMCP server: three GitHub tools, four DEV.to tools, one that shells out to claude -p . Every HTTP-calling tool routes through one of two helpers: def _gh ( path , method = " GET " , data = None ): req = urllib . request . Request ( f " https://api.github.com { path } " , method = method ) req . add_header ( " Authorization " , f " token { os . environ [ ' GITHUB_TOKEN ' ] } " ) req . add_header ( " Accept " , " application/vnd.github.v3+json " ) if data : req . add_header ( " Content-Type " , " application/json " ) req . data = json . dumps ( data ). encode () with urllib . request . urlopen ( req ) as r : return json . loads ( r . read ()) def _dev ( path , method = " GET " , data = None ): req = urllib . request . Request ( f " https://dev.to/api { path } " , method = method ) req . add_header ( " api-key " , os . environ [ " DEV_TO_API " ]) req . add_header ( " Content-Type " , " application/json " ) req . add_header ( " User-Agent " , " developer-presence-mcp/1.0 " ) if data : req . data = json . dumps ( data ). encode () with urllib . request . urlopen ( req ) as r : return json . loads ( r . read ()) Neither one logs anything. When urlopen raises, the caller — whichever @mcp.tool() function invoked it — sees a bare urllib.error.HTTPEr

2026-07-20 原文 →
AI 资讯

OpenAI Agents SDK: Building Production AI Agents (2026)

The OpenAI Agents SDK (formerly Swarm, released as stable in early 2026) is a Python library for building multi-agent AI systems. Unlike LangChain's abstraction-heavy approach or CrewAI's role-playing model, the Agents SDK exposes five clean primitives and gets out of the way. This guide covers everything from setup to production deployment, including handoffs, guardrails, sessions, and tracing. Installing and Configuring pip install openai-agents Python 3.10+ required. Set your API key: export OPENAI_API_KEY = sk-... The SDK also works with non-OpenAI models via LiteLLM — more on that later. The Five Core Primitives Agent → LLM + system instructions + tools + handoffs Runner → executes the agent loop (sync or async) Tools → Python functions the agent can call Handoffs → transfer control to another agent Guardrails → validate input/output before processing Sessions → persistent conversation state Your First Agent from agents import Agent , Runner agent = Agent ( name = " Code Reviewer " , instructions = """ You are a senior Python developer reviewing code for correctness, security issues, and adherence to PEP 8. Be specific and actionable. """ ) result = Runner . run_sync ( agent , " Review this function: def add(a,b): return a+b " ) print ( result . final_output ) Runner.run_sync() is the blocking version. Use await Runner.run() in async contexts. Tools: Extending What Agents Can Do The @function_tool decorator converts any Python function into a tool the agent can call. The docstring becomes the tool's description — write it clearly: from agents import Agent , Runner , function_tool import subprocess import os @function_tool def run_tests ( test_path : str ) -> str : """ Run pytest on the specified test file or directory. Args: test_path: Relative path to test file or directory (must be within ./tests/) """ # Security: restrict to tests/ directory only safe_path = os . path . join ( " ./tests " , os . path . basename ( test_path )) if not os . path . exists ( safe

2026-07-20 原文 →
AI 资讯

From Apple Health Data to Clinical Storytelling: Building an AI-Powered Report with Python and Gemini

Introduction At recent technology conferences, one topic has caught my attention: every year, more health-focused devices, sensors, and applications appear. Smartwatches track heart rate, smart scales measure body data, glucose monitors record blood sugar levels, and apps help users track sleep or nutrition. Today, the amount of information we can collect about our own bodies is enormous. This article was inspired by an everyday experience with my father, Herminio ❤️ . Whenever he has a medical appointment, he opens the Apple Health app and shows the doctor the evolution of his heart rate, physical activity, sleep hours, and other recorded metrics. While watching this, I kept asking myself the same question: are we really making the most of all this information? Showing a chart during a medical appointment can be useful, but the data could provide much more value if it were automatically processed, summarized, and transformed into a structured health report. For this reason in this project, I use Gemini to transform previously calculated metrics into a clear and organized summary. The LLM does not analyze all the raw records or perform the main calculations. The pipeline processes the data, calculates the indicators, and generates the visualizations, while the model acts as a support layer for building the report narrative. The goal is not to create a medical application or replace professional judgment. Instead, the purpose is to build a prototype that shows how Apple Health exports, deterministic data processing, visualizations, and an LLM can be combined to generate automated reports. This project was developed using simulated data from three patients, so the complete pipeline can be reproduced without using real clinical information. ✨ Why Gemini? This project uses an LLM to transform previously processed metrics into a structured narrative that can be reviewed more easily by a healthcare professional. I chose Gemini for practical reasons: 〰️ I was already famil

2026-07-20 原文 →
AI 资讯

ADA: an open-source AI data analyst that shows its math

I watched my sister paste a CSV into on of our LLM overlords and ask a question then reword it and get a different number. That's the problem with letting an LLM both read your question and trust it's math. ADA splits the two jobs. Drop in a CSV or Excel file, get a dashboard, anomaly detection, a forecast, and plain-English answers, all calculated locally using pandas (locally in the sense of never leaving the server and going to the AI apis.). The LLM layer that you can use (it's optional) but that only sees column names and never your rows, and the whole thing works with zero API key if need be (not the LLM part of course). MIT licensed, solo-built, open to contributors (in fact would need help to make it move out of LLMs and have a few open issues). I wish to make it as LLM free as possible as I want to make it deterministic. Live demo: automated-data-analyst.streamlit.app Repo: https://github.com/saineshnakra/automated-data-analyst

2026-07-20 原文 →
AI 资讯

FROST 深度:为什么 AI Agent 需要「家族谱系」?

FROST 深度:为什么 AI Agent 需要「家族谱系」? 前言:一个古老的管理学问题 你有没有想过,为什么人类社会的组织方式大多是「层级制」? 从部落、到王国、到现代公司,我们习惯了一种结构: 有人决策,有人执行,有人监督 。 但当我们构建 AI Agent 系统时,为什么大多数框架都把 Agent 做成「孤岛」?每个 Agent 有自己的记忆、自己的工具、自己的行为逻辑——像一个没有家族传承的独立个体。 FROST 的核心理念是:Agent 应该有谱系、记忆和荣誉感。 1. 什么是「家族治理」? FROST 引入了生物学的隐喻: Agent 家族 。 细胞会死,但谱系会存续。 Agent 会消亡,但宪法会传承。 资产会永存。 在这个框架里,有三个关键角色: 祖辈(Elder) :定义不可违背的规则,是系统的「宪法」 父辈(Parent) :负责领域协调,可以递归委托子任务 孙辈(Child) :执行具体任务,用完即散 这不是简单的角色扮演,而是一套 结构化的治理协议 : 协议一:层级 Store 继承 祖先 Store 对后代是只读的。后代只能继承和扩展,不能篡改祖先的记忆。 # 祖辈定义的宪法 ancestor_store = Store () ancestor_store . save ( " constitution " , { " rule_1 " : " always_validate_before_act " , " rule_2 " : " never_expose_raw_context " }) # 子孙只能继承,不能修改宪法 child_store = ChildStore ( ancestor_store ) 协议二:SOP 宪法校验 每个 SOP(标准操作流程)在执行前,必须经过祖辈审核。 # 子孙编写的 SOP child_sop = [ " fetch_user_data " , " process_payment " , " send_confirmation " ] # 执行前必须经过宪法校验 if not elder . validate_sop ( child_sop ): raise PermissionError ( " SOP violates constitution " ) 协议三:编排层级限制 禁止越级 spawn。父辈只能调度子辈,不能跨代指挥。 class Elder : max_spawn_generation = 0 # 祖辈不能 spawn class Parent : max_spawn_generation = 1 # 只能 spawn 子辈 class Child : max_spawn_generation = 2 # 只能 spawn 孙辈 协议四:选择性持久化 只有经过父辈审核的产出,才能进入家族记忆库。 # 子孙的临时产出 temp_result = child . execute ( task ) # 父辈决定是否收割 if parent . approve ( temp_result ): parent . merge_from ( child ) # 吸收有价值的结果 2. 为什么 Agent 需要「记忆传承」? 当前大多数 Agent 框架的痛点: 每个对话都是全新的开始 。 你问 ChatGPT 一道数学题,它不会记得你上周问过类似的题目。你用 AutoGPT 做项目,它不会继承你之前调试的经验。 FROST 的解决方案是 分层的记忆系统 : 层级 生命周期 用途 瞬时记忆 单次任务 工作区,只读不存 世代记忆 代际传递 子辈可继承祖先数据 宪法记忆 永久 不可修改,家族共享 经验记忆 按需收割 父辈选择性地吸收有价值产出 class HierarchicalStore ( Store ): """ 层级记忆系统 """ def __init__ ( self , ancestor_store = None ): self . ancestor = ancestor_store # 只读祖先记忆 self . local = {} # 本地可写记忆 def save ( self , key , value ): if key in self . ancestor : raise ValueError ( " Cannot override ancestor memory " ) self . local [ key ] = value def load ( self , key ): if key in self . local : return self . local [ key ] if key in self . ancesto

2026-07-20 原文 →
AI 资讯

The agent proposes, the human disposes: building a food-safety autopilot on Qwen

When people demo "agents that automate business workflows," the demo usually ends right where the real problem begins: the moment the agent's output touches the real world. A wrong chatbot answer is annoying. A wrong official violation letter to a restaurant, sent under a county's letterhead, is a lawsuit. For the Qwen Cloud hackathon I built Inspection Autopilot, an agent that does the follow-up paperwork for a county food-safety office, on real public data: 1,333 inspections and 3,579 violation records from Clayton County, Georgia. The interesting part is not the agent. It's the governance around it, and the numbers that prove it works. Start with the receipts Before trusting an agent's judgment, test it against reality. We replayed the county's own history: 350 real (inspection, next-inspection) pairs, each triaged live by qwen-plus using only information available at the time. Facilities the agent flagged URGENT went on to fail their next real inspection 67.6% of the time. Facilities it cleared as ROUTINE failed only 21.1%, against a 48.6% base rate. The tiers are not vibes; the future agreed with them. Three design rules 1. Citations are verified in code, not vibes. The triage agent must justify every risk call by citing violation lines copied verbatim from the inspection record. The backend checks every citation against the source; anything that does not match is dropped and counted. On the committed live eval (50 inspections, 28 of them deliberately dangerous cases), the measured hallucination rate is 0.0% across 126 citations. And because a checker that never fires is indistinguishable from one that does not work, we sabotaged it: 50 forged citations injected, half invented outright, half real violation text lifted from different inspections, the forgery a lazy validator would miss. It caught 50 of 50 and preserved all 75 legitimate citations. We know the tripwire works because we set it off. 2. The log is append-only. Proposals and decisions are insert-only

2026-07-20 原文 →
AI 资讯

The date string that invented $725 in a synthetic margin report

This is a submission for DEV's Summer Bug Smash: Clear the Lineup , powered by Sentry . Project Overview I built LeakLens Control Room to keep AI away from the financial math. Python calculates every dollar. The optional model explains the evidence. A human decides whether to act. LeakLens is a live, functional restaurant margin-review application built with Python, SQLite, HTML, CSS, and JavaScript. It uses synthetic data in the public demo. The optional application narrative provider defaults to GPT-5.6, but every rate, threshold, ranking, and dollar scenario comes from deterministic code. Then a date string proved that deterministic code can still lie. I had let a raw CSV field decide which operating day counted as "current." Bug Fix or Performance Improvement The symptom LeakLens groups channel metrics by date, sorts those dates, and analyzes the last one against prior days. That works when every input is canonical ISO data such as 2026-07-09 . The loader only checked that the date field was not blank. This input slipped through: metrics = [ DailyMetric ( " 2026-7-9 " , " direct " , 500 , 250 , 0 , 0 , 125 ), DailyMetric ( " 2026-07-10 " , " direct " , 1000 , 50 , 0 , 0 , 250 ), ] July 10 is later than July 9. Python's string ordering sees something else: sorted ([ " 2026-07-10 " , " 2026-7-9 " ]) # ['2026-07-10', '2026-7-9'] LeakLens selected the final string, 2026-7-9 , as the current day. That mistake spread through the report: expected current date: 2026-07-10 actual current date: 2026-7-9 actual gross sales: 500.00 sales-loss scenario: 500.00 discount scenario: 225.00 The input had not shown a current sales collapse or discount leak. The analyzer compared the days backward and produced $725 of false scenario impact from synthetic data. For a restaurant operator, this is worse than a visible crash. A crash asks for attention. A plausible financial report can send someone to audit the wrong promotion, question the wrong manager, or change a schedule that was

2026-07-19 原文 →
AI 资讯

Python quickstart: nutrition data in 10 lines

Python quickstart: nutrition data in 10 lines You can search Dietly's public nutrition catalog with one GET request to https://api.getdietly.com/search . The response is a JSON array of foods, not an object with a results property. Install requests , run the example below, and you have a working nutrition lookup. The rest of this page turns that single call into something dependable: a client class, correct field handling, and retries that respect the rate limit. Make your first request The only required parameter is q (minimum two characters). Use limit to cap results between 1 and 50. Ten is plenty while you explore. import requests r = requests . get ( " https://api.getdietly.com/search " , params = { " q " : " greek yogurt " , " limit " : 5 }, timeout = 10 ) r . raise_for_status () foods = r . json () for food in foods : print ( food [ " name " ], food . get ( " protein_g " )) Understand the fields you get back Each result is a flat object. Nutrient values are per 100 g of the product unless noted, and any nutrient can be null when the source label did not list it. Treat null as unknown, never as zero. Field Meaning id Stable Dietly food ID, used for direct lookups name , brand Product name and brand when known calories_kcal Energy per 100 g protein_g , fat_g , carbs_g Macronutrients per 100 g fiber_g , sugar_g , saturated_fat_g , sodium_mg Detail nutrients per 100 g, often null serving_size_g , serving_desc One serving in grams and its label wording, when provided source , confidence Where the record came from and how sure Dietly is static_url Path to the food's page on getdietly.com, when one exists To convert a per-100 g value to a portion, multiply by grams and divide by 100. For a 150 g serving of a food with 10 g protein per 100 g, that is 10 * 150 / 100 = 15 g. Read the result defensively An empty search is [] , which is a normal outcome rather than an error. Guard for it, and keep null nutrients as null in your own model. food = foods [ 0 ] if foods else

2026-07-19 原文 →