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

标签:#Python

找到 614 篇相关文章

AI 资讯

🐍 Day 1/100 — Starting my Python journey!

Hey everyone! 👋 I'm a complete beginner and today I'm officially kicking off my #100DaysOfCode challenge with Python. I've dabbled with the idea of learning to code for a while, but this time I want to actually commit - so I'm posting daily updates here to keep myself accountable and track my progress over the next 100 days. My plan: Post a short update here every day - what I learned, what I struggled with, and what's next Eventually move into some small real-world projects once I've got the basics down Why I'm doing this: I want to build real skills, not just "watch tutorials and forget everything." Writing it down publicly (even anonymously) keeps me honest and hopefully connects me with others on the same path. If you're also learning Python or doing a 100 days challenge, I'd love any tips, resources, or just to follow along with each other's progress! Day 1 status: Just setting up my environment and going through the basics — nothing exciting yet, but everyone starts somewhere! 100DaysOfCode #Python #Beginner #LearnToCode

2026-07-07 原文 →
AI 资讯

Residential Proxies for Developers: Picking the Right IP Strategy (2026 Comparison)

If you've ever built a scraper that worked perfectly in dev and then got blocked or CAPTCHA'd the moment it hit production traffic volume, you already know why proxy choice matters. This post breaks down residential proxies from a practical, implementation-focused angle: what they are, when to use them vs. alternatives, how to wire them into common tools, and how the major providers stack up. TL;DR Residential proxies route requests through real ISP-assigned IPs, so they're harder for anti-bot systems to fingerprint than datacenter IPs. Rotating residential proxies are for scraping/data collection. Sticky sessions (or static ISP proxies) are for anything stateful — logins, checkout flows, long-lived account sessions. Nstproxy is a good default pick if you want residential, static ISP, and mobile proxies under one API/dashboard instead of juggling multiple vendors for different parts of your stack. For large-scale enterprise scraping, Oxylabs and Bright Data have the most mature tooling. For budget/prototype work, IPRoyal, DataImpulse, and Webshare are worth testing. Proxy types, quickly Type Use for Pros Watch out for Residential Scraping, SERP checks, ad verification Looks like real user traffic Usually billed per GB Static ISP Long-lived sessions, account workflows Fast + stable IP Less useful for high-volume rotation Datacenter Speed-sensitive, low-stakes tasks Cheap, fast Easiest to fingerprint/block Mobile Mobile-first platforms/apps Strongest trust signal Most expensive per GB A production-grade scraping/automation stack often uses more than one of these at once — e.g., rotating residential IPs for crawling, and static IPs pinned to specific browser profiles for anything that requires a login. Wiring a residential proxy into your code Most providers give you a host:port endpoint plus username:password auth, and let you control rotation/session stickiness through the username string. A typical setup looks like this: Python ( requests ): import requests proxy_ho

2026-07-07 原文 →
AI 资讯

How to criar Dockerfiles eficientes com multi stage builds

Multi stage builds sao uma das melhores features do Docker para manter imagens pequenas e organizadas. Vou mostrar como aplicar isso em um projeto Python real. Crie um arquivo app.py simples: # app.py def main(): print("Hello from a multi stage build") if __name__ == "__main__": main() Agora crie o Dockerfile sem multi stage: FROM python:3.12-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD ["python", "app.py"] Essa imagem inclui o pip, o cache do pip e ferramentas de build que nao precisamos em producao. O resultado e uma imagem maior que o necessario. Com multi stage builds separamos o ambiente de build do ambiente final. Veja o mesmo Dockerfile com dois stages: FROM python:3.12-slim AS builder WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt FROM python:3.12-slim WORKDIR /app COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages COPY . . CMD ["python", "app.py"] O primeiro stage instala as dependencias. O segundo stage copia so o que importa. O resultado e uma imagem final muito menor. Para construir e ver o tamanho: docker build -t minha-app . docker images | grep minha-app Para linguagens compiladas como Go o ganho e ainda maior. Veja um exemplo com uma aplicacao Go: FROM golang:1.23 AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 GOOS=linux go build -o /app/server FROM scratch COPY --from=builder /app/server /server CMD ["/server"] A imagem final comeca do zero (scratch). Nao tem shell, sistema operacional, nem ferramentas de build. So o binario compilado. Uma dica pratica: sempre nomeie seus stages com AS para facilitar a leitura. Use nomes como builder, test, ou dev. Isso ajuda a saber o que cada stage faz sem precisar contar linhas. That's all for now. Thanks for reading!

