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

推荐订阅源

Blog — PlanetScale
Blog — PlanetScale
S
Security @ Cisco Blogs
博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
Last Week in AI
Last Week in AI
Jina AI
Jina AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
阮一峰的网络日志
阮一峰的网络日志
GbyAI
GbyAI
Microsoft Security Blog
Microsoft Security Blog
B
Blog
A
About on SuperTechFans
B
Blog RSS Feed
M
MIT News - Artificial intelligence
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
宝玉的分享
宝玉的分享
H
Hackread – Cybersecurity News, Data Breaches, AI and More
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
H
Help Net Security
博客园 - Franky
D
Darknet – Hacking Tools, Hacker News & Cyber Security
P
Palo Alto Networks Blog
罗磊的独立博客
S
Securelist
L
LINUX DO - 热门话题
T
Tor Project blog
人人都是产品经理
人人都是产品经理
Google DeepMind News
Google DeepMind News
T
Threatpost
Simon Willison's Weblog
Simon Willison's Weblog
P
Privacy International News Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Spread Privacy
Spread Privacy
WordPress大学
WordPress大学
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
MyScale Blog
MyScale Blog
T
The Blog of Author Tim Ferriss
爱范儿
爱范儿
Cyberwarzone
Cyberwarzone
NISL@THU
NISL@THU
Apple Machine Learning Research
Apple Machine Learning Research
S
SegmentFault 最新的问题
C
Cyber Attacks, Cyber Crime and Cyber Security
G
Google Developers Blog
The Hacker News
The Hacker News
Latest news
Latest news
A
Arctic Wolf
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
S
Schneier on Security

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 - trimooo/react-ai-stream: Lightweight React SDK for streaming AI chat — useAIChat hook, built-in providers, drop-in UI
devleoo · 2026-05-10 · via Hacker News - Newest: "AI"

CI npm npm npm npm downloads bundle size License: MIT Live demo

Backend-agnostic AI streaming for React. One hook. Any provider. Drop-in UI or bring your own.

  • One hookuseAIChat manages messages, loading state, abort, and errors
  • Any backend — Anthropic, OpenAI, Groq, or your own streaming endpoint
  • Optional UI — drop-in <Chat /> component or wire the hook to your own design
  • Event hooksonToken, onComplete, onError for side-effects without extra state
  • TypeScript first — strict types, full DTS, ESM + CJS

Who this is for

SaaS teams adding AI chat to an existing product — you already have a design system, you don't want to be locked into ours.

Enterprise dashboards that need multiple isolated chat instances on the same page — model comparisons, parallel streams, side-by-side analysis.

AI copilot builders who want streaming primitives, not opinions. Wire useAIChat to any interface: a sidebar, a floating widget, a full-page chat.

Teams with a Python, Go, or Rails backend — the hook speaks plain HTTP + SSE. Your existing server can produce the stream. No Node.js required.

Not for: agent systems, RAG, orchestration, or memory platforms. This library stays focused on streaming AI responses into React.

// 1. npm install @react-ai-stream/react @react-ai-stream/ui
// 2. Add an API route (see Backend Setup below)
// 3. Done.

'use client'
import { useAIChat } from '@react-ai-stream/react'
import { Chat } from '@react-ai-stream/ui'
import '@react-ai-stream/ui/styles'

export default function Page() {
  const { messages, sendMessage, loading, stop } = useAIChat({
    endpoint: '/api/chat',
  })

  return (
    <div style={{ height: '80vh' }}>
      <Chat messages={messages} onSend={sendMessage} onStop={stop} loading={loading} />
    </div>
  )
}

Architecture

flowchart LR
    subgraph App["React Application"]
        direction TB
        UI["Your UI / &lt;Chat /&gt;"]
        Hook["useAIChat()"]
        Store["Zustand store\nmessages · loading · error"]
        Client["SSE parser\n+ normalizer"]
        UI <-->|"messages · stop"| Hook
        Hook <--> Store
        Hook --> Client
    end

    subgraph Server["Your Server  (Next.js · Express · FastAPI · Go)"]
        Route["/api/chat"]
    end

    subgraph Providers["LLM Providers"]
        P["Anthropic · OpenAI\nGroq · Custom · Local"]
    end

    Client -->|"POST messages"| Route
    Route <-->|"provider API"| Providers
    Route -->|"SSE stream\ndata: {type:'text'}\ndata: {type:'done'}"| Client
    Store -->|"useSyncExternalStore"| UI
