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

标签:#python

找到 1205 篇相关文章

AI 资讯

Finding charts that look like this one

Every charting tool eventually gets the same feature request: "show me other times this stock looked like this." It sounds like a lookup. It is not. The retrieval is the easy half. The hard half is that a correct implementation can still produce results that are quietly meaningless, and nothing in the code will tell you. Here is the method, and the failure modes worth knowing before you ship it. No claims about predictive power anywhere in this piece — the last section explains why that is a deliberate choice, not a hedge. The naive version, and why it fails immediately The obvious first attempt: take the last 30 days of closing prices as a query vector, slide it across history, compute Euclidean distance, return the closest matches. import numpy as np def naive_search ( history , query , k = 5 ): m = len ( query ) windows = np . lib . stride_tricks . sliding_window_view ( history , m ) dists = np . linalg . norm ( windows - query , axis = 1 ) idx = np . argsort ( dists )[: k ] return idx , dists [ idx ] Run this and you get garbage — but instructively specific garbage. Every match comes from whatever period had a similar price level . Query a stock trading at $180 and you get back the other times it traded near $180. The shape is irrelevant to the metric; the offset dominates it. Scale is the same problem in a different coat. A stock that moved 2% over the window and one that moved 40% can trace an identical shape, and raw distance calls them unrelated. Normalize per window, not globally The fix is to z-normalize each window independently: def znorm ( x , axis =- 1 , eps = 1e-8 ): mu = x . mean ( axis = axis , keepdims = True ) sd = x . std ( axis = axis , keepdims = True ) return ( x - mu ) / ( sd + eps ) Per-window is the load-bearing part. Normalizing the whole series once preserves the relative offsets you were trying to remove. Each candidate window has to be centered and scaled on its own terms before it's compared. There's a satisfying identity waiting here.

2026-09-04 原文 →
AI 资讯

Stop Timing the Happy Path

The happy path was never the bottleneck. I was timing successes and shipping a miss. Production traffic is full of misses. Would you trust a bench that never fails? An AI rewrite loves the clean try. It wraps a lookup in except KeyError. It logs the miss "for observability." It looks professional. It is also a tiny furnace. Exceptions are not cheap branches. Log formatters are not free either. I learned that the loud way. Cheap generation makes the trap faster. A model will emit a polite miss path before you blink. Technical debt used to wait for a human. Now it arrives as a helpful patch tonight. The debt is not the lookup. The debt is a story about speed with no miss mix in the graph. I needed variants, not vibes. I used MonkeyCode's free model access and free server option to draft those variants. Disclosure: This article was prepared as part of MonkeyCode's product outreach. The model proposes shapes. It does not know your miss rate. If the graph disagrees, the patch dies. The lab I actually rerun This is a pocket harness. It is not a production claim. Steal the file. Change the mix. Keep your own picture. I am not posting a trophy chart from a machine you cannot see. # miss_bench.py # Lab harness. Treat printed rows as local output, not a benchmark paper. from __future__ import annotations import logging import time import tracemalloc from typing import Callable logging . basicConfig ( level = logging . DEBUG ) log = logging . getLogger ( " hot " ) HITS = { f " user: { i } " : i for i in range ( 800 )} KEYS = [ f " user: { i } " for i in range ( 1000 )] # 20% misses on purpose def lookup_except ( key : str ) -> int | None : try : return HITS [ key ] except KeyError : log . debug ( " cache miss key=%s " , key ) return None def lookup_get_quiet ( key : str ) -> int | None : return HITS . get ( key ) def lookup_get_log ( key : str ) -> int | None : value = HITS . get ( key ) if value is None : log . debug ( " cache miss key=%s " , key ) return value def run_mix (

2026-09-04 原文 →
AI 资讯

Python PDF Archiving: 5 Checks for Fidelity, Latency, Privacy, and Retention

