@flutchai/chat-core

中文文档
0.1.9发布于 2026/11/03MITTypeScriptES Module近 30 天下载 2268

Framework-agnostic client and state for the Flutch chat API: requests, SSE streaming, conversation store and storage. No UI.

原始使用文档

@flutchai/chat-core

Framework-agnostic client and state for the Flutch chat API: typed requests, SSE streaming, conversation state and storage. No UI. Pair it with @flutchai/chat-react or build your own interface.

import { createFlutchClient, createChatStore } from "@flutchai/chat-core";

const client = createFlutchClient({ baseUrl: "/api/chat", agentId: "…" }); // your backend knows the user;
const store = createChatStore({ client });

store.subscribe(s => render(s.messages));
store.getState().setDraftText("Hello");
await store.getState().send();

Without the store, use the client directly: invoke, stream (typed events), send (accumulates text), cancel, listThreads, getMessages, react, upload, getArticle (text of a report sent as article_link). API types live in @flutchai/chat-contract.

Storage: pass storage (get/set/remove, sync or async) to createChatStore for React Native, cookies, etc. The default is localStorage with a memory fallback.

Backend proxy

Never call the Flutch API from a browser. The API key identifies your whole company. Your backend receives the browser's requests, adds the key and the user, and forwards them. The client mirrors the External API paths under baseUrl, so the proxy is a thin pass-through:

Browser calls {baseUrl} +Forward to https://api.flutch.ai/api/v1 +
POST /agents/{agentId}/streamsame path, SSE
POST /agents/{agentId}/invokesame path
POST /agents/{agentId}/cancelsame path
GET /agents/{agentId}/threadssame path
GET /agents/{agentId}/threads/{id}/messagessame path
GET /agents/{agentId}/messages/{id}/streamsame path, SSE, pass Last-Event-ID
PATCH /agents/{agentId}/messages/{id}/reactionssame path
POST /agents/{agentId}/uploadssame path, multipart
GET /agents/{agentId}/articles/{id}same path

What the proxy must do on every request:

  1. Authenticate the browser user with your own session.
  2. Set X-API-Key from server-side configuration.
  3. Set externalUserId itself (JSON body for invoke/stream, query string for everything else), from the authenticated session: your own id for the user, e.g. (string) $request->user()->id. Flutch creates the user the first time it sees the id, so there is nothing to register or store. Never trust an externalUserId or userId sent by the browser, or one user can read another's conversations.
  4. Allow only the agent(s) you expect in {agentId}, and only the routes above.
  5. Stream without buffering for both SSE routes, and give them a long timeout (15 min): an answer that runs other agents takes minutes. A 404 on the resume route makes the chat give up on a reply that is still being generated.
  6. Forward cancel only for the Stop button. A user who closes the page or loses the network does not stop the reply: Flutch finishes it and saves it in the thread, and the history endpoint returns it in full when they come back. The client calls cancel only when the user presses Stop.

Laravel sketch

// routes/api.php
Route::middleware('auth')->prefix('chat/agents/{agent}')->group(function () {
    Route::post('stream', [FlutchProxy::class, 'stream']);
    Route::post('invoke', [FlutchProxy::class, 'invoke']);
    Route::post('cancel', [FlutchProxy::class, 'cancel']);
    Route::get('threads', [FlutchProxy::class, 'threads']);
    Route::get('threads/{thread}/messages', [FlutchProxy::class, 'messages']);
    Route::patch('messages/{message}/reactions', [FlutchProxy::class, 'react']);
});

class FlutchProxy
{
    private const BASE = 'https://api.flutch.ai/api/v1';

    private function http(string $agent)
    {
        abort_unless($agent === config('services.flutch.agent_id'), 404);
        return Http::withHeaders(['X-API-Key' => config('services.flutch.key')]);
    }

    private function userId(Request $r): string
    {
        return (string) $r->user()->id;   // your own id, from your session, never from the request
    }

