惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

阮一峰的网络日志
阮一峰的网络日志
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Blog — PlanetScale
Blog — PlanetScale
Jina AI
Jina AI
MyScale Blog
MyScale Blog
N
Netflix TechBlog - Medium
月光博客
月光博客
云风的 BLOG
云风的 BLOG
T
The Blog of Author Tim Ferriss
博客园_首页
GbyAI
GbyAI
The Cloudflare Blog
博客园 - 叶小钗
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
MongoDB | Blog
MongoDB | Blog
Y
Y Combinator Blog
博客园 - 三生石上(FineUI控件)
量子位
博客园 - Franky
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
人人都是产品经理
人人都是产品经理
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
M
MIT News - Artificial intelligence
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
I
InfoQ
Google DeepMind News
Google DeepMind News
S
SegmentFault 最新的问题
大猫的无限游戏
大猫的无限游戏
Apple Machine Learning Research
Apple Machine Learning Research
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Last Week in AI
Last Week in AI
J
Java Code Geeks
腾讯CDC
aimingoo的专栏
aimingoo的专栏
C
Check Point Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Vulnerabilities – Threatpost
S
Schneier on Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
L
Lohrmann on Cybersecurity
S
Securelist
F
Full Disclosure
Cisco Talos Blog
Cisco Talos Blog
小众软件
小众软件
The GitHub Blog
The GitHub Blog

Hacker News - Newest: "AI"