2026-07-07 原文 →
AI 资讯

How I Cut My LLM API Bill by 40x: A Freelancer's Migration Story

How I Cut My LLM API Bill by 40x: A Freelancer's Migration Story Last month I almost choked on my coffee when my OpenAI dashboard showed $487.32 for a single client project. That's not profit. That's a panic attack. As a freelancer running a one-person shop, every line item on my monthly expenses gets scrutinized harder than my code reviews. I spent the next weekend stress-testing alternatives, and honestly? I was annoyed at myself for not doing it sooner. The savings are obscene. Let me walk you through exactly what I found, what I migrated to, and how the switch took maybe 20 minutes total. Let me Start With the Damage Here's what I was paying before. OpenAI's GPT-4o runs $2.50 per million input tokens and $10.00 per million output tokens. For one of my retainer clients — a SaaS company whose support chatbot I maintain — I'm pushing roughly 50 million tokens through a month on input and another 15 million on output. Do the math with me: 50M × $2.50 = $125 on input alone. 15M × $10.00 = $150 on output. That's $275/month just for that one client's chatbot. Add my other three active clients and suddenly I'm staring at a $400-500 OpenAI bill every month like clockwork. For a freelancer, that's a third of a client's monthly retainer gone before I even touch my actual engineering hours. Unacceptable. The Alternative Landscape (And Why I Picked What I Picked) I went down the rabbit hole. I tested seven different model providers over a long weekend, ran the same prompts through each, compared output quality, latency, and price. Here's the full breakdown I compiled in a spreadsheet (because yes, freelancers absolutely live in spreadsheets): GPT-4o (OpenAI): $2.50 input / $10.00 output per million tokens. The default. The expensive default. GPT-4o-mini (OpenAI): $0.15 input / $0.60 output per million tokens. Already 16.7× cheaper than its big sibling. DeepSeek V4 Flash (Global API): $0.18 input / $0.25 output per million tokens. Forty times cheaper than GPT-4o. Qwen3-32B (G

2026-07-07 原文 →
AI 资讯

Hardening my own Nmap web UI: the security holes I shipped, and what actually saved me

I built a web front end for an Nmap-based port scanner: a FastAPI backend, a React dashboard, background scan jobs, a plugin system. It worked. Then I sat down and audited it like an attacker would — and found a stack of real weaknesses, plus a lesson in why you verify an exploit before you call it one. This is the honest version: the holes I found, the unauthenticated-RCE chain I thought I had, why it didn't actually fire, and the hardening I shipped anyway. Repo: https://github.com/DipesThapa/PortScanner This is my own project, audited and fixed by me. No third-party systems were touched. Scanners are dual-use — only ever point one at hosts you own or are authorised to test. Hole 1: no authentication, anywhere The foundation: every API route and the /ws/status WebSocket were open. No API key, no session. The Dockerfile bound 0.0.0.0:8000 and ran as root. Anyone who could reach the port could drive scans, hit the upload endpoint, and read every job's logs. api_router = APIRouter () # no dependencies — fully open This is the real, unambiguous problem. Everything below is only interesting because it sat behind no auth. Hole 2: an upload endpoint that allowlisted its own files Deep-dive follow-up commands ran against an allowlist — good instinct. But an upload endpoint wrote a file, chmod +x 'd it, and then added it to that same allowlist: for item in scripts_dir . glob ( " * " ): if item . is_file (): allowed . add ( str ( item . absolute ())) # upload authorises itself An allowlist any input can extend isn't an allowlist. This is a genuine design footgun. Hole 3: the RCE I thought I had — and why it didn't fire Here's the chain I got excited about: the scan target flows toward Nmap's argv, and it's subprocess.run(..., shell=False) . No shell injection — but you don't need a shell to abuse Nmap. If a target became --script=/uploaded.nse , Nmap would load and run that NSE (Lua) script, and NSE can call os.execute . Upload a malicious .nse (Hole 2), get Nmap to load it

2026-07-07 原文 →
AI 资讯

Cómo hablar con tu base de datos usando IA y construir un extractor SQL seguro con Streamlit

Abstract Cada vez más equipos quieren consultar datos sin escribir SQL a mano. El problema es que un sistema Text-to-SQL no solo debe “traducir preguntas”, sino también entender el esquema, restringir permisos, validar consultas y explicar por qué una consulta es rápida o lenta. Ese enfoque coincide con la ruta propuesta por el tutorial oficial de LangChain para agentes SQL: listar tablas, inspeccionar esquemas, generar la consulta, revisarla, ejecutarla y corregir errores hasta obtener una respuesta; y el propio tutorial advierte que ejecutar SQL generado por modelos tiene riesgos y exige permisos mínimos. En paralelo, la documentación oficial de Python recomienda usar placeholders en sqlite3 para enlazar parámetros y evitar inyección SQL, mientras que la documentación de SQLite explica que EXPLAIN QUERY PLAN permite inspeccionar si una consulta hace SCAN, SEARCH y si usa índices. manueldongo23 / sql_ai_sales_assistant_demo SQL AI Sales Assistant A safe Text-to-SQL demo that converts natural language business questions into SQL queries, executes them on a local SQLite retail database, and shows the generated SQL plus EXPLAIN QUERY PLAN . This project was created as evidence for an article about SQL AI Database Solutions . Topic Talk to your database with AI: build a safe SQL query extractor with Streamlit and SQLite. Features Natural language prompts such as sales by month , top customers , sales in Lima . Rule-assisted NL→SQL generation, designed to be transparent and auditable. SQLite demo database with customers, products, orders and order items. Read-only SQL validator that blocks destructive commands. Parameterized queries for user-provided filters. Streamlit interface. CLI demo for quick testing. Query plan inspection with EXPLAIN QUERY PLAN . Architecture User question ↓ NL → SQL interpreter ↓ Read-only SQL validator ↓ SQLite execution ↓ Results + EXPLAIN QUERY … View on GitHub Cuerpo del artículo La promesa de SQL + IA suena sencilla: le haces una pregunta

2026-07-06 原文 →
开发者

I got tired of watching 40 Kalshi tabs, so I built a self-hosted signal monitor

I kept hearing about Kalshi. The commercials, the mentions, and then one morning CNN was talking about Kalshi prediction odds like they were a weather report. So I went and looked. And I had no idea what I was seeing. Kalshi is really hard to understand when you're new to it. You get markets, contracts, prices that are also probabilities, volume, movement, and none of it tells you what's actually worth paying attention to. I wanted something that would translate what I was looking at into something I could understand and, ideally, act on. That was the whole original goal: make the firehose legible. Then, of course, I kept adding to it, because once you can read the flow you start wanting an edge in it. Who doesn't. So Trade Hunter grew from a translation layer into a translation layer with detection on top. This is a writeup of what it became, why I made the design choices I made, and the parts I'm still not sure about. I'd rather you poke holes in it now than find the breakpoints the hard way. If you think a decision here is wrong, please let me know. The comments are the point of this post, not an afterthought. Where this came from Basically, I couldn't read Kalshi, and I wanted to. Trade Hunter is the original tool I built to fix that for myself, and it's the one I still run when I want a live view. So this isn't a polished sequel to anything. It's the thing I built because I wanted it to exist, flaws and design bets included, and I'd rather show you those directly. The core idea never changed even as I piled features on: watch live Kalshi WebSocket feeds and surface an unusual move while it's still moving, rather than reading about it after the fact, or on CNN the next morning. What it actually does Trade Hunter subscribes to live Kalshi feeds across every market you track. Multi-contract series like the Fed rate decisions or who will win Top Chef fan out automatically to all open contracts, so you point it at one thing and it watches the whole family. When some

2026-07-06 原文 →
AI 资讯

How I Cut Our AI API Bill by 95% — The Engineering Playbook

How I Cut Our AI API Bill by 95% — The Engineering Playbook When our finance lead forwarded me the AWS bill for March, I almost choked on my coffee. We were a team of nine engineers shipping AI features, and somehow we'd burned through enough on inference to cover two salaries. The worst part? I hadn't even noticed because the charges were scattered across OpenAI, Anthropic, and a couple of side experiments. That's the moment I decided to actually treat LLM spending like a real infrastructure problem instead of a credit card swipe. What follows is the playbook I wish I'd had on day one. These aren't theoretical tips — they're the exact moves I made across three products to get our run-rate down to roughly 5% of where it started, without shipping worse software. The Harsh Truth About Model Defaults Here's the dirty secret nobody tells you in the LLM hype cycle: most teams default to the most famous model for every single call. GPT-4o for everything. Claude Sonnet for everything. Then they wonder why their "simple AI feature" costs them a kidney. The model selection decision is where I recovered the majority of my budget. When you look at it rationally, the gap between the flagship tier and the cheap-tier models is absurd for tasks that don't require frontier reasoning. This is the matrix I landed on, and it still governs our routing today: Task What I Used To Use What I Use Now Cost Cut Simple chat GPT-4o ($10/M out) DeepSeek V4 Flash ($0.25/M) 97.5% Classification GPT-4o-mini ($0.60/M) Qwen3-8B ($0.01/M) 98.3% Code generation GPT-4o ($10/M) DeepSeek Coder ($0.25/M) 97.5% Summarization GPT-4o ($10/M) Qwen3-32B ($0.28/M) 97.2% Translation GPT-4o ($10/M) Qwen-MT-Turbo ($0.30/M) 97% I want you to really sit with the classification row. Qwen3-8B at $0.01 per million output tokens. That's sixty times cheaper than GPT-4o-mini. For a binary sentiment classifier, the accuracy difference in my benchmarks was under 1.5 percentage points. The ROI math isn't even close. The code

2026-07-06 原文 →
AI 资讯

Build a UGC video moderation pipeline with FFmpeg + NudeNet

TL;DR If your product lets strangers upload video, you need moderation before launch, not after the first bad upload. We will build a small-team pipeline: extract frames with FFmpeg, score them with NudeNet (ONNX Runtime, CPU-friendly), route uploads into approve / human-review / block by confidence, and log every decision. No trust-and-safety department required. 📦 Code: github.com/USER/ugc-moderation, replace before publishing ⚠️ Note: this is a sensitive area. The goal here is the engineering shape (sampling, scoring, routing, auditing), not detection of any specific content. Keep test fixtures clean and lawful. A model does not decide what is allowed. It produces a score. You decide where the lines go. The whole design is about routing scores sensibly and sending the uncertain middle to a human. The architecture 🧠 upload ──> extract sample frames (ffmpeg) ──> score frames (NudeNet / ONNX) ──> aggregate to one confidence ──> route: high-confidence clean -> auto-approve uncertain middle band -> human review queue high-confidence violation -> auto-block ──> write an audit record for every decision The economics only work if the middle band is small. A decent model makes most uploads obviously fine or obviously not, so a human only ever sees the genuinely ambiguous slice. 1. Sample frames, do not score every frame You cannot afford every frame and you do not need it. Pull one frame per second (or scene-change keyframes) with FFmpeg. # extract 1 frame per second into ./frames mkdir -p frames ffmpeg -i upload.mp4 -vf "fps=1" -q :v 3 frames/frame_%05d.jpg Prefer scene changes to catch more variety with fewer frames: # keyframes where the scene actually changes ffmpeg -i upload.mp4 -vf "select='gt(scene,0.3)',showinfo" -vsync vfr frames/scene_%05d.jpg 💡 Tip: a 30-minute upload at 1 fps is ~1,800 frames. Scene-change sampling often cuts that by an order of magnitude with little loss for moderation purposes. 2. Score frames with NudeNet NudeNet runs on ONNX Runtime on pla

2026-07-06 原文 →
AI 资讯

My AI agent tried to ship a mistake we'd already reverted

A month ago we added a card_token column to the users table so a background job could retry failed Pro charges. It lasted about two days. Storing card data in your own database drops you into PCI-DSS (the compliance standard that kicks in the moment card data touches your systems), so we pulled it and moved to Stripe-managed payment methods. Last week the charges started failing again. New Claude Code session, no memory of any of that. Its plan? Add a card_token column to users and retry. I don't really blame the agent. It had the context the first time and it was right. The problem is that context died when the session closed. That's the part I never see mentioned about building with agents: the code sticks around, the reasoning doesn't. People leave a trail without trying. A commit message, a PR comment, the Slack thread before it. Agents don't, and the prompt that explained everything is gone by morning. So I built Selvedge to hold onto the reasoning. What happened the second time Selvedge is a local MCP server the agent calls as it works. There's a four-line block in our CLAUDE.md that says, roughly: before you touch an entity, check if we've been here before. $ selvedge prior-attempts users.card_token users.card_token Prior attempt 28 days ago ( reverted after 2 days ) Reasoning Added to store card tokens for one-click retries. Outcome REVERTED — kept card data out of our own DB to stay clear of PCI-DSS scope ; moved to Stripe-managed methods. So it didn't add the column. It charged off_session against the saved Stripe PaymentMethod instead. Charge retried, no card data in our database, done. We paid for that lesson once. How it works The agent writes down why live, in the moment, from the same context that made the change. That's the whole trick. A lot of the "git blame for AI" tools take your diff afterward and ask a second model to explain it. That's a guess. It reads well, but you can't really build on it. Selvedge stores what the agent actually meant, in i

2026-07-06 原文 →
AI 资讯

I Got Tired of My Portfolio Looking Like a List of Links. So I Built an MCP Server for It.

The obvious fix for "my projects all look similar" is a better README — more screenshots, clearer descriptions, maybe a comparison table. I considered that for about five minutes and decided it was still just a nicer list of links. What actually made a portfolio project feel different was making it something you could talk to instead of read. That's what MCP (Model Context Protocol) is built for — it's the standard that lets AI clients like Claude Desktop call external tools directly, not just process text. So I built a server that exposes my 9 projects as queryable tools instead of static entries. What is MCP, and why does it matter here Almost every AI-developer portfolio I've seen is a list of links. Mine now includes something you can actually talk to . Open Claude Desktop, connect my server, and ask "what has Ayush built with FastAPI?" — it doesn't guess from a cached README, it calls a real tool and answers from structured, live data. What I built A Python MCP server ( FastMCP , stdio transport) exposing five tools: list_projects — short summary of all 9 projects get_project_details(project_name) — full stack, GitHub link, demo URL for one project, fuzzy-matched by name search_projects_by_stack(technology) — "show me everything using Groq" or "LangGraph" or "React" get_flagship_project — the single best project to look at first get_resume_summary — background, target role, core stack The data itself lives in plain Python dictionaries right now — no database needed for something this size. Each tool is a thin function around that data, decorated with @mcp.tool() . @mcp.tool () def search_projects_by_stack ( technology : str ) -> list [ dict ]: """ Find all projects that use a given technology or tool. """ query = technology . lower (). strip () matches = [ { " name " : p [ " name " ], " stack " : p [ " stack " ], " github " : p [ " github " ]} for p in PROJECTS if any ( query in tech . lower () for tech in p [ " stack " ]) ] return matches or [{ " message " : f

2026-07-06 原文 →
AI 资讯

FROST 的治理哲学:为什么每个 Agent 系统都需要一部宪法

FROST 的治理哲学:为什么每个 Agent 系统都需要一部宪法 "细胞会死,但谱系会存续。Agent 会消亡,但宪法会传承。资产会永存。" 在 AI Agent 框架百花齐放的 2026 年,我们见证了一个有趣的现象:框架越来越多,治理却越来越缺失。LangChain 给了你工具链,CrewAI 给了你角色扮演,AutoGen 给了你对话——但没有人回答一个关键问题: 当你的 Agent 家族有十代、百代,谁来保证它们的行为不越界? 这就是 FROST 要解决的问题。 一、一个被忽视的问题:Agent 治理真空 想象这样一个场景:你构建了一个 Agent 系统,它帮你处理客户咨询、自动写报告、管理财务。一开始只有 3 个 Agent,你都能监控。三个月后,Agent 数量变成了 30 个——有些是你创建的,有些是 Agent 自己创建的。 问题来了: 某个 Agent 开始访问不该访问的数据 某个 Agent 创建的子 Agent 继承了一份不该继承的权限 某个 SOP 工作流在运行中被人悄悄修改了 这不是科幻场景,这是今天 Agent 系统正在发生的事。 根本原因 :现有框架的"治理"要么是提示词级别的软约束("请你不要访问这些数据"),要么是事后的日志审计。没有一个是代码级别、架构级别的硬约束。 FROST 的设计哲学是: 治理必须是架构的一部分,而不是补丁。 二、FROST 的宪法模型:四层治理 FROST 把治理拆解为四个层次,每一层都有对应的代码实现: 第一层:只读继承——权限的代码级强制 在大多数框架中,Agent 之间的数据共享靠的是"约定"。FROST 用的是 HierarchicalStore ——一种层级化记忆容器: class HierarchicalStore : """ 层级化记忆存储。 祖先 Store 对后代只读——后代可以继承,但不能篡改。 """ def __init__ ( self , data = None , parent = None , readonly = False ): self . _data = data or {} self . _parent = parent self . _readonly = readonly # 关键:只读标记 def save ( self , key , value ): if self . _readonly : raise PermissionError ( " 只读 Store 禁止写入 " ) self . _data [ key ] = value def load ( self , key , default = None ): if key in self . _data : return self . _data [ key ] if self . _parent : return self . _parent . load ( key , default ) return default 注意 readonly 参数。当一个 Agent 创建子 Agent 时,子 Agent 对父 Agent 的 Store 是 只读的 。这不是提示词告诉 Agent "请你不要修改",而是代码直接抛出异常。 这意味着 :即使 LLM 产生了幻觉,试图越权写入,代码层面也会拒绝执行。 第二层:SOP 宪法校验——工作流的可审计性 在 FROST 中,SOP 不是随便定义的步骤列表,而是经过祖辈审核的"宪法文本": def validate_sop ( ancestor_sop , descendant_sop ): """ 祖辈验证后代的 SOP 是否合规。 检查点: 1. 后代 SOP 的步骤不能超出祖辈定义的边界 2. 后代 SOP 不能调用未授权的 Skill 3. 后代 SOP 的数据访问不能超出权限范围 """ # 检查 1:步骤边界 for step in descendant_sop . steps : if step not in ancestor_sop . allowed_steps : raise SOPValidationError ( f " 步骤 { step } 超出祖辈定义的边界 " ) # 检查 2:Skill 授权 for skill in descendant_sop . required_skills : if skill not in ancestor_sop . authorized_skills : raise SOPValidationError ( f " Skill { skill } 未获授权 " ) return True 这意味着 :任何后代 Agent 想要执行的工作流,都必

2026-07-06 原文 →
AI 资讯

Modeling the Expected Value of a Sealed Card Box (and Where the Number Quietly Lies)

A friend messaged me a photo of a sealed booster box last month with one question: "worth it?" He'd already decided, really. The chase card in that set was all over his feed, so the box felt like a good deal. I asked him to send me the pull rates instead of the hype, and we spent twenty minutes turning "worth it?" into something we could actually compute. That exercise is a small, self-contained data problem. It's also a good example of how a clean-looking model can hand you a confident number that doesn't survive contact with reality. If you like building little estimators, this one is worth doing carefully, because the interesting part isn't the formula. It's everything the formula assumes. The formula is the easy part Expected value of a box is a weighted sum. Each card you can pull has a probability and a market value, and you multiply the two across every slot the box gives you. That's it. Undergrad probability. Here's a stripped-down version for a hypothetical set. I'm using made-up numbers so nobody mistakes this for real pull data — the point is the shape of the computation, not the specific set. # One "hit slot" in a box: probabilities cover the full outcome space. # Values are illustrative market estimates in USD. hit_table = [ { " name " : " Alt-art chase " , " p " : 0.0125 , " value " : 180.00 }, { " name " : " Secret rare " , " p " : 0.030 , " value " : 45.00 }, { " name " : " Full-art rare " , " p " : 0.100 , " value " : 8.00 }, { " name " : " Standard hit " , " p " : 0.400 , " value " : 0.55 }, { " name " : " No notable hit " , " p " : 0.4575 , " value " : 0.06 }, ] assert abs ( sum ( row [ " p " ] for row in hit_table ) - 1.0 ) < 1e-9 ev_per_slot = sum ( row [ " p " ] * row [ " value " ] for row in hit_table ) hit_slots_per_box = 36 # e.g. one meaningful slot per pack ev_box = ev_per_slot * hit_slots_per_box print ( f " EV per slot: $ { ev_per_slot : . 2 f } " ) # $4.65 print ( f " EV per box: $ { ev_box : . 2 f } " ) # $167.31 The box costs $150 sea

2026-07-06 原文 →
AI 资讯

Before adopting DSPy, prove the LM program has a contract

Before adopting DSPy, prove the LM program has a contract DSPy is easy to undersell. If you describe it as "a nicer way to write prompts", you will probably test the wrong thing. The better first test is this: can your language-model workflow be expressed as a small program with declared inputs, declared outputs, measurable examples, and an optimizer that is allowed to change prompts without changing the business boundary? That is the point where DSPy starts to make sense. The upstream README positions DSPy as a framework for programming, rather than prompting, foundation models. The current Doramagic project pack for stanfordnlp/dspy also points at the same starting command: pip install dspy . The package metadata I checked today declares name="dspy" , version 3.3.0b1 , and Python >=3.10,<3.15 . The GitHub API snapshot showed the repository was still active, with a push on 2026-07-05 and recent pull requests around empty evaluation sets, document formatting, and GEPA trace attribution. That activity is useful, but it is not the adoption proof. The proof is whether your own task can survive three separations. 1. Separate the task contract from the prompt In DSPy terms, the first artifact worth reading is not a clever prompt. It is the Signature. A Signature says what goes in and what must come out. A Module wraps that contract into something callable. An Adapter turns the contract into the provider-facing prompt format and parses the model response back into fields. That gives you a practical review question: Can the team name the output fields before anyone starts tuning wording? If the answer is no, DSPy will not rescue the workflow. You are still negotiating the task itself. The first pass should be a tiny contract: input text, retrieved context if needed, answer, citations, confidence, or whatever fields the product actually needs. Do not start with agents, tools, or multi-stage pipelines. 2. Separate compilation from runtime correctness DSPy optimizers can impr

2026-07-06 原文 →
AI 资讯

Building a 'Chief Health Officer' with LangGraph: Automatically Filter Your Food Delivery Based on Real-Time Blood Sugar

We’ve all been there: it’s 7:00 PM, you’re exhausted after a long sprint, and you open a food delivery app. Your brain screams "Double Cheeseburger," but your body is still recovering from that mid-afternoon sugar spike. What if your phone was smart enough to say, "Hey, your blood sugar is currently 160 mg/dL and rising—maybe skip the extra fries?" In this tutorial, we are building a Chief Health Officer (CHO) Agent . This isn't just a simple chatbot; it’s a sophisticated AI Agent using LangGraph to bridge the gap between real-time medical data (CGM) and real-world actions (Food Delivery APIs). By leveraging automation , function calling , and state machines , we’ll create a system that actively protects your metabolic health. The Architecture: How the CHO Agent Thinks To build a reliable agent, we need a "stateful" workflow. We aren't just sending a prompt to an LLM; we are creating a loop that monitors glucose levels, analyzes food options, and interacts with the browser. graph TD A[Start: Hunger Trigger] --> B{Fetch CGM Data} B -->|Sugar High/Unstable| C[Constraint: Low GI Only] B -->|Sugar Stable| D[Constraint: Balanced Meal] C --> E[Scrape Delivery App Menu] D --> E E --> F[Agent: Analyze Ingredients & GI Index] F --> G[Selenium: Mark/Filter Non-Compliant Items] G --> H[End: Safe Ordering] subgraph "The LangGraph Loop" C D E F end Prerequisites Before we dive into the code, ensure you have the following: LangGraph & LangChain : For the agent's cognitive architecture. Dexcom API Credentials : To fetch real-time Continuous Glucose Monitor (CGM) data. Selenium : For interacting with food delivery web interfaces (Meituan/Ele.me). OpenAI API Key : Specifically for GPT-4o’s reasoning and function-calling capabilities. Step 1: Defining the Agent State In LangGraph, everything revolves around the State . Our CHO agent needs to track the current glucose level, the user's health constraints, and the list of available food items. from typing import TypedDict , List , Anno

2026-07-06 原文 →
AI 资讯

I Built an AI Agent That Remembers Why Customers Leave (And I'm Building My Way Into AI Development)

With over 5 years in customer support and retention, I've lost count of how many times I've seen the same pattern: a customer explains an issue, gets it "resolved," and then has to explain the same problem again weeks later, as if the first conversation never happened. Support systems forget. Customers don't. That frustration, seen over years on the support side, is what led me to this hackathon project. Most support systems and most AI chatbots treat every interaction as isolated. They don't remember. So patterns that should be obvious (repeated complaints, dropping usage, unresolved issues) never get connected until a customer just leaves. That became the seed for my project: the Retention Risk Agent. The Problem With "Forgetful" AI Most AI tools answer questions in the moment, then forget everything. Ask a chatbot about a customer's history, and it only knows what's in that single message, not what happened last week, last month, or across five different support tickets. For churn prediction, that's a fatal flaw. Churn isn't a single event. It's a pattern, a series of small signals that only make sense when viewed together over time. This is something I understand deeply from years of watching it happen firsthand. Cognee is an open-source memory layer for AI agents. Instead of treating each interaction as isolated, it builds a knowledge graph, connecting facts, relationships, and context across everything you feed it. That's exactly what churn detection needed. What I Built I created a Python script that: Ingests customer records (support tickets, usage patterns, plan changes) Uses Cognee to build a memory graph connecting these signals Asks a simple question: "Which customers show signs of churn risk, and why?" The result wasn't a keyword match; it was reasoning. The agent correctly flagged a customer whose usage dropped 80% and who'd ignored two check-in emails. It flagged another who'd complained twice about slow support and mentioned a competitor. And critica

2026-07-06 原文 →
AI 资讯

Guardrails for LLM Apps in Python

Introduction Every post in this series has quietly touched a piece of the same problem. Building Agentic Workflows in Python said a tool's input is untrusted and must be validated before it reaches your code. Building Reliable LLM Applications in Python said the model will confidently invent facts, so ground it and get typed output instead of parsing prose. Neither post named the thing underneath both statements: anything that crosses from outside your code into the model, or from the model back into your code, is untrusted input — a request body from the network, not a trusted internal value. This post names that boundary directly and gathers the defenses in one place — prompt injection (direct and indirect), input validation, output validation, and PII redaction — with the SAFE pattern shown beside every unsafe one it replaces, since this is the security-forward capstone of the series. The Trust Boundary: Three Kinds of Untrusted Input An LLM application has three places where untrusted text enters: User input — anything a person types, uploads, or submits through an API. Retrieved content — Making RAG Accurate in Python built a pipeline that ranks and returns chunks from a document store; those chunks were written by whoever authored the source document, not by you, and a malicious or compromised document can carry text aimed at the model reading it, not at a human reader. Model output — untrusted the moment it's about to be used rather than displayed : passed to a tool, interpolated into a query, or fed into another LLM call as context. A model that just read attacker-controlled retrieved text can be manipulated into producing attacker-controlled output. The single rule under all three: text is data until your code has explicitly decided it's safe to use for anything more than display. Nothing below is executed against a live API — every snippet is illustrative, and none of it uses a real key or a real record. Direct Prompt Injection: Defending the System Prompt

2026-07-06 原文 →