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

标签:#api

找到 355 篇相关文章

AI 资讯

A FastAPI Agent Template Is Not Production-Ready Until Task Ownership Crosses Every Layer

Vercel published an OpenAI Agents SDK with FastAPI template on July 17, 2026. A template can remove setup work, but successful generation is not the production boundary that usually breaks. Task ownership is. Primary source: Vercel template, “OpenAI Agents SDK with FastAPI” . Before adopting any agent starter, I would add one vertical test: Alice must be able to create and cancel her task; Bob must not be able to read, stream, or cancel it—even if he guesses the task ID. State the cross-layer contract UI -> POST /tasks -> ownership row -> worker UI <- GET /tasks/:id <- authorization <- state UI <- event stream <- authorization <- events UI -> POST /tasks/:id/cancel -> authorization -> cancellation Use explicit states: queued -> running -> succeeded -> failed queued|running -> cancelling -> cancelled The database, API response, stream, and UI must agree on the same task and owner. Minimal schema create table tasks ( id text primary key , owner_id text not null , state text not null check ( state in ( 'queued' , 'running' , 'succeeded' , 'failed' , 'cancelling' , 'cancelled' )), created_at text not null , updated_at text not null , revision integer not null default 0 ); create table task_events ( task_id text not null , revision integer not null , kind text not null , payload text not null , primary key ( task_id , revision ) ); Do not derive ownership from a browser-supplied field. Resolve the authenticated principal on the server and store it when creating the task. FastAPI authorization seam from fastapi import Depends , FastAPI , HTTPException app = FastAPI () def current_user (): # Replace with verified session/JWT middleware. return { " id " : " alice " } def load_owned_task ( task_id : str , user = Depends ( current_user )): task = db_get_task ( task_id ) # application function if task is None or task [ " owner_id " ] != user [ " id " ]: # Avoid revealing whether another user's task exists. raise HTTPException ( status_code = 404 , detail = " task not found " )

2026-07-17 原文 →
AI 资讯

5 proyectos de agentes autónomos que revelan una infraestructura emergente

El ecosistema de agentes autónomos está evolucionando. Mientras la atención se centra en modelos y frameworks, empiezan a aparecer proyectos que cubren necesidades operativas básicas: comunicación, almacenamiento, finanzas. Aquí van cinco que vale la pena observar. 1. Apumail: el correo nativo para agentes Apumail ofrece direcciones de email que los agentes pueden crear y leer mediante una API REST plana. El contenido se negocia automáticamente: texto plano para agentes, HTML para humanos. Señal relevante: es el primer intento serio de darle a un agente un buzón de correo con el mismo estándar que usamos los humanos, sin adaptadores. Si los agentes empiezan a gestionar correspondencia, este tipo de servicio será indispensable. 2. RogerThat: chat entre agentes Una capa de mensajería en tiempo real diseñada para que agentes conversen entre sí. RogerThat no es un chat humano con bots, sino un canal donde los agentes coordinan acciones. Contexto: si varios agentes intervienen en un mismo workflow, necesitan un bus de eventos. RogerThat plantea que ese bus puede ser un chat, con las garantías de entrega y orden que eso implica. 3. DOBI: agente para DePIN y activos del mundo real Agent autónomo que opera sobre la cadena para gestionar infraestructuras físicas descentralizadas (DePIN). Ejecuta acciones on-chain a partir de decisiones tomadas por el modelo. Patrón: no es un simple bot de trading; apunta a mantenimiento de equipos, comprobación de sensores, distribución de incentivos. La frontera entre software y hardware se desdibuja. 4. CIDIF: financiamiento de I+D para agentes Plataforma que automatiza la presentación y seguimiento de solicitudes a fondos de innovación. El agente rellena formularios, adjunta documentación y trackea el estado. No obvio: la burocracia gubernamental es un entorno altamente estructurado (pocas decisiones abiertas, muchos campos fijos). Es un terreno ideal para agentes, aunque el ruido político lo opaque. 5. Orquesta: orquestación de flujos mu

2026-07-17 原文 →
开发者

Next.js App Router, there are always things that get forgotten. Let's anticipate its errors!