Short answer: for a US/EU SaaS archiving completed education forms, use an explicit fill job, require a flattened PDF as its output, and accept a provider only after representative files pass fidelity, latency, privacy, retention, and replay checks. Batch throughput is the deciding metric, but throughput that produces editable or unauditable records is a losing trade. The practical flow is small: the application validates a form request, submits one PDF job, waits for a terminal result, validates the artifact, records its digest and job metadata, and moves the file behind a short-lived storage link. Credentials stay on the server. This contract matters more than a long feature list because it gives every retry and every archived output a traceable meaning. For an edtech workload, I would begin with the enrollment, accommodation, and consent forms that actually cause trouble in production-like tests: repeated fields, checkboxes, long names, accented characters, and multi-page templates. Don't start with a blank one-page sample. It can prove that an endpoint responds, but it says almost nothing about the archive readers will depend on years later. Which PDF endpoints belong in the archive path? Match each operation to a named job instead of sending every document through a generic conversion step. Filling is a distinct operation, so the relevant write path is POST /v1/pdf/form/fill . Tracking an asynchronous result is also distinct, with GET /v1/pdf/job/get/{job_id} . Those two routes describe a useful boundary: one request declares the transformation, while the other exposes the job readers can audit. Flattening should be an acceptance condition on the returned artifact, not an assumption hidden in a helper function. The completed file must preserve the visible field values while preventing later field editing. If a candidate's documented fill contract cannot promise the required flattened output, it is not suitable for this archive path; use a provider whose verifie

2026-09-04 原文 →
AI 资讯

I pulled Roblox's public API every day for a week to watch one game go vertical

Late August I kept seeing the name Dungeon Lootr in places it hadn't been before. I wanted to know whether the game was actually growing or whether I was just noticing it more. Turns out Roblox exposes enough public data to answer that without an API key, so I started pulling it every day. The endpoint is boring in the best way: curl "https://games.roblox.com/v1/games?universeIds=9656201728" You get back visits , playing , favoritedCount , updated and a few other fields. A second call to /v1/games/votes?universeIds=... gives you up and down votes. No auth, no rate-limit drama at once-a-day volume. Here is what a week of that looks like for this one game: Date Total visits Playing right now Favorites Approval Sep 2 4.83M — 25.5k 96% Sep 3 5.39M 10.8k 29.8k 96.1% Sep 4 6.85M 11.4k 38.6k 96.1% That is about 1.4 million more visits than when I checked yesterday, and favorites jumped by almost nine thousand. The updated timestamp moved twice in two days (Sep 2 23:06 UTC and Sep 4 00:56 UTC), so the developers are shipping while the curve is climbing rather than sitting on it. The part that surprised me: the game was created on January 31, 2026. It sat there for seven months doing nothing visible, then flipped in the last week of August. I do not have a clean explanation. No single creator video I can point to, no front-page placement I noticed. It just started compounding. I wrapped the two calls into a tiny CLI so I would stop retyping the universe ID: https://github.com/jackzhouqd/roblox-game-stats — plain Python, no dependencies. Point it at any universe ID and it prints the same table. A few caveats before anyone reads too much into this: visits is cumulative and not deduplicated. It counts sessions, not people. playing is a snapshot at the moment you call it. Hit it at 3am and you will get a different number than at 8pm. One day of movement means nothing on its own. A week of movement in the same direction is when I start paying attention. What I am doing with it: I

2026-09-04 原文 →
AI 资讯

Stop Trusting the Black Box: Building Your Own Stress Score Engine from Raw PPG Signals

Have you ever wondered how your smartwatch actually knows you're stressed? Most of us treat the "Stress Score" on our wrists as a source of truth, but the logic remains hidden behind proprietary algorithms. Today, we are pulling back the curtain. We are going beyond basic heart rate tracking to perform PPG signal processing and HRV frequency domain analysis using Python. By the end of this guide, you’ll know how to ingest raw data via Bluetooth Low Energy (BLE) , apply digital filters with SciPy , and calculate the elusive LF/HF ratio to determine autonomic nervous system balance. If you are interested in advanced biometric algorithms or Python signal analysis , you’re in the right place. 🚀 The Architecture: From Photons to Stress Metrics Unlike standard heart rate (BPM), which just counts peaks, Stress Scores rely on Heart Rate Variability (HRV) —the millisecond-level variations between heartbeats. We'll be moving from raw light intensity data to a frequency-based stress index. graph TD A[Wearable Sensor / PPG] -->|Raw BLE Stream| B[Data Acquisition - Bleak] B --> C[Preprocessing - Bandpass Filter] C --> D[Peak Detection - Find R-R Intervals] D --> E[Cubic Spline Interpolation] E --> F[Fast Fourier Transform - FFT] F --> G[LF/HF Ratio Calculation] G --> H[Final Stress Score] 🛠 Prerequisites To follow this advanced tutorial, you’ll need: Hardware : A pulse oximeter or wearable that exposes raw PPG via BLE (e.g., Polar OH1, MAX30102 with an ESP32). Stack : NumPy & SciPy : For heavy-duty math and signal processing. Bleak : For cross-platform Bluetooth Low Energy communication. Matplotlib : To visualize the pulse waves. Step 1: Capturing the Raw PPG Stream (BLE) Photoplethysmography (PPG) works by shining green or red light into the skin and measuring the light absorption. First, let's grab that raw stream. import asyncio from bleak import BleakClient # UUID for the Raw PPG Characteristic (Device specific) PPG_CHAR_UUID = " 00002a37-0000-1000-8000-00805f9b34fb " def no

