AI 资讯
FastAPI for AI Engineers - Part 4: Stop Bad Data Before It Breaks Your API (Pydantic and Data Validation)
In the previous article, we connected our FastAPI application to a database using SQLite and SQLAlchemy. We also used classes like: class StudentCreate ( BaseModel ): name : str department : str cgpa : float without fully understanding what was happening behind the scenes. Today, we'll fix that. If you haven't read it check it out: FastAPI for AI Engineers - Part 3: Connecting to a database Ananya S Ananya S Ananya S Follow Jun 6 FastAPI for AI Engineers - Part 3: Connecting to a database # ai # fastapi # python # backend 6 reactions Add Comment 6 min read Why Do We Need Data Validation? Imagine you're building a weather application. A user asks: What is the temperature in Chennai? A valid response might be: 35 or 35°C But what if the API returns: Sunny This is clearly wrong. Temperature should be represented as a number. Even if the value itself is inaccurate, we still know that temperature must be numeric. This is where validation becomes important. Validation allows us to define rules about what data is acceptable before it enters our application. For example: Temperature should be numeric Age cannot be negative CGPA should be between 0 and 10 Email addresses should follow a valid format Without validation, applications can receive invalid data and behave unexpectedly. The Problem Without Validation Consider a student registration API. @app.post ( " /student " ) def create_student ( student ): return student A user could send: { "name" : "Ananya" , "cgpa" : "Excellent" } The API would accept it. But a CGPA should be a number, not text. As applications grow, manually checking every field becomes difficult. We need a better solution. Enter Pydantic Pydantic is a Python library used for data validation. FastAPI uses Pydantic extensively behind the scenes. Instead of manually validating data, we define a schema. from pydantic import BaseModel class Student ( BaseModel ): name : str cgpa : float Now FastAPI knows: name must be a string cgpa must be a floating-point nu
AI 资讯
Lawyers, Marketers, Product Managers—Xiaomi's Breakthrough Agent Product SoloEngine: Everyone Is a Creator
On June 3, Xiaomi released the latest version of its open-source project, SoloEngine . The first low-code Agentic AI development platform. At the AIGC2026 Summit, Amazon Web Services disclosed a striking statistic: 87% of enterprises claim to have deployed AI, but only 10% have actually extracted real value from it. The current agent industry chain shows a curious pattern—hot at both ends, hollow in the middle. Upstream foundation models and chips attract capital; downstream use-case demand is robust; but the midstream lacks an engineering platform capable of converting domain expertise into reliable agents. The reasons behind this gap are concrete. Building an AI Agent currently comes down to two approaches. One is low-code workflow platforms: Dify and n8n offer visual canvases where users drag and drop nodes to quickly assemble AI applications. But workflows rely on preset paths—step A leads to step B, step B leads to step C, with if/else conditions controlling branches. Hit something outside the preset, and the flow breaks. At best, they function as AI-powered macro scripts. The other is code-based development frameworks: LangChain and CrewAI support genuine Agentic AI architectures where agents can make autonomous decisions and dynamically adjust strategies. But this requires Python programming skills. A lawyer has to learn Python just to build a legal Agent; a CMO has to configure a CrewAI environment just to set up a marketing Agent team. Low-code platforms don't support true autonomous decision-making. Code frameworks are only accessible to programmers. SoloEngine fills precisely this gap. I. SoloEngine: Making Everyone a Creator Open a browser. Drag Agents onto a canvas. Connect collaboration relationships. Configure the tools you need. Hit run. The backend automatically compiles your design into an executable Agentic AI system—one that plans tasks, executes operations, and delivers results. Users just review and confirm, and the work gets done. No lines of
AI 资讯
stubgen-pyx: The stubs mypy can't generate
NVIDIA's cuda-python , the official Python bindings for the CUDA toolkit, recently added automatically-generated .pyi stub files using stubgen-pyx . Their description of why: "This allows IDE auto-completion to work (which is also used by IDE-integrated coding agents). This has also found 2 real bugs in our code already. The ability to catch a certain class of bugs with this will be really helpful going forward, especially since our linting abilities with cython-lint are a bit behind what they are in pure Python." When you commit .pyi stubs alongside a Cython extension, you get an artifact your normal Python linting and type-checking pipeline can analyze. Inconsistencies between what the Cython source does and what the stub claims become visible. NVIDIA found two real bugs this way before they were reported. I'm the author of stubgen-pyx, and this post is a technical walk-through of how those stubs are produced. The problem with existing stub generators When you compile a Cython module, the source disappears. What you get is a .so (or .pyd ) file: a compiled extension with no type information readable by a language server. Tools like mypy's stubgen can generate stubs for these by importing the compiled binary and using runtime introspection. The results are usually disappointing. Take this typed Cython module: """ Mathematical utilities for scientific computing. """ cdef class Matrix : """ A simple matrix class. """ cdef int rows cdef int cols def __init__ ( self , int rows , int cols ): """ Initialize a matrix. """ self . rows = rows self . cols = cols def shape ( self ) -> tuple [ int , int ]: """ Get matrix dimensions. """ return ( self . rows , self . cols ) cpdef scale ( self , double factor ): """ Scale all elements. """ pass cdef int _validate ( self ): """ Internal validation (not exposed). """ return 0 def matrix_product ( Matrix a , Matrix b ) -> Matrix : """ Compute matrix product. """ return Matrix ( a . rows , b . cols ) Running stubgen on the compiled
AI 资讯
How to Build a Polymarket BTC Momentum Trading Bot in Python (5-Minute Crypto Up/Down Market Strategy)
Introduction Crypto prediction markets move fast. One interesting pattern I noticed while trading on Polymarket is that short-term crypto markets often follow Bitcoin's direction, especially near market expiration. When Bitcoin shows strong directional momentum, assets such as Ethereum (ETH), Solana (SOL), and XRP frequently move in the same direction. This observation led me to build a simple momentum-based Polymarket trading bot. The core idea is straightforward: Monitor BTC Up/Down markets. Detect strong directional probability from the order book. Confirm that ETH, SOL, or XRP markets agree with Bitcoin. Enter positions when confidence is high. Hold until market settlement. Redeem winnings automatically. In this tutorial, you'll learn how to build a Python bot that: ✅ Fetches Polymarket market data ✅ Reads order book probabilities ✅ Detects BTC momentum signals ✅ Places automated buy orders ✅ Waits for settlement ✅ Redeems winning positions The goal is not to predict the future perfectly. The goal is to identify situations where multiple crypto prediction markets agree on direction and exploit that momentum. Why Bitcoin Momentum Matters Bitcoin is still the dominant asset in the cryptocurrency market. When BTC experiences a strong move: ETH often follows SOL often follows XRP often follows Other altcoins frequently move in the same direction This correlation is especially visible during short-duration prediction markets. For example: Market YES Probability BTC Up 0.95 ETH Up 0.93 SOL Up 0.92 When all three markets strongly agree on direction, there may be an opportunity to enter the same side before settlement. This is the basic principle behind the momentum bot. Strategy Overview The bot continuously watches several crypto markets. Step 1: Monitor BTC Market If BTC Up reaches: BTC Up > 0.90 or BTC Down > 0.90 the bot considers Bitcoin momentum strong. Step 2: Confirm Altcoin Agreement The bot then checks: ETH SOL XRP If at least one of these markets has the sam
AI 资讯
Automating Brazilian company verification for accountants and finance teams
If you work with Brazilian companies — as an accountant, credit analyst, or anyone processing PJ clients at scale — here's a practical automation approach using free public data. What you can verify automatically For any CNPJ, public data gives you: Situação cadastral : ATIVA, BAIXADA, INAPTA, SUSPENSA — critical for invoice validation Razão social : legal name for contract matching CNAE : is this company allowed to do what they claim? QSA : who are the actual partners/directors? Data abertura : how old is the company? The data 65M+ CNPJs from Receita Federal, indexed and searchable at Jurídico Online . Free. Also available as a Python package: pip install juridico-online from juridico_online import empresa_url , buscar_url # Get company page URL for a CNPJ url = empresa_url ( " 00.000.000/0001-91 " ) print ( url ) # https://juridicoonline.com.br/empresa/00000000000191 # Search by company or partner name search = buscar_url ( " Magazine Luiza " ) print ( search ) Checks worth automating 1. Situação ATIVA before accepting any invoice INAPTA or BAIXADA companies cannot legally issue NF-e. 2. CNAE vs service being billed A company with CNAE "comércio de alimentos" billing for software development is a red flag. 3. Company age vs contract value A 3-month-old company offering a R$500k contract deserves extra scrutiny. 4. Shared partners across suppliers If two suppliers share directors, that's a conflict of interest. Search partner names at juridicoonline.com.br to see all companies they control. Integration patterns ERP/AP : validate CNPJ status before releasing payment Onboarding : auto-fill razão social when client enters CNPJ Batch audit : cross-check your vendor list quarterly Monitoring : alert if a key supplier's CNPJ changes status The data is public, free, and updated regularly. No excuse to check manually at scale.
AI 资讯
ContextLens — py-spy/pprof but for what's inside your LLM prompt
In multi-turn agent loops, the full context re-sends on every API call. A tool result added at turn 3 gets billed again at turns 4, 5, 6, 7... forever. Most of it is never read again. Standard observability tools tell you the total token count. They never tell you what's in there or how much of it is waste . That's what ContextLens fixes. What it does ContextLens is a diagnostic profiler for LLM agent context windows. It: Decomposes the context window into regions: system prompt, tool schemas, tool results, retrieved chunks, user messages, assistant messages Tracks which blocks get re-billed across turns using SHA-256 content hashing Runs 5 waste detectors and ranks findings by dollar cost Prints a concrete one-line fix for each finding Renders an interactive D3 treemap report as a self-contained HTML file No API key required. Works offline on saved traces. The five detectors Detector What it finds Duplicate Same block re-sent verbatim across multiple turns Near-Duplicate >85% Jaccard similarity between distinct blocks Stale Tool Result Tool output never referenced by a later assistant message Unused Tool Schema Tool defined every turn but never called Redundant Retrieval Retrieved chunk with <15% overlap with model output ---Run the built-in demo (simulates a 30-turn agent loop, no API key needed): python -c "import contextlens; contextlens.demo()" python examples/demo.py Live capture — Anthropic import anthropic import contextlens as cl client = anthropic.Anthropic() with cl.capture_anthropic(client, model="claude-3-5-sonnet-20241022") as collector: for turn in range(20): client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1024, system="You are a helpful assistant.", messages=build_messages(turn), ) report = cl.analyze_trace(collector.build_trace()) print(f"Recoverable waste: {report.recoverable_tokens:,} tokens (${report.recoverable_cost_usd:.4f})") Live capture — OpenAI import openai import contextlens as cl client = openai.OpenAI() with cl.ca
AI 资讯
AgentTrust ID is live
This weekend, AgentTrust ID went live in production. As of today, all five SDKs are published: pip install agenttrustid npm install @agenttrustid/sdkgo get github.com/agenttrustid/sdk/go cargo add agenttrustid # Maven / Gradle # id.agenttrust:agenttrustid:0.3.0 The SDKs are open source under Apache 2.0 at github.com/agenttrustid/sdk . The hosted platform is running at app.agenttrust.id in a controlled beta. Why I built this AI agents broke the assumptions that machine-to-machine security was built on. An API key answers one question: who is calling. It asks it once, at the door. An agent decides its next action at runtime, from context nobody wrote by hand. The same agent that summarized a document a second ago might now try to email it, delete it, or chain a task to another agent. A credential that only proves identity has no opinion about any of that. Agents need a decision at the action boundary : should this specific action happen, right now, on whose behalf . Answered at runtime, every time, with an audit trail and a kill switch. What's running Everything below is live in production today, not a roadmap: Per-action authorization. Every consequential action passes a pre-flight check. The Guardian pipeline routes each action by risk: deterministic rule checks for the common path, a policy engine for mutations, and AI-backed review for destructive operations. Fail-closed where it counts. Opaque, instantly revocable tokens. Credentials are at_ references with no standing authority of their own . The server decides on every use, so revocation is one call, effective immediately. Scoped delegation. When one agent hands work to another, the grant narrows instead of copying : subset scopes, independent TTLs, independently revocable, bounded chain depth. Read-only sessions with time-boxed elevation. Sessions start safe and rise only on approval, for a bounded window, then revert on their own. One model across surfaces. MCP tools, agent-to-agent calls, and direct API inte
开源项目
🔥 magenta / magenta-realtime - Magenta RealTime 2: An Open-Weights Live Music Model
GitHub热门项目 | Magenta RealTime 2: An Open-Weights Live Music Model | Stars: 1,418 | 86 stars today | 语言: Python
开源项目
🔥 alistaitsacle / free-llm-api-keys - Free LLM API keys for GPT-5.5, Claude, DeepSeek, Gemini, Gro
GitHub热门项目 | Free LLM API keys for GPT-5.5, Claude, DeepSeek, Gemini, Grok — copy, paste, use. Updated 3-5x daily. No credit card needed. | Stars: 1,782 | 143 stars today | 语言: Python
开源项目
🔥 luongnv89 / claude-howto - A visual, example-driven guide to Claude Code — from basic c
GitHub热门项目 | A visual, example-driven guide to Claude Code — from basic concepts to advanced agents, with copy-paste templates that bring immediate value. | Stars: 35,507 | 154 stars today | 语言: Python
开源项目
🔥 Andyyyy64 / whichllm - Find the local LLM that actually runs and performs best on y
GitHub热门项目 | Find the local LLM that actually runs and performs best on your hardware. Ranked by real, recency-aware benchmarks, not parameter count. One command, run it instantly. | Stars: 3,192 | 103 stars today | 语言: Python
开源项目
🔥 google / skills - Agent Skills for Google products and technologies
GitHub热门项目 | Agent Skills for Google products and technologies | Stars: 12,111 | 481 stars today | 语言: Python
AI 资讯
I Built a GDPR Compliance Scanner Using the Claude API - Here's How It Works
I Built a GDPR Compliance Scanner Using the Claude API - Here's How It Works A few months ago I noticed something that kept bugging me. I was building and handing off websites for clients and every single time, GDPR compliance was either an afterthought or a panic right before launch. Privacy policies copied from templates, cookie banners slapped on at the last minute, no one really sure if the contact form was actually compliant. The bigger problem: there was no quick, affordable way to check . Enterprise compliance tools cost hundreds per month. Legal consultants cost more. Most small businesses just crossed their fingers. So I built ClearlyCompliant - an automated GDPR compliance scanner that analyses a website and delivers a detailed PDF report for a one-off fee. No subscription, no jargon, just a clear picture of where a site stands. Here's how it actually works under the hood. The Stack Django (Python) - backend and web app BeautifulSoup + requests - crawling and HTML parsing Python threading - async scanning without the overhead of Celery/Redis Anthropic Claude API (Haiku) - AI-powered policy analysis ReportLab - PDF report generation Stripe - payments IONOS SMTP - email delivery Gunicorn + Nginx on an IONOS VPS The Scanning Pipeline When a user submits a domain and completes payment, the scan kicks off immediately. Rather than making them wait on a loading screen, the scan runs asynchronously in a background thread and the report gets emailed when it's done. I deliberately avoided Celery and Redis here. For the scale I needed, Python's built-in threading module was more than sufficient and kept the infrastructure simple. One less thing to maintain, one less thing to break. import threading def run_scan_async ( domain , order_id , customer_email ): thread = threading . Thread ( target = run_full_scan , args = ( domain , order_id , customer_email ) ) thread . daemon = True thread . start () The scan itself runs 23 individual GDPR checks across several categori
AI 资讯
I Wanted Better Insights Across My Bank Accounts, So I Built MyVault
Most side projects start with a simple frustration. Mine started with a banking app. One of my banks had a feature I really liked. It automatically categorized transactions and showed spending breakdowns in graphs and charts. For the first time, I could easily see how much I spent on restaurants, groceries, transport, subscriptions, and other categories. The problem was that only one of my banks offered this feature. Like many people, I use multiple bank accounts, credit cards, and savings accounts. Two of my other banks provided little more than a long list of transactions. If I wanted a complete picture of my finances, I had to switch between apps and manually piece everything together. As a software engineer, my first instinct was obvious: "Why don't I just build this myself?" That idea eventually became MyVault . The Original Goal The first version of the project was surprisingly simple. I wanted users to: Upload bank statements Extract transaction data Automatically categorize spending View useful charts and reports The goal wasn't budgeting. It wasn't investment tracking. It wasn't accounting. I simply wanted a single place where I could see spending across all of my bank accounts. Once I started building, however, I realized there was a much more interesting opportunity. If all transaction data was already extracted and structured, why not allow users to ask questions about their finances? Instead of searching through transactions manually, users could simply ask: How much did I spend on restaurants last year? What subscriptions am I paying for? Which categories increased the most this month? How much did I spend while traveling? That's when MyVault started evolving from a reporting tool into an AI-powered financial assistant. Building as a Solo Developer One of the biggest challenges wasn't technology. It was building everything alone. When you're working on a side project, you don't just write code. You become responsible for everything: Product decisions B
开源项目
🔥 SudoHopeX / KaliGPT - KaliGPT: an Agentic AI (built with Gemini, ChatGPT, Ollama,
GitHub热门项目 | KaliGPT: an Agentic AI (built with Gemini, ChatGPT, Ollama, OpenRouter Models) fine tuned for ethical hackers & students in offensive security making workflows smarter, faster, and more accessible. | Stars: 487 | 46 stars today | 语言: Python
开源项目
🔥 sherlock-project / sherlock - Hunt down social media accounts by username across social ne
GitHub热门项目 | Hunt down social media accounts by username across social networks | Stars: 84,663 | 73 stars today | 语言: Python
开源项目
🔥 roboflow / supervision - We write your reusable computer vision tools. 💜
GitHub热门项目 | We write your reusable computer vision tools. 💜 | Stars: 40,746 | 600 stars today | 语言: Python
开源项目
🔥 HunxByts / GhostTrack - Useful tool to track location or mobile number
GitHub热门项目 | Useful tool to track location or mobile number | Stars: 13,582 | 21 stars today | 语言: Python
开源项目
🔥 RyanCodrai / turbovec - A vector index built on TurboQuant, written in Rust with Pyt
GitHub热门项目 | A vector index built on TurboQuant, written in Rust with Python bindings | Stars: 6,293 | 1,533 stars today | 语言: Python
AI 资讯
What a policy gate catches in AI-generated code, and what slips through
I maintain an open-source GitHub Action called vorsken. It does one thing: scan the diff on a pull request with Semgrep, apply a fixed policy, and return BLOCK, FLAG, or PASS. No dashboard, no model that drifts over time. Rules at ERROR/HIGH/CRITICAL severity block the merge, WARNING/MEDIUM flag it, the rest pass. Same diff, same verdict. The usual pitch for a tool like this is that it catches the SQL injection your AI assistant wrote. I wanted to see what it actually catches against real assistant output, so I generated 28 functions and ran them through. The test Seven backend tasks: a FastAPI upload endpoint, a URL-fetch helper, JWT auth, a SQL filter, an ImageMagick subprocess call, a LangChain file agent, and a LangChain RAG pipeline. I generated each one four times, with ChatGPT (GPT-5.5 Instant), Claude Code (Opus 4.8), Claude Code plus the security-guidance plugin, and Cursor (Composer 2.5). Single-shot, neutral prompt, no security hints. Then I scanned all 28 with the same ruleset. I'm reporting which rule fired on which file, not whether some model thinks the code is safe. That part you can reproduce. Task ChatGPT Claude Code + plugin Cursor Verdict file upload — — — — PASS url fetch (SSRF) ssrf ssrf ssrf — FLAG / Cursor PASS jwt auth api8 api8 — — BLOCK / 2 PASS sql filter — — — — PASS imagemagick — — — — PASS fs agent — overperm — — 1 BLOCK / 3 PASS rag dangerous dangerous dangerous dangerous BLOCK 7 BLOCK, 3 FLAG, 18 PASS across 28 functions. The basics were fine SQL filter, ImageMagick, file upload: clean on every tool. The SQL was parameterized, the subprocess calls passed argument lists instead of shell strings, the uploads weren't doing anything reckless. If you still expect current models to spray SQL injection across a straightforward CRUD task, they don't. On conventional work they get it right. Two of the flags are soft. The JWT api8 hits landed on a SECRET_KEY = "CHANGE_ME" placeholder, which you can read as a false positive or as a gate doing i