Loading

Your React app never knows which LLM produced the stream. The hook speaks a three-event protocol (text, done, error) over SSE. Any server that produces those events works.


Why not Vercel AI SDK?

react-ai-stream Vercel AI SDK
Bundle size ~12 kB ~90 kB+
Framework lock-in None — plain React Next.js / Vercel optimized
Backend required Optional (direct providers work) Yes for most features
Custom endpoint First-class Via adapters
Pre-built UI Yes (@react-ai-stream/ui) No
Event hooks onToken / onComplete / onError Limited
License MIT MIT

react-ai-stream is a good fit when you want a small, portable library with no framework opinions. If you're all-in on Next.js and need RSC streaming or server actions, Vercel AI SDK is worth evaluating.


Installation

npm install @react-ai-stream/react @react-ai-stream/ui
# or
pnpm add @react-ai-stream/react @react-ai-stream/ui

Peer dependencies: React 18 or 19.


Backend Setup

Next.js App Router

// app/api/chat/route.ts
import { NextRequest } from 'next/server'

export const runtime = 'edge'

export async function POST(req: NextRequest) {
  const { messages } = await req.json()

  const response = await fetch('https://api.anthropic.com/v1/messages', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': process.env.ANTHROPIC_API_KEY!,
      'anthropic-version': '2023-06-01',
    },
    body: JSON.stringify({
      model: 'claude-sonnet-4-6',
      max_tokens: 1024,
      messages,
      stream: true,
    }),
  })

  const stream = new ReadableStream({
    async start(controller) {
      const enc = new TextEncoder()
      const send = (data: object) =>
        controller.enqueue(enc.encode(`data: ${JSON.stringify(data)}\n\n`))

      const reader = response.body!.getReader()
      const decoder = new TextDecoder()
      let buf = ''
      while (true) {
        const { done, value } = await reader.read()
        if (done) break
        buf += decoder.decode(value, { stream: true })
        const parts = buf.split('\n\n')
        buf = parts.pop() ?? ''
        for (const part of parts) {
          for (const line of part.split('\n')) {
            if (!line.startsWith('data: ')) continue
            try {
              const ev = JSON.parse(line.slice(6))
              if (ev.type === 'content_block_delta' && ev.delta?.type === 'text_delta')
                send({ type: 'text', text: ev.delta.text })
              else if (ev.type === 'message_stop')
                send({ type: 'done' })
            } catch { /* skip */ }
          }
        }
      }
      send({ type: 'done' })
      controller.close()
    },
  })

  return new Response(stream, {
    headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' },
  })
}

The SDK expects your endpoint to emit SSE lines in this format:

Chunk Meaning
{ "type": "text", "text": "..." } Append text to the assistant message
{ "type": "done" } Stream is complete
{ "type": "error", "error": "..." } Surface an error

Express / Node.js

import express from 'express'
import Anthropic from '@anthropic-ai/sdk'

const app = express()
app.use(express.json())

app.post('/api/chat', async (req, res) => {
  const { messages } = req.body
  res.setHeader('Content-Type', 'text/event-stream')
  res.setHeader('Cache-Control', 'no-cache')

  const send = (data: object) => res.write(`data: ${JSON.stringify(data)}\n\n`)

  const client = new Anthropic()
  const stream = await client.messages.stream({
    model: 'claude-sonnet-4-6',
    max_tokens: 1024,
    messages,
  })

  for await (const event of stream) {
    if (event.type === 'content_block_delta' && event.delta.type === 'text_delta')
      send({ type: 'text', text: event.delta.text })
  }

  send({ type: 'done' })
  res.end()
})

useAIChat Hook

const {
  messages,      // Message[]  — full conversation history
  sendMessage,   // (text: string) => Promise<void>
  loading,       // boolean    — true while streaming
  stop,          // () => void — abort in-flight stream
  error,         // string | null
  clearMessages, // () => void — reset conversation
} = useAIChat(options)

Options