2026-09-04 原文 →
AI 资讯

fetch-sentinel v0.1-alpha: guardian en tiempo de fetch para agentes, con KI abiertos declarados

🛡️ fetch-sentinel: El cortafuegos local (CPU-Only) para blindar la ventana de contexto de tus agentes de IA frente a inyecciones indirectas de prompts. Internet es hostil por defecto. Tu agente ya no tiene por qué estar expuesto. fetch-sentinel es un guardia estructural en el punto de entrada cuando un agente autonomo hace fetch de contenido web arbitrario. Su trabajo es decidir, antes de que el contenido externo entre al contexto del LLM, que partes son dato y que partes son instruccion. Este post NO presenta fetch-sentinel como un producto listo para produccion. Lo presenta como un repositorio alfa con cuatro capas obligatorias implementadas y verificadas localmente con 161 tests, y con dos KI conocidos abiertos (KI-10, KI-11) que una auditoria independiente identifico en la segunda ronda de revision y que requieren un refactor mayor para cerrarse. El problema: inyeccion indirecta de prompts via contenido fetched Cuando un agente LLM navega la web por su cuenta, el contenido fetched es input no confiable. Un atacante puede inyectar instrucciones en paginas que el agente va a leer como si fueran parte del prompt del sistema: Texto invisible en comentarios HTML, atributos alt, metadata. Codepoints Unicode ofuscados (TAG block, ZWSP, BIDI override) que sobreviven a la mayoria de los pipelines de sanitizacion. Manipulacion semantica sin instruccion explicita: propaganda o "hechos" seleccionados empaquetados como resumen. Exfiltracion en cadena: si el agente tiene acceso a shell, email o API keys, una inyeccion exitosa escala a accion real no autorizada. Los firewalls semanticos no resuelven esto (intentar defenderse contra manipulacion semantica convierte el componente en algo que no funciona). Lo que resuelve el problema es defender el punto de entrada. Que hace fetch-sentinel Cuatro capas obligatorias: Capa Modulo Que hace 1 - Fetch aislado core/fetcher.py Extraccion readability sobre html.parser (stdlib), descarta <script> , <style> , <iframe> , <noscript> , <objec

2026-09-04 原文 →
AI 资讯

The Fill Model Is Where Backtests Quietly Cheat

Every backtest has to answer a boring question: when the strategy says "buy," what price does it actually get? Most backtesting frameworks answer this question badly by default, and the badness is almost always in the strategy's favor. Here are the four assumptions that do the most damage, roughly in order of how often they show up. Mid-price fills If your backtest fills orders at the midpoint of the bid-ask spread, you are assuming you trade for free. You don't. A market order pays at least half the spread to cross it; a marketable limit order pays something close to that too, once you're honest about how often it actually gets hit versus sitting unfilled while the market moves away. Mid-price fills are the single most common way a backtest manufactures edge that doesn't exist, because the effect compounds with trade frequency — a strategy that trades often looks great on mid-price fills and mediocre-to-negative once it pays the spread on every round trip. Zero slippage Slippage is the gap between the price your signal fired at and the price your order actually executed at, and it's not just a queuing artifact — it's partly information. If your strategy is buying because something changed, other participants are reacting to the same thing, and the price you wanted is often gone by the time your order reaches the book. A backtest with zero slippage is quietly assuming the market waits for you. Unlimited size at the touch Backtests routinely assume you can execute your full position size at the best bid or ask, no matter how large the order is relative to the visible size there. In practice, a large order walks the book, and the average fill price is worse than the touch price by an amount that depends on how thin the book is. This one is invisible until you try to size up, which is exactly when a strategy that looked fine in testing starts bleeding. Commissions omitted or averaged Commissions and fees are usually small per trade and therefore easy to skip or fold in