Ever felt like the Next.js App Router is a super cool superpower, but sometimes it feels like we accidentally left a few things behind during the setup? It happens to the best of us! Building with the App Router is incredibly powerful, giving us server first capabilities and an asik developer experience. Yet, with great power comes a few hidden quirks that often sneak past our radar until runtime. Let's dive deep and spot those common pitfalls together, making sure our Next.js apps run smoother than a freshly brewed cup of coffee. The Great Divide Understanding Client versus Server Components One of the biggest paradigm shifts with the App Router is the clear distinction between Client and Server Components. This isn't just a fancy label it dictates where your code runs and what it can access. Forgetting this fundamental difference is a top contender for unexpected errors. Server Components by Default We often forget that, by default, all components in the App Router are Server Components. This is awesome because it means zero client side JavaScript for many parts of our UI, leading to blazing fast initial loads and better SEO. Server Components can directly access server resources like databases, file systems, or environment variables without exposing them to the browser. They run once on the server, generate HTML, and send it to the client. When 'use client' Becomes Our Best Friend The 'use client' directive is like waving a flag saying, "Hey, this component needs to run in the browser!" We use it when a component relies on browser specific APIs like window or document , handles user interaction like click events, or uses React Hooks such as useState or useEffect . The common mistake here is forgetting to add 'use client' to components that need interactivity, leading to build errors or hydration mismatches when the server rendered HTML doesn't quite match what the client expects. We might also accidentally try to import a server side utility into a client compone

2026-07-17 原文 →
AI 资讯

Building AquaStat: Why We Started Tracking Data Center Water Usage

When people think about data centers, they usually think about servers, GPUs, electricity, and AI. Very few people think about water. That realization is what led me to start building AquaStat . Why AquaStat? Modern data centers consume significant amounts of water for cooling. Depending on the technology, climate, and workload, water usage can vary dramatically from one facility to another. Finding reliable information about that usage, however, is often difficult. Some facilities voluntarily publish sustainability reports. Others release only limited information. In many cases, information is scattered across government documents, environmental reports, local news articles, permits, or community discussions. I wanted to build a platform that could organize this information into something developers, researchers, journalists, and the public could actually use. What AquaStat Is AquaStat is an API-first platform focused on collecting, organizing, and analyzing information related to data center water usage. The long-term vision includes: A developer-friendly REST API OpenAPI documentation API key management A desktop control center A command-line interface Historical tracking Source attribution for collected information Transparent methodologies A modern TypeScript ecosystem Rather than hiding calculations, I want AquaStat to explain where information comes from and how conclusions are reached whenever possible. Technical Goals I'm designing AquaStat around several principles: API First Everything should be accessible through documented APIs before being exposed through a graphical interface. Strong Documentation Documentation should be treated as part of the product, not an afterthought. Reproducible Calculations Whenever AquaStat estimates or derives values, the methodology should be understandable and repeatable. Modern Tooling The project uses a modern TypeScript stack with an emphasis on maintainability, testing, and developer experience. Challenges One of the b

2026-07-16 原文 →
AI 资讯

From a Suno Track to a Hosted Music Video: Designing the Async Workflow

A music generator such as Suno can give a creator a finished track. It does not automatically give them a finished music video. The usual next step is a toolchain: Export the song as an MP3. Use an image model such as Nano Banana to establish the artist, character, location, or visual style. Turn those references into individual video shots with a model such as Veo , Seedance , or another video generator. Route performance close-ups through a lip-sync-capable step when the singer needs to match the vocals. Prepare lyrics or an SRT file, then align captions with the song. Retry failed shots, choose the usable takes, match aspect ratios, place the original track, and compose the final timeline. Upload the exported MP4 somewhere the application can reliably deliver it. Modern multimodal models reduce parts of this work, but an application still has to own the workflow around them. A full song is longer than one generated shot. Character consistency can drift. One failed scene should not require restarting everything. Subtitle timing, task state, retries, cost evidence, and final delivery still need product code. I wanted to see what this integration would look like if the application only had to submit the source material and track one job. For the concrete implementation below, I used the BeatAPI Music Video API . At the simplest level, the application provides: one MP3, WAV, AAC, or M4A file; one to seven reference images; optional creative direction; optional lip-sync and subtitle controls; output format and quality settings. The API returns a task ID immediately and delivers a hosted MP4 when the workflow succeeds. The default path does not require the developer to review or edit a storyboard. Before: song -> reference images -> generated shots -> lip sync -> subtitle timing -> retries -> editing -> hosting Behind one workflow API: audio + reference images + controls -> one async task -> hosted MP4 By the end of the tutorial, you will have a backend flow that: uplo

2026-07-16 原文 →
AI 资讯

How to Fix Email Not Working on Render (SMTP Blocked) 🚀