AI can't read an investor deck AI as an attorney? Student uses ChatGPT, Gemini to sue UW over alleged racial discrimination Hacking MCP Servers in AI Systems – The Rug Pull: Tool Changes After Approval GitHub - MeepCastana/KubeezCut: Free Web based video editor GitHub - GenAI-Gurus/awesome-eu-ai-act: Curated tools, official sources, OSS, templates, and guides for EU AI Act compliance. Can AI judge journalism? A Thiel-backed startup says yes, even if it risks chilling whistleblowers Coming soon: 10 Things That Matter in AI Right Now DARPA built an AI to fact-check enemy weapons claims What explains heterogeneity in AI adoption? When AI Meets Muscle: Context-Aware Electrical Stimulation Promises a New Way to Guide Human Movements - Department of Computer Science AI Changed How We Build. It Did Not Change What Matters. Linux rules on using AI-generated code - Copilot is OK, but humans must take 'full responsibility for the… Meta spins up AI version of Mark Zuckerberg to engage with employees Code Mode: Let Your AI Write Programs, Not Just Call Tools | TanStack Blog GitHub - Delavalom/graft: Go framework for building AI agents. Type-safe tools, multi-provider (OpenAI, Anthropic, Gemini, Bedrock), zero vendor SDKs. India's TCS tops estimates, says new AI models did not dent services demand Gen Z's fading AI hype Strong feeling: we are in a folded AI reality GitHub - machinarii/total-recall-catalog: A reference catalog of latest knowledge retrieval, memory & RAG systems GitHub - mensfeld/code-on-incus: Give each AI agent its own isolated machine with root, Docker, and systemd. Active defense detects and stops threats automatically.. Quantization, LoRA, and the 8% Problem: Benchmarking Local LLMs for Production AI Iran war: We spoke to the man making Lego-style AI videos that experts say are powerful propaganda Powell, Bessent discussed Anthropic's Mythos AI cyber threat with major U.S. banks GitHub - immartian/bellamem: Persistent belief-graph memory for AI agents. Retrieves decisive context by importance — not recency, not RAG, not /compact. recursive-mode: The Repo-Native Operating System for AI Engineering After the attack on Sam Altman's home, will AI CEO's go on the offensive? The biggest advance in AI since the LLM Opus 4.6 vs GPT 5.4 One Prompt Unity World Generation Test “AI polls” are fake polls Client Challenge Can AI be a 'child of God'? Inside Anthropic's meeting with Christian leaders How to Switch AI Chatbots and Why You Might Want To GitHub - MattMessinger1/agentic_refund_guardrail: Safe refund policy layer for AI agents — Python + TypeScript. Same behavior, shared tests. Adam/papers/emergent_values_whitepaper.md at master · strangeadvancedmarketing/Adam Ask HN: How do you stop playing 20 questions with your AI coding tools How far can automation and AI support psychotherapy? - @theU GitHub - stagas/rtdiff: realtime git diff gui and AI-assisted commits A Mac Studio for Local AI — 6 Months Later A History of the Early Years of AI at the University of Edinburgh Why AI Coding Tools Still Feel Stuck on Localhost MSN AI Datacenters Are Becoming Strategic Targets twitter.com Penn Researchers Use AI to Surface Unreported GLP-1 Side Effects in Reddit Posts Show HN: MoodSense AI (ML and FastAPI and Gradio, Deployed on Hugging Face) Moodsense Ai - a Hugging Face Space by aman179102 AI models are terrible at betting on soccer—especially xAI Grok GitHub - xialeistudio/echoic GitHub - HimashaHerath/github-dev-wrapped: AI-powered weekly GitHub activity reports deployed to GitHub Pages GitHub - alejandrobalderas/claude-code-from-source: Architecture, patterns & internals of Anthropic's AI coding agent — reverse-engineered from source maps AI and Tech brief: Ireland ascendant GitHub - Titovilal/context0: Context0 - Never Surrender Training for a Marathon with an AI Coach: What Worked and What Didn't Cyber Pulse: Agentic Intel - Apps on Google Play I Built an AI PR Reviewer That Catches Bugs by Not Looking for Bugs Gen Z workers are so fearful AI will take their job they’re intentionally sabotaging their company’s AI rollout | Fortune How AI Is Reimagining the Game of Golf–For Both Players and Courses GitHub - nattergabriel/reseed: A CLI tool for managing and distributing agent skills across projects Is SVG the final frontier? My AI workflow evolved from prompts to a near-autonomous workflow MLSharp Help - 3DGS Viewer & Generator I put my cognitive field based AI's runtime on GitHub Is Numble the first AI-proof game? A3: Kubernetes for autonomous AI agent fleets | Emergent Principles Deepali Vyas ("The Elite Recruiter") GitHub - msmarkgu/RelayFreeLLM: A restful API designed to route user prompts to various AI model providers. Unionized ProPublica staff are on strike over AI, layoffs, and wages Unleashing the Advantage of Quantum AI We're heading for an AI-fueled 'dementia crisis,' brain scientist warns The AI-Assisted Breach of Mexico's Government Infrastructure [pdf] GitHub - stef41/lmscan: 🔍 Detect AI-generated text and fingerprint which LLM wrote it. Open-source GPTZero alternative. Zero dependencies, works offline. MSN GitHub - visionscaper/collabmem: Enabling long-term collaboration with Agentic AI - building up episodic and world model memory over time with in-context awareness We gave an AI a 3 year retail lease in SF and asked it to make a profit | Andon Labs AI Code is Hollowing Out Open Source, and Maintainers are Looking the Other Way What leaked "SteamGPT" files could mean for the PC gaming platform's use of AI AI is the boss at this retail store. What could go wrong? GitHub - Wuzu11517/agentic-proxy: Local proxy meant to help reduce With Drones, Geophysics and ArtificiaI Intelligence, Researchers Prepare to Do Battle Against Land Mines A Single Operator, Two AI Platforms, Nine Government Agencies: The Full Technical Report 在 Steam 上购买 FriedrichAI: Offline AI 立省 10% GitHub - inevolin/resume-cli: Hit Claude usage limits? Resume any AI coding session elsewhere. Switch tools at zero friction. GitHub - atripati/ark: AI Runtime Kernel — a context operating system for AI agents. Eliminates tool bloat, loads only what’s needed, and gives LLMs their reasoning space back. How to Build a Secure AI PR Reviewer with Claude, GitHub Actions, and JavaScript This Startup Wants You to Pay Up to Talk With AI Versions of Human Experts Intel Arc Pro B70 Brings 32GB VRAM to Local AI for $949 WordPress 7.0: The Good, the AI, and the Still Missing AI on the couch: Anthropic gives Claude 20 hours of psychiatry IatroBench: Pre-Registered Evidence of Iatrogenic Harm from AI Safety Measures AI Agents Know About Supabase. They Don't Always Use It Right. The history and future of AI at Google, with Sundar Pichai Inside an AI‑enabled device code phishing campaign How Meta Used AI to Map Tribal Knowledge in Large-Scale Data Pipelines AI for Systems: Using LLMs to Optimize Database Query Execution Forecasting the Economic Effects of AI Introducing Tinker: Play with AI, bring your ideas to life AI sheds light on an ancient gaming mystery People really hate AI but not as much as Iran—or Democrats | Fortune What is an AI Product Engineer? Phoebe Gates wants her $185 million AI startup to succeed with 'no ties to my privilege or my last name': 'I have a chip on my shoulder' | Fortune
GitHub - salimassili62-afk/ai-costguard: Local-first runtime safety layer for AI agents that blocks runaway costs, loops, retries, and budget overruns before provider API calls execute.
salim2006 · 2026-06-16 · via Hacker News - Newest: "AI"

