npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@zimtsui/brainswitch

v0.0.60

Published

<!-- 本文档由 GPT-5 辅助生成 -->

Readme

Brainswitch

NPM Version

Brainswitch 是一个强类型的 LLM 推理 API 适配器。

支持服务商 API 类型

  • OpenAI Responses
  • Google
  • 阿里云 OpenAI Chat Completions Compatible
  • Anthropic

安装

环境要求:Node.js >= 22。

npm install @zimtsui/brainswitch

核心概念

  • Session:会话状态。
  • InferenceContext:工作流环境,包含 TypeLog Logger、AbortSignal、用户防止并发过载的读写锁
  • Engine:推理引擎,从一个会话状态生成下一个会话状态。
  • Endpoint:代表一家服务商的一个模型的 API 端点。
  • Adaptor:Engine 工厂。
  • RoleMessage:三类角色消息 DeveloperUserAI,消息由 Text/Function.Call/Response 片段组成。
  • Function.Declaration.Map:函数工具声明集合,使用 JSON Schema 描述函数参数。

配置

export type Config = {
    brainswitch: {
        endpoints: Record<string, {
            baseUrl: string;
            apiKey: string;
            model: string;
            name: string;
            apiType:
                | 'openai-responses'
                | 'google'
                | 'aliyun'
                | 'anthropic'
            ;
            proxy?: string;
            inputPrice?: number;    // CNY per MToken
            outputPrice?: number;   // CNY per MToken
            cachePrice?: number;    // CNY per MToken
            rpm?: number;           // Requests per minute
            timeout?: number;       // Time limit in milliseconds
            maxTokens?: number;     // Maximum number of generated tokens
            additionalOptions?: Record<string, unknown>;
        };
    };
}

快速上手

import { Adaptor, agentloop, RoleMessage, Function, type InferenceContext, type Config, type Session } from '@zimtsui/brainswitch';
import { Type } from '@sinclair/typebox';
import { RWLock } from '@zimtsui/coroutine-locks';


// 配置推理服务商 API 接入点
const config: Config = {
    brainswitch: {
        endpoints: {
            'gpt-5-mini': {
                name: 'GPT-5 mini',
                apiType: 'openai-responses',
                baseUrl: 'https://api.openai.com/v1',
                apiKey: process.env.OPENAI_API_KEY!,
                model: 'gpt-5-mini',
            },
            'gemini-3-flash': {
                name: 'Gemini 3 Flash',
                apiType: 'google',
                baseUrl: 'https://generativelanguage.googleapis.com',
                apiKey: process.env.GOOGLE_API_KEY!,
                model: 'gemini-3-flash',
            },
        }
    }
}

// 声明函数工具
const fdm = {
    get_weather: {
        description: '获取指定城市的天气',
        paraschema: Type.Object({
            city: Type.String(),
            unit: Type.Optional(Type.Union([Type.Literal('C'), Type.Literal('F')]))
        }),
    },
    submit_result: {
        description: '提交最终结果',
        paraschema: Type.Object({
            weather: Type.String(),
            advice: Type.String(),
        }),
    },
} satisfies Function.Declaration.Map;
type fdm = typeof fdm;

// 实现函数工具
export class Submission {
    public constructor(public weather: string, public advice: string) {}
}
const fnm: Function.Map<fdm> = {
    async get_weather({ city, unit }) {
        const data = { city, unit: unit ?? 'C', temperature: 26, sky: 'sunny' };
        return JSON.stringify(data);
    },
    async submit_result({ weather, advice }) {
        throw new Submission(weather, advice);
    },
};

// 初始化工作流上下文
const wfctx: InferenceContext = {
    busy: new RWLock(),
    cost(deltaCost) {
        console.log((-deltaCost).toFixed(2));
    },
    signal: null,
};

// 创建会话
const session: Session<fdm> = {
    developerMessage: RoleMessage.Developer.create([
        RoleMessage.Part.Text.create('你的工作是为用户查询天气,并给出穿衣建议。调用工具提交最终结果'),
    ]),
    chatMessages: [
        RoleMessage.User.create([ RoleMessage.Part.Text.create('请查询现在北京的天气,并给穿衣建议。') ]),
    ],
};

// 选择推理引擎
const adaptor = Adaptor.create(config);
const engine = adaptor.makeEngine('gpt-5-mini', fdm, Function.ToolChoice.REQUIRED);

// 使用 agentloop 驱动智能体循环,最多 8 轮对话
try {
    for await (const text of agentloop(wfctx, session, engine, fnm, 8)) console.log(text);
} catch (e) {
    if (e instanceof Submission) {} else throw e;
    console.log(e.weather);
    console.log(e.advice);
}