If you've deployed your application on Render and noticed that emails are not being sent, you're definitely not the only one. I recently faced this issue while deploying my project: https://rizzzler.onrender.com After spending hours debugging my code, checking environment variables, testing SMTP credentials, and reading logs, I finally discovered the real cause: The hosting environment was restricting outbound SMTP connections, preventing my application from connecting to the mail server. To solve this, I moved the email-sending functionality to Google Cloud , where the SMTP connection worked correctly. This article explains how I diagnosed the issue, common mistakes to avoid, and the solution that worked for me. Symptoms You might experience one or more of the following: Password reset emails are never received. OTP emails aren't delivered. Email verification doesn't work. Nodemailer throws timeout errors. SMTP connection fails. Everything works on localhost but fails after deployment. Typical errors include: ETIMEDOUT ECONNREFUSED Connection timeout Greeting never received Step 1: Verify Your SMTP Credentials Before assuming the issue is with Render, verify your SMTP configuration. Check that the following are correct: SMTP Host SMTP Port Username Password Even one incorrect character can prevent emails from sending. Step 2: Check Environment Variables Ensure all required environment variables are configured in Render. Example: SMTP_HOST=smtp.example.com SMTP_PORT=587 SMTP_USER=your-email@example.com SMTP_PASS=your-password Also remember to: Restart your Render service after updating variables. Never hardcode credentials in your source code. Step 3: Test Locally If your application sends emails successfully on your local machine but fails only after deployment, your application code is probably not the problem. This is an important clue. Step 4: Read the Logs Open your Render logs and look for SMTP-related errors. Common messages include: ETIMEDOUT ECONNREFUSED Co

2026-07-16 原文 →
开发者

Introducing Timezone Convert API — DST-aware IANA conversion at the edge

Just shipped Timezone Convert API — DST-aware IANA timezone conversion. Free, no key, CORS-enabled. Endpoints GET /convert?time=2026-07-16T09:00&from=Asia/Kolkata&to=America/New_York GET /now?zone=Europe/London GET /offset?zone=Pacific/Auckland GET /diff?a=Asia/Tokyo&b=Asia/Kolkata GET /zones (400+ IANA zones) Try it curl "https://timezone-convert.techtenstein.com/now?zone=Europe/London" Live at https://timezone-convert.techtenstein.com — OpenAPI 3.1 spec at /openapi.json . MIT.

2026-07-16 原文 →
AI 资讯

Manage Secret Scanning Custom Patterns as Code With a Safe REST Sync