npm version AI CostGuard Pro

AI CostGuard is a local-first runtime safety layer for AI agents that prevents runaway costs, loops, retries, and budget explosions before API calls execute. It wraps OpenAI-compatible clients and function-style SDK calls, estimates request cost locally, blocks budget overruns, detects repeated prompts, emits structured events, and exposes CLI checks plus a local dashboard.

It is local-first. It does not include a SaaS control plane, cloud dashboard, proxy gateway, telemetry service, billing reconciliation service, or hard security boundary.

What AI CostGuard Does

  • Checks selected AI SDK calls before they execute.
  • Estimates request cost from model pricing, prompt text, and reserved output tokens.
  • Blocks unknown models unless explicit pricing is supplied.
  • Blocks budget overruns, repeated prompt loops, retry storms, and max-step overruns.
  • Emits structured errors and local events your app can handle.

What AI CostGuard Does Not Do

  • It does not call providers for real-time pricing.
  • It does not reconcile provider invoices or replace provider billing alerts.
  • It does not provide auth, API-key security, or a hard security boundary.
  • It does not run a hosted dashboard, SaaS backend, or cloud telemetry service.
  • It does not guarantee exact tokenizer parity with OpenAI, Anthropic, or other providers.

Install

npm install @salimassili/ai-costguard

Quick Start

import OpenAI from 'openai';
import { guard, GuardError } from '@salimassili/ai-costguard';

const openai = guard(new OpenAI({ apiKey: process.env.OPENAI_API_KEY }), {
  budget: 5,
  maxSteps: 50,
  scope: { projectId: 'my-app' },
});

try {
  const response = await openai.chat.completions.create({
    model: 'gpt-4o-mini',
    messages: [{ role: 'user', content: 'Write a short summary.' }],
    max_tokens: 200,
  });

  console.log(response.choices[0]?.message?.content);
} catch (error) {
  if (error instanceof GuardError) {
    console.error(error.code, error.message, error.context);
  } else {
    throw error;
  }
}

Before / After

Without AI CostGuard:

await openai.chat.completions.create(request);

With AI CostGuard:

const openai = guard(new OpenAI({ apiKey: process.env.OPENAI_API_KEY }), {
  budget: 5,
  maxSteps: 50,
  scope: { projectId: 'agent-api', sessionId: runId },
});

await openai.chat.completions.create(request);

What It Guards

By default AI CostGuard evaluates these SDK method paths:

  • chat.completions.create
  • completions.create
  • responses.create
  • messages.create

Other client methods are passed through without cost checks. To protect a custom client method:

const client = guard(customClient, {
  budget: 2,
  guardedMethods: ['agent.run'],
  pricingOverrides: [
    {
      model: 'internal-model',
      inputPer1kTokens: 0.001,
      outputPer1kTokens: 0.002,
      lastUpdated: '2026-06-07',
      source: 'internal pricing sheet',
    },
  ],
});

