@nicekit/core
v0.2.0
Published
NiceKit - AI toolkit for prompt building, model transport, and response parsing, plus core business logic
Readme
NiceKit
AI toolkit for prompt building, model transport, and response parsing.
NiceKit 是一个轻量级 AI 工具库,提供统一的提示词构建、多模型传输和响应解析能力,帮助前端项目解耦 AI 服务调用,提高代码复用性和可维护性。
特性
- 🚀 统一客户端 - 一个
AIClient替代庞大的服务单例,支持 Gemini / OpenAI / Anthropic 三种协议 - 📝 提示词构建器 - 链式 API 构建提示词,告别手动字符串拼接
- 📋 模板注册表 - 领域化提示词模板管理,支持版本控制和条件渲染
- 🔄 响应解析 - 安全的 JSON 提取、验证和降级策略
- ⚛️ React Hooks -
useGenerate/useGenerateStream封装状态管理 - 🌍 领域模板 - 内置健康、玄学等领域提示词模板
- 📦 Tree-shaking 友好 - 按需引入,零冗余
安装
npm install @nicekit/core
# 如需使用 Gemini 模型
npm install @google/generative-ai
# 如需 React Hooks
npm install react快速开始
纯 TypeScript 使用
import { AIClient, PromptBuilder, extractJson } from '@nicekit/core';
// 1. 初始化客户端
const client = new AIClient({
models: [{
id: 'deepseek',
name: 'DeepSeek',
API_KEY: 'your-api-key',
ServiceEndPoint: 'https://api.deepseek.com/v1/chat/completions',
deploymentName: 'deepseek-chat',
}],
defaultModelId: 'deepseek',
});
// 2. 构建提示词
const { systemInstruction, userPrompt } = new PromptBuilder()
.systemInstruction('你是一位专业的健康顾问')
.withContext({
temporal: { now: new Date(), includeSeason: true },
user: { bodyType: '阴虚' },
})
.prompt('请给出今日养生建议')
.constrain('字数100字以内')
.outputFormat({ kind: 'json', schemaHint: '{"tips":["..."]}' })
.build();
// 3. 调用 AI
const text = await client.generate(userPrompt, { systemInstruction });
// 4. 解析响应
const data = extractJson<{ tips: string[] }>(text);React 使用
import { NiceKitProvider, useGenerateStream, PromptBuilder } from '@nicekit/core/react';
// 应用根组件
function App() {
return (
<NiceKitProvider options={{
models: [{ id: 'deepseek', name: 'DeepSeek', API_KEY: '...', ServiceEndPoint: '...' }],
defaultModelId: 'deepseek',
}}>
<ChatPage />
</NiceKitProvider>
);
}
// 页面组件
function ChatPage() {
const { generateStream, text, isStreaming, abort } = useGenerateStream();
const handleAsk = async () => {
const { userPrompt, systemInstruction } = new PromptBuilder()
.role('health_advisor')
.prompt('如何改善睡眠质量?')
.build();
await generateStream(userPrompt, { systemInstruction });
};
return (
<div>
<button onClick={handleAsk} disabled={isStreaming}>
{isStreaming ? '生成中...' : '提问'}
</button>
{isStreaming && <button onClick={abort}>停止</button>}
<div>{text}</div>
</div>
);
}使用领域模板
import { PromptBuilder, PromptRegistry, createDomainRegistry } from '@nicekit/core';
// 创建包含所有领域模板的注册表
const registry = createDomainRegistry();
// 使用健康领域模板
const { systemInstruction, userPrompt } = new PromptBuilder(registry)
.role('health_advisor')
.template('health_daily_advice_v1', {
bodyType: '气虚',
season: '夏季',
recentConcern: '容易疲劳',
})
.build();
const text = await client.generate(userPrompt, { systemInstruction });核心模块
AIClient
轻量级 AI 客户端,自动选择合适的传输层。
const client = new AIClient({
models: [...],
defaultModelId: 'deepseek',
logger: consoleLogger, // 可选
stats: myStatsCollector, // 可选
});
// 非流式
const text = await client.generate(prompt, options);
// 流式
for await (const chunk of client.generateStream(prompt, options)) {
if (chunk.type === 'content') updateUI(chunk.text);
}
// 工具调用
const result = await client.generateWithTools(prompt, tools, options);PromptBuilder
链式 API 构建提示词。
const { systemInstruction, userPrompt } = new PromptBuilder()
.role('health_advisor') // 内置角色
// 或 .systemInstruction('...') // 自定义角色
.withContext({ // 注入上下文
temporal: { now: new Date(), includeSeason: true },
user: { nickname: '小明', bodyType: '阴虚' },
geo: { city: '北京' },
})
.template('template_id', vars) // 使用模板
.prompt('具体任务指令') // 或直接写 prompt
.constrain('约束条件1') // 追加约束
.outputFormat({ kind: 'json' }) // 指定输出格式
.build();PromptRegistry
管理提示词模板。
const registry = new PromptRegistry();
// 注册模板
registry.register({
id: 'my_template_v1',
domain: 'custom',
semver: '1.0.0',
output: { kind: 'text' },
nodes: [
{ type: 'text', text: '请分析:${topic}' },
{ type: 'if', condition: { op: 'exists', key: 'detail' }, then: [
{ type: 'text', text: '\n详细信息:${detail}' }
]},
],
});
// 渲染模板
const { text } = registry.render('my_template_v1', { topic: '健康' });响应解析
import { extractJson, extractJsonWithFallback, withFallback } from '@nicekit/core';
// 安全提取 JSON
const data = extractJson<MyType>(aiText);
// 带降级的提取
const data = extractJsonWithFallback<MyType>(aiText, defaultValue);
// 通用降级策略
const result = await withFallback(
() => client.generate(prompt),
{ type: 'defaultValue', value: '暂无数据' }
);React Hooks
| Hook | 用途 |
|------|------|
| useNiceKitClient() | 获取 AIClient 实例 |
| useGenerate() | 非流式生成,封装 loading/error/data |
| useGenerateStream() | 流式生成,封装 text/isStreaming/error |
| useAIResponse<T>(validator, fallback) | JSON 响应解析 + 降级 |
传输层
NiceKit 内置三种传输层,自动根据模型配置选择:
| 传输层 | 适用模型 |
|--------|---------|
| OpenAICompatTransport | DeepSeek / Qwen / Kimi / OpenRouter |
| GeminiTransport | Google Gemini (需要 @google/generative-ai) |
| AnthropicTransport | Claude 系列 |
错误处理
import { ApiError, RateLimitError, TimeoutError, buildUserFacingMessage } from '@nicekit/core';
try {
await client.generate(prompt);
} catch (error) {
if (error instanceof RateLimitError) {
// 限流,可重试
} else if (error instanceof ApiError) {
// API 错误
}
// 获取用户友好的错误消息
const message = buildUserFacingMessage(error);
}从现有代码迁移
迁移前(散落在组件中)
// components/MoodDiaryPage.tsx
const result = await aiService.generateContent(
`用户情绪:${mood},请生成疗愈指引...`,
undefined,
buildAIOptions(SYSTEM_SPIRITUAL_HEALER)
);迁移后(使用 NiceKit)
import { PromptBuilder } from '@nicekit/core';
const { userPrompt, systemInstruction } = new PromptBuilder()
.role('spiritual_healer')
.prompt(`用户情绪:${mood},请生成疗愈指引...`)
.build();
const result = await client.generate(userPrompt, { systemInstruction });许可证
MIT