Option Type Description
endpoint string URL of your streaming API route
headers Record<string, string> Extra headers sent with every request
body Record<string, unknown> Extra fields merged into every request body
provider 'openai' | 'anthropic' Direct provider (no backend needed)
apiKey string API key for direct provider
model string Model name
baseURL string Override base URL (OpenAI-compatible APIs)
maxTokens number Max tokens (Anthropic only)
system string System prompt (direct providers only)
client AIClient Bring your own pre-built client
onToken (token: string) => void Called for each streamed text chunk
onComplete (message: Message) => void Called when the full response is done
onError (error: Error) => void Called on stream or provider errors

Event hooks example

const chat = useAIChat({
  endpoint: '/api/chat',
  onToken: (token) => {
    // e.g. update a word count in real-time
    setTokenCount((n) => n + 1)
  },
  onComplete: (message) => {
    // e.g. save the final response to a database
    saveToHistory(message)
  },
  onError: (err) => {
    // e.g. report to Sentry
    Sentry.captureException(err)
  },
})

Message shape

interface Message {
  id: string
  role: 'user' | 'assistant' | 'system' | 'tool'
  content: string
  createdAt: Date
}

Providers

Custom endpoint (recommended)

const chat = useAIChat({ endpoint: '/api/chat' })

// With extra headers or body fields:
const chat = useAIChat({
  endpoint: '/api/chat',
  headers: { 'X-Session-Id': sessionId },
  body: { persona: 'support-agent' },
})

Anthropic direct

const chat = useAIChat({
  provider: 'anthropic',
  apiKey: process.env.NEXT_PUBLIC_ANTHROPIC_API_KEY!,
  model: 'claude-sonnet-4-6',
  maxTokens: 2048,
  system: 'You are a helpful assistant.',
})

OpenAI direct

const chat = useAIChat({
  provider: 'openai',
  apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY!,
  model: 'gpt-4o',
  system: 'You are a helpful assistant.',
})

Groq (OpenAI-compatible)

const chat = useAIChat({
  provider: 'openai',
  apiKey: process.env.NEXT_PUBLIC_GROQ_API_KEY!,
  baseURL: 'https://api.groq.com/openai/v1',
  model: 'llama-3.3-70b-versatile',
})

Pre-built UI

<Chat /> — all-in-one

import { Chat } from '@react-ai-stream/ui'
import '@react-ai-stream/ui/styles'

<Chat
  messages={messages}
  onSend={sendMessage}
  onStop={stop}
  loading={loading}
  placeholder="Type here…"
  className="my-chat"
/>

Individual components

import { MessageList, ChatInput, MarkdownRenderer } from '@react-ai-stream/ui'

function MyChatUI() {
  const { messages, sendMessage, loading, stop } = useAIChat({ endpoint: '/api/chat' })
  return (
    <div>
      <MessageList messages={messages} loading={loading} />
      <ChatInput onSend={sendMessage} onStop={stop} loading={loading} />
    </div>
  )
}

Theming with CSS variables

:root {
  --ras-bg: #0f172a;
  --ras-bg-user: #6366f1;
  --ras-bg-assistant: #1e293b;
  --ras-text: #f1f5f9;
  --ras-text-user: #ffffff;
  --ras-text-muted: #94a3b8;
  --ras-border: #334155;
  --ras-radius: 16px;
  --ras-font: 'Inter', sans-serif;
  --ras-code-bg: #0d1117;
  --ras-code-text: #c9d1d9;
}
Variable Default Controls
--ras-bg #ffffff Chat container background
--ras-bg-user #2563eb User message bubble
--ras-bg-assistant #f3f4f6 Assistant message bubble
--ras-text #111827 Base text color
--ras-text-user #ffffff Text inside user bubbles
--ras-text-muted #6b7280 Typing indicator, timestamps
--ras-border #e5e7eb Input border, dividers
--ras-radius 12px Bubble corner radius
--ras-font system-ui, sans-serif Font family
--ras-code-bg #1e293b Code block background
--ras-code-text #e2e8f0 Code block text

Dark mode

@media (prefers-color-scheme: dark) {
  :root {
    --ras-bg: #0f172a;
    --ras-bg-user: #6366f1;
    --ras-bg-assistant: #1e293b;
    --ras-text: #f1f5f9;
    --ras-text-muted: #94a3b8;
    --ras-border: #334155;
    --ras-code-bg: #0d1117;
    --ras-code-text: #c9d1d9;
  }
}

Customization Recipes

Custom UI (bypass <Chat />)