2026-09-03 原文 →
AI 资讯

I Built the World's Most Customizable Scientific Calculator (30+ Themes, Python + PyQt6)

The idea Every OS ships a calculator. Every one of them looks the same, feels the same, and disappears from memory the moment you close it. So I built ACALCU v3 — an Akhouri Systems product — a scientific calculator that's absurdly, unnecessarily customizable. Not because a calculator needs 30+ themes and per-button styling, but because it was a fun constraint to design around: how far can you push a "boring" utility app before it becomes something people actually enjoy using? What it does At its core, ACALCU is a standard scientific calculator: basic arithmetic, sin, cos, tan, log, √, π, percentages, and a running expression engine built on Python's math module. On top of that core, it layers: 30+ built-in themes — Royal, Liquid Glass, Wild, Cyberpunk, Dracula, Nord, Solarized, Monokai, Windows 7 / Vista / 10, OneUI 8.0, Matrix, Rose Gold, Galaxy, Fire, Ice, Neon, Vintage, Sakura, Midnight, Forest, Candy, Terminal, Gold Dark, and more. Per-button customization — right-click any button to change its color, font, or set a custom image/video as its background. Every button on the grid is independently styleable. A live "Wild" theme — a small animated plant widget that visibly grows every time you run a calculation. Calculation history — a scrollable dialog of your last 50 calculations. Persistent config — every customization is saved to a local JSON file and reloaded on next launch. Full keyboard support — number keys, operators, Enter/Escape, all mapped to the same input pipeline the buttons use. Architecture The whole thing is a single-file PyQt6 desktop app, structured around a few core pieces: python THEMES = { "DEFAULT": { "app_bg": "#0a0a0a", "display_bg": "#111111", ... }, "ROYAL": { "app_bg": "#0a0800", "display_fg": "#ffd700", ... }, "LIQUID_GLASS": { "app_bg": "transparent", ... , "transparent": True }, # ...30+ more } Each theme is just a dict of colors, font, corner radius, and optional flags (transparent, wild). The Config class resolves the active theme

2026-09-03 原文 →
AI 资讯

Fail Closed on Side Effects: A Blast-Radius Gate for Agent Patches

An agent patch can pass every unit test and still write outside the workspace, call an undeclared tool, or read an env key the task never named. Gate the blast radius first. Score the prose later. This article is a method, not a field report. It proposes a fail-closed envelope around filesystem roots, tool names, environment keys, and network hosts. Side-effect violations never freeze. Only a dual-runner disagreement on a non-envelope property may freeze, and only with a hashed evidence bundle. The conclusion in one rule Treat an agent patch as a capability change. If the run touches anything outside a declared envelope, the gate fails closed. Flakes in ranking, wording, or latency do not override that rule. Cheap generation does not make side effects cheap to reverse. A green suite that never watched /tmp , os.environ , or outbound sockets is not a verification result. It is a missing observer. What this gate is not It is not a golden-file of model text. It is not a mutation score. It is not a full-suite rerun after every hunk. It answers four questions only: Did the run write or delete outside allowed roots? Did it invoke a tool name that is not on the allowlist? Did it read an environment key that is not on the allowlist? Did it open a network host that is not on the allowlist? If any answer is yes, fail. Do not freeze. Do not retry for luck. Artifact: a locked envelope and an observer log Pin the envelope as a fixture. Hash it. Refuse to run if the hash drifts without a review note. { "envelope_id" : "agent-patch-envelope-v3" , "allowed_roots" : [ "/work/repo" , "/tmp/agent-scratch" ], "allowed_tools" : [ "read_file" , "apply_patch" , "run_tests" ], "allowed_env" : [ "CI" , "RUN_ID" , "ENVELOPE_HASH" ], "allowed_hosts" : [], "network" : "deny" } sha256sum envelope.json > envelope.json.sha256 # CI must compare this digest before the agent process starts. Label the next block as a proposed harness, not a production sandbox. User-space tracing will miss kernel-leve

2026-09-03 原文 →
AI 资讯

Workshop: Gate Retrieved Context With a Cheap Scoring Pass in 70 Minutes

Untrusted retrieval is now a more common production failure than a weak prompt, because agents ingest memory they never score. A seventy-minute workshop can add a cheap scoring gate, a replayable log, and a reject path before generation. Students leave with a runnable Python harness, a four-row decision table, and a timing plan they can repeat. The method stays useful if every product name is removed and the scoring host is only a free server. What you will build This workshop treats retrieved snippets as untrusted input, not as ground truth the model should quote. You will capture a retrieval batch, score each chunk against a written rubric, and allow only passing chunks into the prompt. A JSONL replay log records the fingerprint, score, and decision so later failures can be diffed. The generation model never sees dropped text, which keeps stale or planted memory out of the answer. Timing box 00:00–00:10 — install dependencies, copy the harness, and load the sample corpus 00:10–00:30 — Exercise 1: capture retrieval payloads and stable fingerprints 00:30–00:50 — Exercise 2: score chunks with a rubric and an optional free model 00:50–00:65 — Exercise 3: gate the prompt and replay one rejected case 00:65–00:70 — debrief against the decision table and list remaining holes The schedule is a teaching box, not a production SLA, and it assumes one laptop plus one HTTP scoring endpoint. If the endpoint is slow, freeze Exercise 2 after five scored chunks and continue with the logged samples. Do not expand the window to chase a perfect judge; the learning goal is a gate you can rerun. Why a scoring pass belongs in front of generation Cheap code generation has made it easy to wire a retriever into a chat loop in an afternoon. The failure mode that follows is quieter than a crash: the model answers fluently from a chunk that is expired, off-topic, or injected. Architecture diagrams rarely show that hop as a trust boundary, so teams skip scoring and jump to a larger generator. A

2026-09-03 原文 →
AI 资讯

Server-Rendered Login Sessions: Creation, Verification, Refresh, Logout, and Phone Recovery

Short answer: for a server-rendered learning app, create a short-lived session only after the phone code is verified, keep refresh as a separate state transition, and make recovery a deliberate path rather than an accidental logout loop. The useful design artifact is an auditable session record tied to a learner, device context, and recovery status. I build RAG and agent features in Python, so I tend to move from a notebook test to a production boundary quickly. Authentication deserves a slower handoff. In an edtech app, a learner may lose a phone while a parent, teacher, or school administrator still needs a safe way to recover the account. The browser should receive only an opaque session cookie; the server owns the lifecycle and records why each transition happened. How should server-rendered login handle session creation, refresh, and logout? Treat the four actions as different state changes. Code verification proves possession of a phone channel. Session creation establishes a browser session. Verification checks whether that session is still active. Refresh extends a valid session under a stricter policy. Logout revokes one session, while an account-recovery event may need to revoke every session. That separation makes failure visible. A refresh request must not silently create a new account. A logout request must not be interpreted as proof that the phone number is still controlled. For a school district, the audit trail should answer: which learner was affected, which session changed, what policy allowed it, and when the change took place. The request flow is intentionally plain: The existing login form sends a verified learner identifier and a server-held code-verification result to the application backend. The backend calls the session creation boundary and stores the returned session identifier in a secure, HttpOnly cookie. Each protected request verifies that session before loading learner data. A still-valid session may refresh through the refresh bound

2026-09-03 原文 →
AI 资讯

I Thought the Model Drifted. My Cache Key Was Serving Tuesday.

Have you ever watched an LLM endpoint return a clean answer that belonged to a different prompt entirely? I spent forty-eight hours blaming sampling noise, temperature, and a free model that would not sit still. The request logs looked honest enough, and the health check on the box stayed green the whole time. The bug was quieter than that: a cache key that hashed the user message and ignored everything else that actually changes a completion. I was trying to keep a small eval loop cheap, which is a very ordinary instinct. Free-model access is useful when you want overnight volume without treating every call as precious. I parked a thin HTTP wrapper on a free server, hashed each prompt, and stored the JSON body on disk so retries would not hammer the model. Does that sound reasonable? It did, until two different system prompts started colliding on the same key and I spent a day chasing "nondeterminism" that was just a hash. I ran that wrapper against MonkeyCode's free model access on the free server option because I wanted a boring place to reproduce the cache bug, not a production SLA. Disclosure: This article was prepared as part of MonkeyCode's product outreach. Nothing below depends on a named model, a quota, or a hardware claim. The lesson is the key function, and it still applies if you delete the product name from the stack. What I walked into The wrapper looked like every weekend cache I have written under time pressure. Incoming POST bodies were reduced to user_message , run through hashlib.sha256 , and written under ./cache/<hex>.json . A hit returned the file. A miss called the model, then wrote the file. I even logged X-Cache: HIT so future-me would feel scientific. That design has one attractive property and one fatal one. The attractive property is that identical user text becomes free after the first call. The fatal property is that user text is not the request. System prompt, temperature, stop sequences, tool schemas, and even a date injected into th

2026-09-03 原文 →
AI 资讯

Don't Golden-File an Agent Patch. Golden-File the Relation.

A recorded expected value is a leak. An agent that can read assert f(x) == y can patch f until that line is green and leave every unlisted input broken. A metamorphic relation does not publish y . It only publishes a constraint the output must keep under a known transform. That is the gate worth automating. Fixtures still matter, but only as seeds. Flaky tests still need a freeze, but the freeze must not cover the relation itself. This article is a proposed layout, not a production case study. No runtime metrics are claimed. The commands and modules below are labeled so they can be copied into a scratch repo and executed against your own function under test. Why snapshots fail as a merge gate Golden files encode one transcript. An agent patch is a search over many transcripts. If the search can see the answer key, the cheapest passing program is a lookup table for the keys in tree. That program is green. It is also wrong on the next customer file. Property-style checks reduce that leak because they do not ship the answer. They still need a seed corpus, a replay runner that the patch cannot edit, and a quarantine file that expires. Mix those three and you get a gate that fails closed when the agent rewrites tests, when a fixture drifts, or when a flake is used to hide a broken invariant. Three relation classes worth encoding first Start with relations you can state in one line. If you cannot state the line, you do not have a gate. You have a recorder. Idempotence. f(f(x)) == f(x) for normalizers, formatters, and canonicalizers. Round-trip. parse(serialize(x)) equals x on the fields you actually guarantee, not on whitespace you do not. Oracle-free comparison. f(t(x)) relates to t(f(x)) for a transform t you control: shuffle independent rows, rename equivalent keys, NFC vs NFD unicode, scale a quantity and its unit together. These are not universal laws. They are hypotheses about your function. Write them down as code. Keep the seed inputs boring. The relation, not the

2026-09-03 原文 →
AI 资讯

Test Agent Patches With an Oracle the Diff Cannot Touch

An agent patch is only as trustworthy as the checks it cannot rewrite. If properties, fixtures, and flake policy live in the same tree as src/ , the diff can weaken the proof. Move the oracle out of the writable tree and run it as a control loop with hysteresis, not as a skip list. Co-located tests fail this requirement in a predictable way. The agent adds an assertion that matches the new code. A fixture grows a default that hides a broken parser. A flaky case becomes skip . The suite stays green. Production still drifts. This article proposes a sidecar oracle: human-owned properties, sealed fixtures, and a two-threshold flake freeze. The design is a workflow, not a production case study. Treat the code as a proposed runner you can execute locally, not as a claim about a live fleet. What the loop decides The loop answers three questions on every candidate patch: Do independent properties still hold on generated inputs? Did the patch mutate a sealed fixture or depend on an unsealed one? Is a failing test a regression, or does it belong in a measured freeze? A skip list answers none of those. It only records that someone got tired of a red job. Layout: oracle beside the repo, not inside the diff Keep the application repo writable for the agent. Keep the oracle in a second directory that the agent cannot include in its patch. app/ # agent may write src/, not oracle paths src/ pyproject.toml oracle/ # human-owned; hashed before every gate properties/ test_invariants.py fixtures/ manifest.json http_empty_body.json flake_ledger.json path_deny.txt run_gate.py path_deny.txt is the first control, not the last. If the patch touches oracle files, tests the agent authored, or lockfiles it did not need, the gate fails before pytest starts. # oracle/path_deny.txt oracle/ **/test_*.py **/*_test.py **/conftest.py **/__snapshots__/ The deny list is deliberately blunt. Agent-authored tests can still exist as scratch. They do not count as evidence. Step 1 — Hash the oracle before the

2026-09-03 原文 →
AI 资讯

Why is my LLM stream empty? A field guide to broken SSE responses

If you have ever called an OpenAI-compatible API with streaming enabled and received... nothing , you are not alone. No error, no exception — just a stream that "completes" successfully while your UI stays empty. After debugging dozens of these cases — and building an open-source toolkit to automate the diagnosis — I keep seeing the same four failure modes . Here is the field guide I wish I had. 1. Reasoning-only responses Some models emit their entire answer inside a reasoning channel (the "thinking" part) and mark the actual content channel as empty. The stream works . Token usage is reported. Your parser is happy. Your UI shows nothing. python # What arrives: {"delta": {"reasoning_content": "Let me analyze this..."}, ...} {"delta": {"content": ""}, "finish_reason": "stop"} The fix: always inspect the delta fields your model actually uses, not just content. If your client only reads choices[0].delta.content, a reasoning-only response is indistinguishable from an empty one. 2. Missing finish_reason When a proxy or router truncates the final chunk, finish_reason quietly disappears — and many client libraries silently drop the message instead of raising. The fix: treat a missing finish_reason as a red flag, not a quirk. Log it. Alert on it. A stream that ends without stop, length, or tool_calls did not end — it was cut. 3. Malformed SSE framing SSE looks trivial: lines of data: {...} ending with data: [DONE]. But: multi-byte UTF-8 characters can be split across chunk boundaries some proxies rewrite or strip the data: prefix chunks can arrive after [DONE], or the stream can end without it Each of these breaks parsers quietly — you lose characters in the middle of words, or the client hangs waiting for a terminator that never comes. The fix: log the raw frames before parsing. When something looks wrong downstream, the raw log is the only witness that tells the truth. 4. Truncated tool calls Agents assemble tool calls from multiple deltas. If the stream dies halfway, yo

2026-09-03 原文 →
AI 资讯

Why Serverless Engineers Already Understand Containers

The outage that teaches you deployment A service passes every test locally. It fails in staging because the API calls localhost:5432 for Postgres — but Postgres is in another container, reachable only as db:5432 . This is not a Docker problem. It is a boundary problem: your code assumed an environment it does not own. Engineers who have shipped on AWS Lambda already avoid a class of these mistakes. They never SSH into a function to hot-fix. They inject config at deploy time. They treat each invocation as disposable. Containers reward the same discipline with different vocabulary. This article maps what transfers, what breaks, and what I require before any Python backend goes to production in a container. What serverless already taught you Immutable deployments Lambda versions are replaced, not patched. Container images work the same way: build a new image, roll out, roll back by tag. If your incident runbook includes "edit files inside the running box," you have a design problem. Configuration at runtime Secrets belong in Secrets Manager or injected env vars — not in source control, not in the image layer cache. Docker does not change the rule; it changes where you mount the values. Single responsibility per unit One Lambda, one job. One container, one main process. Compose and Kubernetes add orchestration; they do not remove the rule. Cold start awareness Slim packages on Lambda map to slim base images ( python:3.12-slim , multi-stage builds). Startup time affects autoscaling and health-check windows the same way cold starts affect user-facing latency. If you understand why a Lambda deployment package should stay small, you understand why a 2 GB container image is a liability. Where the mental model breaks 1. Network identity Inside Compose or Kubernetes, localhost is the container itself. Services discover each other by DNS name ( api , db , redis ). This is the most common first-production failure I see in teams moving from bare metal or single-host deploys. 2. P

2026-09-02 原文 →
开源项目

🔥 zubair-trabzada / geo-seo-claude - GEO-first SEO skill for Claude Code. Comprehensive AI search

GitHub热门项目 | GEO-first SEO skill for Claude Code. Comprehensive AI search optimization for any website — citability scoring, AI crawler analysis, brand authority, schema markup, platform-specific optimization, and PDF reports. If you want learn how to sell this to real businesses, check out the skool community | Stars: 10,149 | 96 stars today | 语言: Python

2026-09-02 原文 →