For function-style SDKs such as Vercel AI SDK adapters, LangChain wrappers, or agent runners:

import { guardFunction } from '@salimassili/ai-costguard';

const guardedGenerateText = guardFunction(generateTextAdapter, {
  budget: 1,
  scope: { projectId: 'chatbot' },
});

await guardedGenerateText({
  model: 'gpt-4o-mini',
  prompt: 'Answer the user in one paragraph.',
  max_tokens: 200,
});

Decisions And Errors

Blocked requests throw GuardError before the provider method is called.

try {
  await openai.chat.completions.create(request);
} catch (error) {
  if (error instanceof GuardError) {
    console.log(error.code);
    console.log(error.metadata);
  }
}

Current runtime block codes:

  • UNKNOWN_MODEL
  • BUDGET_EXCEEDED
  • MAX_STEPS_EXCEEDED
  • LOOP_DETECTED
  • RETRY_STORM_DETECTED

Configuration

guard(client, {
  budget: 10,
  maxSteps: 100,
  behaviorAnalysis: true,
  maxHistory: 32,
  historyTtlMs: 5 * 60 * 1000,
  loopDetection: {
    similarityThreshold: 0.85,
    minHistorySize: 2,
    windowSize: 5,
  },
  retryThreshold: 2,
  scope: {
    projectId: 'production-api',
    userId: 'optional-user',
    sessionId: 'optional-agent-run',
  },
  guardedMethods: ['chat.completions.create', 'responses.create'],
  pricingOverrides: [],
  webhooks: {
    slack: process.env.SLACK_WEBHOOK,
    discord: process.env.DISCORD_WEBHOOK,
    retries: 2,
    timeoutMs: 1500,
  },
  eventLogPath: '.ai-costguard/events.jsonl',
  eventLogPrompt: 'none',
});

scope isolates budgets and behavior history. If no scope is supplied, the guard uses one process-local default scope.

Loop Detection Tuning

Default loop detection uses character trigram cosine similarity with:

  • loopDetection.similarityThreshold: 0.85

  • loopDetection.minHistorySize: 2

  • loopDetection.windowSize: 5

  • Higher threshold, such as 0.95: fewer false positives, but near-duplicate loops can slip through.

  • Lower threshold, such as 0.75: catches looser repeats, but unrelated prompts can be blocked.

  • Higher minHistorySize: waits for more repeated prompts before blocking.

  • Lower minHistorySize: blocks faster, but is more aggressive.

  • Smaller windowSize: compares fewer recent prompts, reducing old-history false positives.

  • Larger windowSize: compares more history, improving catch rate but increasing false-positive risk in repetitive workflows.

const openai = guard(client, {
  budget: 5,
  loopDetection: {
    similarityThreshold: 0.9,
    minHistorySize: 3,
    windowSize: 6,
  },
  scope: { sessionId: 'agent-run-123' },
});

Legacy loopSimilarityThreshold and loopMinRepeats config fields are still accepted, but loopDetection takes precedence. Loop detection is heuristic. Expect false positives and false negatives, especially for short prompts, templated prompts, and prompts that share a lot of boilerplate.

Accounting Semantics

AI CostGuard is a pre-call estimator, not a billing ledger.

  • attemptedCost: estimated cost of every guarded attempt, including blocked attempts.
  • totalCost: estimated cost of allowed calls.
  • blockedCost: estimated cost stopped before provider execution.
  • actualCost: provider-reported usage cost when the response includes recognizable usage fields.

Budget decisions use estimated allowed cost. Actual usage is recorded for observability but does not rewrite earlier decisions.

Pricing

Known model pricing comes from built-in registry entries, runtime registrations, or per-guard overrides. Unknown models are blocked by default.

Pricing last updated: 2026-06-07. Provider pricing changes; AI CostGuard does not fetch real-time pricing. Override pricing manually when provider pages or your contract pricing differ from the built-ins.

import { getPricingMeta, registerPricing } from '@salimassili/ai-costguard';