'use client'
import { useState } from 'react'
import { useAIChat } from '@react-ai-stream/react'
import { MarkdownRenderer } from '@react-ai-stream/ui'
import '@react-ai-stream/ui/styles'

export function SupportWidget() {
  const { messages, sendMessage, loading, stop } = useAIChat({ endpoint: '/api/chat' })
  const [input, setInput] = useState('')

  return (
    <div className="widget">
      <div className="messages">
        {messages.map((m) => (
          <div key={m.id} className={`bubble bubble--${m.role}`}>
            {m.role === 'assistant'
              ? <MarkdownRenderer content={m.content} />
              : <p>{m.content}</p>}
          </div>
        ))}
      </div>
      <form onSubmit={(e) => { e.preventDefault(); sendMessage(input); setInput('') }}>
        <input value={input} onChange={(e) => setInput(e.target.value)} disabled={loading} />
        {loading
          ? <button type="button" onClick={stop}>Stop</button>
          : <button type="submit">Send</button>}
      </form>
    </div>
  )
}

System prompt (server-side, recommended)

// In your route handler — keeps the prompt private
body: JSON.stringify({
  model: 'claude-sonnet-4-6',
  system: 'You are a friendly support agent for Acme Inc.',
  messages,
  stream: true,
})

Multiple independent chats

Each useAIChat call has a completely isolated store — no context needed:

const claude = useAIChat({ endpoint: '/api/chat?model=claude' })
const gpt    = useAIChat({ endpoint: '/api/chat?model=gpt' })

// Broadcast the same message to both
function sendToAll(text: string) {
  claude.sendMessage(text)
  gpt.sendMessage(text)
}

Shared client via context

import { createAIClient } from '@react-ai-stream/core'
import { AIChatProvider, useAIChat } from '@react-ai-stream/react'

const client = createAIClient({ endpoint: '/api/chat' })

function App() {
  return (
    <AIChatProvider client={client}>
      <MainChat />
    </AIChatProvider>
  )
}

function MainChat() {
  const { messages, sendMessage, loading } = useAIChat({} as any)
  // ...
}

Programmatic control

const { sendMessage, clearMessages, stop, messages } = useAIChat({ endpoint: '/api/chat' })

// Send on mount (e.g., welcome message)
useEffect(() => { sendMessage('Say hello briefly.') }, [])

// Reset
function newChat() {
  stop()
  clearMessages()
}

// Read last assistant reply
const lastReply = messages.findLast((m) => m.role === 'assistant')?.content

API Reference

useAIChat(options)

Returns UseAIChatReturn:

interface UseAIChatReturn {
  messages:      Message[]
  sendMessage:   (content: string) => Promise<void>
  loading:       boolean
  stop:          () => void
  error:         string | null
  clearMessages: () => void
}

<Chat />

Prop Type Required Description
messages Message[] yes Message array from useAIChat
onSend (text: string) => void yes Called when user submits
onStop () => void no Abort handler — shows Stop button
loading boolean no Enables typing indicator
placeholder string no Input placeholder text
className string no Extra CSS class on root div

<MessageList />

Prop Type Description
messages Message[] Messages to render
loading boolean Show animated typing indicator
className string Extra CSS class

<ChatInput />

Prop Type Description
onSend (text: string) => void Submit handler
onStop () => void Abort handler
loading boolean Disable input, show Stop button
placeholder string Textarea placeholder
disabled boolean Hard-disable the input

<MarkdownRenderer />

Prop Type Description
content string Markdown string to render
className string Extra CSS class on wrapper

Renders GitHub-Flavored Markdown with syntax-highlighted code blocks and a copy button on each.

createAIClient(options)

import { createAIClient } from '@react-ai-stream/core'

const client = createAIClient({ endpoint: '/api/chat' })
const client = createAIClient({ provider: 'openai', apiKey: '...', model: 'gpt-4o' })
const client = createAIClient({ provider: 'anthropic', apiKey: '...', model: 'claude-sonnet-4-6' })

Returns AIClient — pass to useAIChat({ client }) or <AIChatProvider client={...}>.


Community

Built with react-ai-stream

Using react-ai-stream in a project? Open a discussion or PR this table.

Project Description
Live demo 3-model parallel streaming — Groq × Llama 3.3, Llama 3.1, Llama 4 Scout

License

MIT