    private function json($res)
    {
        return response($res->body(), $res->status())->header('Content-Type', 'application/json');
    }

    public function stream(Request $r, string $agent)
    {
        $body = $r->only(['content', 'threadId', 'metadata']) + ['externalUserId' => $this->userId($r)];
        $upstream = $this->http($agent)->withOptions(['stream' => true])
            ->post(self::BASE."/agents/$agent/stream", $body);

        return response()->stream(function () use ($upstream) {
            $body = $upstream->toPsrResponse()->getBody();
            while (!$body->eof() && !connection_aborted()) {
                echo $body->read(1024);
                @ob_flush();
                flush();
            }
            $body->close();   // does not stop the reply: Flutch finishes it and saves it in the thread
        }, $upstream->status(), [
            'Content-Type' => 'text/event-stream',
            'Cache-Control' => 'no-cache',
            'X-Accel-Buffering' => 'no',   // nginx
        ]);
    }

    public function invoke(Request $r, string $agent)
    {
        $body = $r->only(['content', 'threadId', 'metadata']) + ['externalUserId' => $this->userId($r)];
        return $this->json($this->http($agent)->post(self::BASE."/agents/$agent/invoke", $body));
    }

    public function cancel(Request $r, string $agent)
    {
        return $this->json($this->http($agent)->post(
            self::BASE."/agents/$agent/cancel?externalUserId=".urlencode($this->userId($r)),
            $r->only(['requestId'])
        ));
    }

    public function threads(Request $r, string $agent)
    {
        return $this->json($this->http($agent)->get(
            self::BASE."/agents/$agent/threads",
            $r->only(['page', 'limit']) + ['externalUserId' => $this->userId($r)]
        ));
    }

    public function messages(Request $r, string $agent, string $thread)
    {
        return $this->json($this->http($agent)->get(
            self::BASE."/agents/$agent/threads/$thread/messages",
            $r->only(['page', 'limit']) + ['externalUserId' => $this->userId($r)]
        ));
    }

    public function react(Request $r, string $agent, string $message)
    {
        return $this->json($this->http($agent)->patch(
            self::BASE."/agents/$agent/messages/$message/reactions?externalUserId=".urlencode($this->userId($r)),
            $r->only(['like'])
        ));
    }
}

Uploads (POST uploads) are a multipart pass-through: attach the uploaded file with Http::attach('file', ...) and the same externalUserId query string.

This is a starting point, not tested drop-in code. Adjust error handling and make sure PHP output buffering (output_buffering=off, zlib.output_compression=off) and any reverse proxy do not buffer the /stream response.

版本与发布记录

@flutchai/chat-core 共发布 11 个版本,首次发布于 2026/10/21;过去 12 个月发布了 11 个版本。

版本发布日期距今
0.1.9latest2026/11/0312 天前
0.1.82026/11/0114 天前
0.1.72026/11/0114 天前
0.1.62026/11/0114 天前
0.1.52026/11/0114 天前
0.1.42026/10/3115 天前

关于 @flutchai/chat-core 的常见问题

@flutchai/chat-core 是什么?

Framework-agnostic client and state for the Flutch chat API: requests, SSE streaming, conversation store and storage. No UI.

如何安装 @flutchai/chat-core?

在项目目录运行 npm install @flutchai/chat-core,或使用 pnpm add / yarn add / bun add。

@flutchai/chat-core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@flutchai/chat-core 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@flutchai/chat-core 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@flutchai/chat-core 可以商用吗?

@flutchai/chat-core 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@flutchai/chat-core 的下载量有多少?

根据 npm 官方下载统计,@flutchai/chat-core 在 2026/10/15 – 2026/11/13 这 30 天内被下载 2,268 次,日均约 76 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@flutchai/chat-core 还在维护吗?

最新版本 0.1.9 发布于 2026/11/03(12 天前);至今共发布 11 个版本,其中过去 12 个月发布了 11 个;首次发布于 2026/10/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。