registerPricing([
  {
    model: 'my-company-model',
    inputPer1kTokens: 0.001,
    outputPer1kTokens: 0.002,
    lastUpdated: '2026-06-07',
    source: 'internal',
  },
]);

console.log(getPricingMeta('gpt-4o-mini'));

Check built-in pricing freshness from CI or a release script:

aifw pricing --check-stale --days 30

The command exits 0 when all registry entries are within the threshold and 1 when one or more entries are stale.

If you intentionally want fallback pricing for unknown models:

guard(client, {
  budget: 5,
  unknownModelPolicy: 'fallback',
  unknownModelPricing: {
    model: 'fallback',
    inputPer1kTokens: 0.001,
    outputPer1kTokens: 0.002,
    lastUpdated: '2026-06-07',
    source: 'application fallback',
  },
});

Pricing changes frequently. Verify provider pricing before production use and override entries when needed.

Token Counting Accuracy

AI CostGuard ships with a dependency-free token estimator so the root package stays small. It warns once per model/scope when approximate counting is used:

[ai-costguard] Using approximate token counting for model: gpt-4o-mini. Register an exact tokenizer via registerTokenizer() for production use.

For production budgets that need tighter input-token estimates, register a provider tokenizer:

import { registerTokenizer } from '@salimassili/ai-costguard';

registerTokenizer('gpt-4o-mini', (text) => {
  return myTokenizer.encode(text).length;
});

registerTokenizer(/^claude-/u, (text) => {
  return myAnthropicTokenizer.count(text);
});

String patterns match model-name substrings case-insensitively. RegExp patterns are tested against the original model string. If a registered tokenizer throws or returns an invalid count, AI CostGuard falls back to the built-in approximation and keeps guarding the call.

Events

const unsubscribe = openai.on('block', (event) => {
  console.log(event.code, event.reason, event.context.estimatedCost);
});

unsubscribe();

Supported events are cost, allow, and block. Handler errors are swallowed so observability code cannot change guard decisions.

Local Dashboard

Opt into a local JSONL event log:

const openai = guard(client, {
  budget: 5,
  eventLogPath: '.ai-costguard/events.jsonl',
});

Start the local-only dashboard:

ai-costguard dashboard --events .ai-costguard/events.jsonl --budget 5

For one-off package execution:

npx @salimassili/ai-costguard dashboard --events .ai-costguard/events.jsonl --budget 5

If the package is installed locally, npx ai-costguard dashboard also works. The dashboard binds to 127.0.0.1 by default and reads only local event files.

For CI or terminal output:

ai-costguard dashboard --events .ai-costguard/events.jsonl --budget 5 --once --json

See docs/DASHBOARD.md.

Integrations

Runnable mocked examples are included for:

  • OpenAI SDK agent loop protection
  • Anthropic SDK workflow budget guard
  • Vercel AI SDK chatbot budget cap
  • LangChain retry-storm prevention
  • Mastra-style agent runner protection
  • CrewAI launch/budget gate
  • CI budget checks

See docs/INTEGRATIONS.md and examples/integrations.

Express Middleware

The middleware attaches a manual checker. It does not automatically parse or inspect every route.

import { middleware, GuardError } from '@salimassili/ai-costguard';

app.use(middleware({ budget: 2 }));

app.post('/chat', async (req, res, next) => {
  try {
    req.localSafety.check({
      model: 'gpt-4o-mini',
      tokens: 500,
      inputTokens: 100,
      outputTokens: 400,
      estimatedCost: 0.0003,
      timestamp: Date.now(),
      prompt: String(req.body?.prompt ?? ''),
    });

    res.json({ ok: true });
  } catch (error) {
    if (error instanceof GuardError) {
      res.status(403).json({ code: error.code, reason: error.message });
      return;
    }
    next(error);
  }
});

Optional Redis / Pro Helper

Redis-backed shared spend tracking is isolated behind a subpath import:

import { GuardPro } from '@salimassili/ai-costguard/pro';