GitHub's July 13, 2026 changelog lists REST API management for secret scanning custom patterns. That makes a reviewed configuration-as-code workflow possible. Primary source: GitHub Changelog archive, July 2026 . Follow the July 13 entry to the current REST documentation before implementation. The transport below is an unexecuted design. Endpoint paths, payload fields, permissions, pagination, and plan availability must come from the linked official API reference—not from guessed examples. Define the sync contract A safe synchronizer should: read desired patterns from version control; fetch the remote collection; match each pattern by a stable identity; emit create, update, unchanged, and delete actions; refuse deletion unless explicitly enabled; apply only after the plan is reviewed. patterns.json -> normalize -> diff remote -> plan.json -> approval -> apply Keep API-specific payloads opaque to the diff engine: { "patterns" : [ { "stableKey" : "internal-service-token-v1" , "remoteId" : "SET_AFTER_CREATION" , "payload" : { "REPLACE_WITH_DOCUMENTED_FIELD" : "REPLACE_WITH_REVIEWED_VALUE" } } ], "allowDelete" : false } Placeholders are deliberate. A secret detector's regex fields and matching semantics are security contracts and should never be invented from a blog post. Build a deterministic planner export function plan ( desired , current ) { const remote = new Map ( current . map ( x => [ x . id , x ])); const changes = []; for ( const item of desired . patterns ) { if ( ! item . remoteId ) { changes . push ({ action : " create " , key : item . stableKey }); continue ; } const found = remote . get ( item . remoteId ); if ( ! found ) throw new Error ( `Missing remote pattern ${ item . remoteId } ` ); const same = JSON . stringify ( canonical ( found )) === JSON . stringify ( canonical ( item . payload )); changes . push ({ action : same ? " unchanged " : " update " , key : item . stableKey }); remote . delete ( item . remoteId ); } for ( const orphan of remote . valu

2026-07-16 原文 →
AI 资讯

Coding agents can write your integration. They can't run it.

Digibee opens with a clear disclaimer: every team there uses Claude Code. This isn't a take from people who skipped the AI tooling revolution. It's an observation from people who shipped with it and ran into the same wall, repeatedly. That wall is enterprise integration. "Enterprise integration isn't a greenfield challenge. It's a completely different category of work, with completely different failure modes that coding agents weren't designed for." What coding agents are actually good at here They're useful for integration work under a narrow set of conditions: well-documented APIs, one-time tasks, low stakes, nothing in production at risk. A quick script to pull from a public endpoint? Great. A throwaway ETL job? Perfect. The problems start the moment an integration needs to be recurring, reliable, auditable, and maintained by someone other than the person who prompted it. The three structural gaps 1. They start from scratch every time. Pre-built connectors for enterprise systems like SAP, Salesforce, or NetSuite encode years of accumulated knowledge — how sequencing works, how idempotency is handled, where the quirks are. A coding agent reasons through all of that fresh on every run. It also suffers from the "lost in the middle" effect: when documentation gets long, LLMs drop content from the middle of their context window and fall back on training data. The more obscure the API, the more likely the generated code quietly fails under real load — not on deployment, but six months later when the CIO notices corrupted records. 2. They produce code, not infrastructure. Integrations need retry logic, failure recovery, credential management, audit trails, monitoring, and alerting. Coding agents produce none of that. You can prompt your way around it piecemeal — but now you're maintaining the integration and five hand-rolled infrastructure components. An agent optimised to iterate fast isn't optimised to fail safely. In production, a bad write means unprocessed payments

2026-07-15 原文 →
AI 资讯

Sync vs. Async Transcription: Which to Use (2026)

You've got a recording and you want text back. For years that meant one thing at AssemblyAI: submit the file, wait for the job to finish, get a transcript. Async. It's reliable, it's cheap, and for a huge range of workloads it's exactly right. But "wait for the job to finish" is doing a lot of work in that sentence. If your file is two minutes long and your user is staring at a spinner, waiting is the whole problem. That's the gap the Sync API fills — and it's why "which transcription path" is no longer a two-way question. This post is about the two ways to transcribe a recording : async and sync. (If you're deciding between recorded and live audio in the first place — streaming versus the rest — start with our guide to real-time vs batch transcription , then come back here to choose between the two non-streaming paths.) The one-sentence difference Async transcription hands you a job: you submit audio, the work happens in the background, and you collect the result later by polling or via a webhook. Sync transcription hands you an answer: you POST a short clip and the transcript comes back in the same HTTP response — no job to track, no callback to wait for. Everything else follows from that. Async is built for throughput and depth on files of any length. Sync is built for speed on short files, when a person or an agent is waiting on the other end. How fast can each actually go? This is the question that usually settles it, so let's be concrete. Async processes the whole file and returns a single complete transcript, typically in seconds to a few minutes depending on file length and load. Crucially, it bills on audio duration ($0.21/hr on Universal-3.5 Pro), so a 30-minute file costs the same whether it comes back in 20 seconds or two minutes. You're optimizing for cost and completeness, not for the clock. Sync is built to return a transcript for a short clip almost immediately — roughly 134ms p50 — in one request/response, with no polling and no webhooks. It's price

2026-07-15 原文 →
AI 资讯

Backward Compatibility: A Practitioner's Guide to Evolving APIs Without Breaking Clients

How to version REST endpoints, evolve GraphQL schemas, and ship mobile updates — without leaving existing users behind. Why It Matters Every deployed API is a contract. Every mobile binary installed on a user's phone is a snapshot of that contract. The moment you change a response shape, rename a field, or remove an endpoint, you risk breaking clients you cannot force-update. Backward compatibility is not about avoiding change. It is about managing change so that existing consumers continue to work while the system evolves underneath them. This article covers three layers: REST API versioning , GraphQL schema evolution , and mobile app compatibility (React Native & Flutter). Each section delivers concrete patterns and production-ready code. Part I — REST APIs The Versioning Decision REST APIs have four common versioning strategies. Each comes with tradeoffs: Strategy Example Pros Cons URI path /api/v1/users Simple, cacheable, widely understood Implies the resource itself changed; cache duplication Query parameter /api/users?version=1 Easy to implement, can default to latest Complicates routing and cache keys Custom header X-API-Version: 1 Keeps URIs clean Hard to test in browsers, invisible in logs Content negotiation Accept: application/vnd.app.v2+json Fine-grained, per-resource versioning Complex to test, requires custom media types Rule of thumb: Use URI versioning for public APIs. Use header-based versioning for internal services where you control all clients. Non-Breaking vs. Breaking Changes Not every change requires a new version: ✅ Non-breaking (no version bump needed): - Adding a new field to a response - Adding a new optional query parameter - Adding a new endpoint - Returning a new enum value (if clients handle unknowns) ❌ Breaking (requires a new version): - Removing or renaming a field - Changing a field's type (string → number) - Making an optional parameter required - Changing the response structure Pattern: Side-by-Side Versioning When a breaking cha

2026-07-15 原文 →
AI 资讯

I Ran 10 AI Coding Models Through 5 Tasks: A Data Scientist's Take

I Ran 10 AI Coding Models Through 5 Tasks: A Data Scientist's Take I'll be honest — I went into this expecting a clear winner. I came out with a scatter plot, three regressions, and a deeper appreciation for why "best" is the most dangerous word in machine learning. Over the past three weeks I've been grinding through prompts with ten different LLMs, all routed through the same endpoint, scoring every output on a 1–10 rubric that I tried very hard not to bias. The pricing data is pulled directly from the provider pages. The scores are mine. If you disagree with a score, you're probably right — n=1 per task per model is a laughably small sample size, and I say that as someone who publishes papers with bigger samples. But trends still emerged. Let me walk you through what I found. The Lineup Before I touch a single benchmark, here's the cast. I've grouped them by family so you can see the obvious concentration in the open-source Chinese ecosystem, which personally I find fascinating — three of the top five are DeepSeek or Qwen variants. # Model Provider Output $/M Category 1 DeepSeek V4 Flash DeepSeek $0.25 General (strong code) 2 DeepSeek Coder DeepSeek $0.25 Code-specialized 3 Qwen3-Coder-30B Qwen $0.35 Code-specialized 4 DeepSeek V4 Pro DeepSeek $0.78 Premium general 5 DeepSeek-R1 DeepSeek $2.50 Reasoning (code thinking) 6 Kimi K2.5 Moonshot $3.00 Premium general 7 GLM-5 Zhipu $1.92 Premium general 8 Qwen3-32B Qwen $0.28 General purpose 9 Hunyuan-Turbo Tencent $0.57 General purpose 10 Ga-Standard GA Routing $0.20 Smart routing One quick note on Ga-Standard — it's a routing layer that picks a backend model per request. So the score fluctuates. I averaged across runs. How I Tested Five prompts. Each one designed to probe a different cognitive layer: Function implementation — flatten a nested list recursively in Python Bug fix — chase down an async/await race condition in JavaScript Algorithm — Dijkstra's shortest path in TypeScript with proper types Code review — sec

2026-07-14 原文 →
AI 资讯

Stop Writing try/catch in Every Controller

When I first started building APIs with Express.js, every async controller looked the same. I would write a try block, perform some database operations, and then write a catch block that called next(error) . It worked, so I copied the same pattern into every controller. One controller became ten. Ten became fifty. Eventually, I realized that half of my controller code wasn't actually business logic, it was just repetitive error handling. That's when I discovered the Async Handler pattern. The Problem A typical Express controller often looks like this: export const getUser = async ( req , res , next ) => { try { const user = await User . findById ( req . params . id ); if ( ! user ) { throw new Error ( " User not found " ); } res . json ( user ); } catch ( error ) { next ( error ); } }; There's nothing wrong with this code. The problem is that every async controller ends up looking exactly the same. Every file contains: try, catch and next(error) over and over again. Besides being repetitive, it's also easy to forget. Miss one try-catch block, and Express won't automatically catch errors thrown inside async functions. What Is an Async Handler? An async handler is a small wrapper function that automatically catches errors from async controllers. Instead of every controller handling its own errors, the wrapper does it for you. A Simple Analogy Imagine an office where every employee has to stop working whenever someone rings the front door. Besides doing their own job, they also have to greet every visitor. This quickly becomes repetitive and inefficient. Instead, the company hires a receptionist to handle every visitor. Now the employees can focus on their actual work while the receptionist takes care of the door. An async handler works the same way. Controllers focus on handling requests, while the async handler catches errors and passes them to Express's error handler. Without an Async Handler export const createUser = async ( req , res , next ) => { try { const user

2026-07-14 原文 →
AI 资讯

A Practical Guide to Proxies for Web Scraping (with Python examples)

If you have written more than a couple of scrapers, you already know the pattern. The first few hundred requests fly through. Then responses slow down, you start seeing 429 Too Many Requests , a captcha wall appears, and finally the target just returns empty pages or a hard 403 . Your code did not change. Your IP did. Scraping at any real volume is less about parsing HTML and more about managing where your requests come from. This post is a practical walk-through of how proxies fit into a scraping pipeline: why a single IP fails, what proxy types actually matter, how rotation works, and how to wire it all up in Python with requests , aiohttp , and Scrapy. There is code you can copy, plus the mistakes that cost me the most time. Why one IP is never enough Every site you scrape sees the same thing: a stream of requests from one address, arriving faster and more regularly than a human ever would. Anti-bot systems are built to spot exactly that. The signals they use are boring but effective: Request rate per IP. Too many hits in a short window trips a rate limiter. Volume over time. Even a slow scraper eventually stands out if every request comes from the same address for hours. Behavioral fingerprint. No mouse, no scroll, identical headers, requests in perfect intervals. Reputation. Datacenter ranges that have been abused before are pre-flagged. You can soften some of these with headers, delays, and a real browser, but there is a ceiling. Once a single IP has made enough requests, it gets throttled or blocked regardless of how polite you are. The only way past that ceiling is to spread requests across many addresses, so no single one crosses the threshold. That is the entire job of a proxy pool. The proxy landscape, minus the marketing Providers love to complicate this. For scraping, the distinctions that actually change your results are these: Shared vs private. Shared proxies are handed to many customers at once. You inherit everyone else's behavior, so an address ca

2026-07-14 原文 →
AI 资讯

Diagnosing Cloudflare Blocks Before Changing Your Scraper

A scraper fails, someone swaps the User-Agent, someone else adds a proxy, then the job starts passing locally but fails again in CI. That usually happens because Cloudflare did not block “scraping” as one thing. It evaluated several signals, and each failure needs a different fix. This is about authorized automation: your own sites, customer-approved workflows, testing, monitoring, data access you are allowed to perform. If you do not have permission to automate against a site, changing fingerprints or rotating IPs does not make it okay. Start with the failure you actually see Cloudflare failures often get collapsed into “403”, but the page body matters. Common cases: Error 1020 : usually an access denied page from a Cloudflare rule or bot score decision. The HTTP status may still be 403, so inspect the HTML. 403 without a 1020 page : often IP reputation, firewall rules, geo restrictions, or an auth problem. 429 : rate limit exhaustion. Slowing down can help here, but it will not fix a fingerprint problem. Endless Just a moment... page : your client did not complete the browser-side challenge. CAPTCHA or Turnstile loop : Cloudflare still considers the session borderline after earlier checks. Add classification before you add workarounds. Even a basic classifier saves time: import time import requests CLOUDFLARE_MARKERS = { " 1020 " : " cloudflare_access_denied " , " Just a moment " : " cloudflare_js_challenge " , " cf-turnstile " : " cloudflare_turnstile " , " cf-error-code " : " cloudflare_error_page " , } def classify_response ( resp : requests . Response ) -> str : body = resp . text [: 5000 ] if resp . status_code == 429 : return " rate_limited " for marker , label in CLOUDFLARE_MARKERS . items (): if marker in body : return label if resp . status_code == 403 : return " forbidden_unknown " return " ok " if resp . ok else f " http_ { resp . status_code } " def get_with_backoff ( url : str , max_attempts = 4 ): for attempt in range ( max_attempts ): resp = request

2026-07-14 原文 →
AI 资讯

Getting the public IP in PHP — no dependencies, no API key

Getting the public IP in PHP — no dependencies, no API key PHP is still one of the most widely deployed server-side languages, running a significant share of the web's backend code. If you're building a PHP application that needs the public IP address — for geolocation, DDNS, diagnostics, or country detection — this article covers the common patterns using IPPubblico.org : free, no key, HTTPS, JSON and plain text endpoints. Use case 1 — Your server's own public IP (one-liner) The simplest case: a PHP script that needs to know its own public IP. <?php $ip = trim ( file_get_contents ( 'https://ipv4.ippubblico.org/' )); echo $ip ; // 203.0.113.42 file_get_contents works if allow_url_fopen is enabled (it is by default on most servers). If not, use cURL (see below). Use case 2 — With cURL (recommended for production) file_get_contents has no timeout control and minimal error handling. For production code, cURL is better: <?php function getPublicIP (): ?string { $ch = curl_init ( 'https://ipv4.ippubblico.org/' ); curl_setopt_array ( $ch , [ CURLOPT_RETURNTRANSFER => true , CURLOPT_TIMEOUT => 5 , CURLOPT_FOLLOWLOCATION => true , CURLOPT_SSL_VERIFYPEER => true , ]); $response = curl_exec ( $ch ); $httpCode = curl_getinfo ( $ch , CURLINFO_HTTP_CODE ); curl_close ( $ch ); if ( $response === false || $httpCode !== 200 ) { return null ; } return trim ( $response ); } $ip = getPublicIP (); echo $ip ?? 'Unavailable' ; Use case 3 — Full geolocation data When you need country, city, ISP and timezone in addition to the IP: <?php function getIPInfo ( ?string $ip = null ): ?array { $url = 'https://ippubblico.org/?api=1' ; if ( $ip !== null ) { $url . = '&ip=' . urlencode ( $ip ); } $ch = curl_init ( $url ); curl_setopt_array ( $ch , [ CURLOPT_RETURNTRANSFER => true , CURLOPT_TIMEOUT => 5 , CURLOPT_SSL_VERIFYPEER => true , ]); $response = curl_exec ( $ch ); $httpCode = curl_getinfo ( $ch , CURLINFO_HTTP_CODE ); curl_close ( $ch ); if ( $response === false || $httpCode !== 200 ) { retur

2026-07-14 原文 →
AI 资讯

I Wish I Ran the Numbers on Open Source AI APIs Sooner

I Wish I Ran the Numbers on Open Source AI APIs Sooner Three months ago I would have told you self-hosting was the obvious move. "Open source means free, right?" I said that to a client while quoting them $3,500 for a GPU server setup. They smiled politely and went with someone else. That rejection sent me down a rabbit hole I wish I'd started years earlier, because the actual math — not the vibes-based math freelancers like me tend to do — completely flips the script. If you're running a solo practice or a tiny shop, you probably bill every minute of GPU babysitting straight out of your own pocket. That's time you could be shipping features, pitching clients, or — if we're being honest — sleeping. So let me walk you through what I learned the hard way, with all the pricing left exactly where it belongs. The Open Source Lineup That Actually Matters Right Now When I started this research, I assumed "open source AI API" was an oxymoron. If you're calling an API, somebody owns the server, so what's even the point of being open? Turns out the point is massive: open-weight models accessible through an API give you the pricing transparency of self-hosting without the DevOps funeral you're planning for your weekends. Here's the pricing matrix I put together from Global API's public rates. These are output token prices (input is usually cheaper), and yes — they're shockingly low compared to GPT-4o territory. Model License Output Price Self-Host Range DeepSeek V4 Flash Open weights $0.25/M $500-2,000/mo DeepSeek V3.2 Open weights $0.38/M $800-3,000/mo Qwen3-32B Apache 2.0 $0.28/M $400-1,500/mo Qwen3-8B Apache 2.0 $0.01/M $200-800/mo Qwen3.5-27B Apache 2.0 $0.19/M $300-1,200/mo ByteDance Seed-OSS-36B Open weights $0.20/M $500-2,000/mo GLM-4-32B Open weights $0.56/M $400-1,500/mo GLM-4-9B Open weights $0.01/M $200-800/mo Hunyuan-A13B Open weights $0.57/M $300-1,000/mo Ling-Flash-2.0 Open weights $0.50/M $300-1,000/mo Look at Qwen3-8B and GLM-4-9B at $0.01/M output tokens. A mi

2026-07-14 原文 →
AI 资讯

Speed Test: I Found AI APIs 99% Cheaper Than Premium

Here's the thing: speed Test: I Found AI APIs 99% Cheaper Than Premium I have a confession: I've been overpaying for AI APIs for years. Like, embarrassingly overpaying. When I finally sat down and actually benchmarked 15 different models on speed and cost, I couldn't believe what I found. Some of the fastest models out there cost literal pennies per million tokens. Here's the thing — if you're still defaulting to whatever the big labs are pushing, you're leaving serious money on the table. So I spent a week running tests through Global API's infrastructure, hitting endpoints from multiple regions, and crunching numbers until my eyes hurt. What I discovered genuinely surprised me. Check this out: there's a model that pushes 80 tokens per second and costs $0.15 per million output tokens. Compare that to premium options charging $3.00/M and you'll understand why I had to write this down. Let me walk you through everything I found. Why I Even Started This Whole Thing My monthly AI bill got out of control. I'm running a few production apps that do text generation, summarization, and chat, and my December bill made me physically flinch. I knew there had to be faster, cheaper models hiding in the ecosystem — I just hadn't taken the time to actually measure them properly. That's the whole reason I ran these benchmarks. Not for clout, not for content marketing. Pure self-interest. I wanted to know where the actual sweet spots are. Where you get the best speed-per-dollar ratio. Where you can save 70%, 80%, even 99% without tanking your user experience. What I found was honestly kind of shocking. My Testing Setup (For the Nerds) I kept the methodology tight and consistent. Here's exactly how I ran everything: Date: May 20, 2026 Test regions: US East (Ohio) and Asia (Singapore) Prompt: "Explain recursion in 200 words" Output target: ~150 tokens per run Iterations: 10 runs each, averaged the results Streaming: Enabled via SSE Base URL: https://global-apis.com/v1 I measured two k

2026-07-14 原文 →
AI 资讯

I built a tool that checks whether ChatGPT recommends your brand (Python + Apify)

Your customers have stopped Googling "best note-taking app." They're asking ChatGPT, Perplexity, and Gemini instead — and getting back a short list of three or four products. If your brand isn't on that list, you're invisible, and unlike a Google ranking you can't even see where you stand. That's the problem I set out to measure. This post is the build breakdown: five AI answer engines, one uniform result shape, a mention-detection core that doesn't lie to you, and the honest gotchas I hit around cost and billing. The whole thing runs as a paid Apify Actor written in async Python. The niche has a name now — GEO (Generative Engine Optimization) or AEO (Answer Engine Optimization). Think SEO, but the search engine is a language model and the "ranking" is whether you get named in the answer. The core question Give the tool a brand, its competitors, and the buyer-intent questions your customers actually type: { "brand" : "Notion" , "competitors" : [ "Obsidian" , "Coda" , "Evernote" ], "prompts" : [ "best note taking app for students" , "Notion vs Obsidian which should I use" ], "engines" : [ "perplexity" , "chatgpt" , "gemini" , "claude" , "aiOverview" ], "samplesPerPrompt" : 3 } It asks each engine each prompt (several times, because LLM answers vary run-to-run), then analyzes every answer for: were you mentioned, how early, were you recommended or just listed, what's the sentiment, who else got named, and — the part incumbents skip — which domains each engine cited. That last one is the actionable output: it tells you which websites the AI trusts for your category, i.e. where you need coverage. Architecture: one shape to rule them all The trick that keeps the whole thing sane is that every engine adapter — whether it's a clean REST API or a messy HTML scrape — returns the exact same record shape : { " engine " : " perplexity " , " prompt " : " best note taking app for students " , " sampleIndex " : 1 , " responseText " : " ... " , " citations " : [{ " url " : " ... "

2026-07-14 原文 →
AI 资讯

Audit-log every email your AI agent sends

When an autonomous agent gets an email address of its own, the first question your security team asks isn't "can it send mail?" It's "can you prove, six months from now, exactly what it said and to whom?" That's a different problem from "does it work." A demo that fires off a few support replies looks great in a sprint review. But the moment a real customer says "your bot promised me a refund," or a regulator asks for the complete record of what an automated system told a data subject, you need a defensible trail — an immutable record of every outbound and inbound message the agent touched, captured outside the mailbox the agent can also delete from. I work on the Nylas CLI, so the terminal commands below are the exact ones I reach for. But the architectural point here is provider-agnostic and it's the part most "AI email" tutorials skip: the live mailbox is not your audit log. It's mutable, it has retention limits, and the same agent that sends mail can also trash it. If your only record of what the agent did lives in the inbox, you don't have an audit trail — you have a working copy. What "audit-log everything" actually means There are two stores in this design, and keeping them separate is the whole point. The live mailbox — the Agent Account grant. Messages flow in and out here. It's queryable, it's real-time, and it's mutable . Flags change, messages move folders, things get trashed. On the free plan it's also retention-limited: 30 days for the inbox, 7 days for spam. The audit store — your system. An append-only, write-once log keyed by message_id and thread_id . Nothing in it is ever updated or deleted in normal operation. This is the record you hand a reviewer. The audit store is the thing you build. Nylas gives you the two capture points — the send response and the inbound webhook — but the immutability is your responsibility. That means a WORM (write-once-read-many) object store, an append-only table with no UPDATE / DELETE grant for the app role, or a has

2026-07-14 原文 →