const pro = new GuardPro({
  redisUrl: process.env.REDIS_URL ?? '',
  budget: 25,
  windowSeconds: 86400,
});

await pro.checkAndCharge('production', 0.0042);
await pro.shutdown();

ioredis is an optional dependency and is not loaded by the root import.

AI CostGuard does not include license-key checks or local commercial-license enforcement.

AI CostGuard Pro

AI CostGuard Free is the open-source npm package above — free forever, MIT licensed.

AI CostGuard Pro is a $19/month or $199/year subscription for teams taking AI agents into production. Lemon Squeezy handles purchase, receipts, and subscription management. The npm package does not perform runtime license-key enforcement.

Current pro-v0.1 materials include:

  • Redis/GuardPro setup guide
  • Multi-process shared-budget example
  • Environment-variable based Redis/webhook configuration guidance

Planned monthly updates include multi-tenant examples, tokenizer adapter recipes, GuardError handling patterns, pricing override guides, production checklists, and framework config starters as those files are completed.

No runtime license-key enforcement. No private npm package. No SaaS backend. You get a downloadable folder of setup materials and examples that use the public package API. Use environment variables or your deployment secret manager for provider keys, REDIS_URL, and webhook URLs; never hardcode secrets.

Get AI CostGuard Pro →

CLI

aifw check --budget 1 --model gpt-4o-mini --input-tokens 500 --tokens 1000 --max-steps 5

The package also installs an ai-costguard bin alias:

ai-costguard check --budget 1 --model gpt-4o-mini --tokens 1000 --max-steps 5
ai-costguard dashboard --events .ai-costguard/events.jsonl --budget 5

For custom models:

aifw check --budget 1 --model internal-model --tokens 1000 --input-price-per-1k 0.001 --output-price-per-1k 0.002

Exit codes:

  • 0: projected cost is within budget
  • 1: projected cost exceeds budget
  • 2: usage/config error

Benchmarks

Run local benchmarks:

npm run build
npm run benchmark

The script reports runtime overhead, approximate heap delta, false-positive scenarios, loop detection behavior, and cost-estimation boundaries. Results are local measurements, not universal guarantees. See docs/BENCHMARKS.md.

Latest local benchmark in this repo on Node v24.14.1 / Windows measured 0.023937 ms added per mocked guarded call over 5000 iterations. Re-run on your target runtime before using this number in performance-sensitive claims.

Token accuracy benchmark, fixed proxy corpus: average error 9.68%, median error 11.43%, max error 28.57%, 24 samples. The dependency-free estimator is a rough guardrail, not provider-tokenizer parity. Register an exact tokenizer for production use when token accuracy matters.

Why Not 50 Lines Of Code?

A simple homemade budget check can stop one request after one counter crosses one number. AI CostGuard packages the parts that usually become messy once agents enter production:

  • Provider pricing registry with runtime overrides and unknown-model blocking.
  • Structured GuardError codes and metadata for API responses.
  • Scoped budget and behavior state per project, user, or session.
  • TTL-bounded prompt history.
  • Loop and retry-storm detection.
  • Estimated, attempted, blocked, and actual usage accounting.
  • Method filtering so non-AI SDK calls are not charged.
  • Event hooks, best-effort webhooks, JSONL event logs, and local dashboard visibility.
  • CI budget checks and runnable integration examples.

Development

npm ci
npm run build
npm run typecheck
npm test
npm run smoke
npm run benchmark
npm run benchmark:tokens
npm audit --omit=dev
npm pack --dry-run

Limitations

  • Token counting is approximate and dependency-free unless you register an exact tokenizer.
  • Token estimation is intentionally conservative and can overestimate materially; see the token accuracy benchmark.
  • Pricing entries can become stale; override them for production.
  • The free guard is process-local.
  • Loop detection uses character trigram similarity, not embeddings.
  • Retry detection is heuristic.
  • Webhooks are best-effort and never affect enforcement.
  • The dashboard reads local JSONL logs only; it is not a hosted analytics product.
  • Provider usage reconciliation only works when responses expose recognizable usage fields.

License

MIT