DHX-Tool 工具库
DHX-Tool 工具库
DHX Team
2024年12月8日
tool-libraryfrontendanimationaistream-renderlangchain
简洁高效的前端工具库,通过统一的上层处理和适配器模式,提供流渲染、动画交互、AI 集成等常用功能的简单配置和一步调用
DHX-Tool 工具库
DHX-Tool 是一个专注于简化常用功能集成的工具库。通过将常用功能整合成简单内容,然后通过添加适配器实现特殊处理,让开发者能够以最少的配置实现复杂的功能。
🚀 核心理念
设计哲学
- 简洁优先: 常用功能默认配置,一步调用即可使用
- 适配器模式: 特殊需求通过适配器扩展,保持核心简洁
- 按需导入: 所有模块独立,支持 tree-shaking 和按需加载
- 零配置启动: 提供合理的默认配置,开箱即用
- 类型安全: 完整的 TypeScript 类型定义
- 性能优化: 内置性能优化,无需额外配置
架构设计
DHX-Tool (工具库)
├── StreamRenderer (流渲染模块)
│ ├── MarkdownAdapter
│ ├── HTMLAdapter
│ └── ComponentAdapter
├── Animation (动画模块)
│ ├── Live2DAdapter
│ ├── LottieAdapter
│ └── ThreeAdapter
└── AI (AI 模块)
├── LangChainAdapter
└── ChatAdapter
所有模块都遵循统一的适配器接口,便于扩展和自定义。
📦 模块概览
业务通用请求拦截处理适配器
1. StreamRenderer 流渲染模块
前端流式渲染能力,支持 Markdown、HTML、组件等内容的渐进式渲染。
核心特性
- 流式渲染: 支持内容的分块渲染,优化首屏加载
- 增量更新: 支持内容的增量添加,无需重新渲染
- 多种适配器: 内置 Markdown、HTML、组件适配器
- 性能优化: 智能的渲染调度和性能优化
- 可扩展: 通过适配器接口轻松扩展新的渲染类型
适配器接口设计
// 统一的适配器接口
interface StreamAdapter<T = any> {
// 初始化
init: (container: HTMLElement, options?: AdapterOptions) => void;
// 渲染单个块
renderChunk: (chunk: T) => Promise<void> | void;
// 渲染完整内容
render: (content: T) => Promise<void> | void;
// 清理
cleanup: () => void;
// 更新选项
updateOptions: (options: Partial<AdapterOptions>) => void;
}
interface AdapterOptions {
// 渲染配置
chunkSize?: number; // 每次渲染的块大小
delay?: number; // 渲染延迟(用于动画效果)
// 性能配置
useRequestAnimationFrame?: boolean;
batchSize?: number; // 批处理大小
// 自定义配置
[key: string]: any;
}
StreamRenderer API
interface StreamRendererProps {
// 数据源
source: StreamSource;
// 适配器类型
adapter?: 'markdown' | 'html' | 'component' | StreamAdapter;
// 配置选项
options?: AdapterOptions;
// 样式配置
className?: string;
// 事件处理
onComplete?: () => void;
onError?: (error: Error) => void;
onChunkRendered?: (chunk: any) => void;
}
type StreamSource =
| string // 字符串内容
| ReadableStream<string> // 流式内容
| AsyncIterable<string> // 异步迭代器
| (() => Promise<string>) // 异步函数
| (() => ReadableStream<string>); // 流式函数
基础用法
import { StreamRenderer } from 'dhx-tool/stream-renderer';
// Markdown 流式渲染
function MarkdownStreamExample() {
const markdownSource = async function* () {
const chunks = [
'# 标题\n\n',
'这是第一段内容。\n\n',
'这是第二段内容。\n\n',
'```typescript\n',
'const code = "example";\n',
'```\n',
];
for (const chunk of chunks) {
await new Promise(resolve => setTimeout(resolve, 100));
yield chunk;
}
};
return (
<StreamRenderer
source={markdownSource}
adapter="markdown"
onComplete={() => console.log('渲染完成')}
/>
);
}
// HTML 流式渲染
function HTMLStreamExample() {
const htmlSource = async function* () {
yield '<div>';
yield '<h1>标题</h1>';
yield '<p>内容</p>';
yield '</div>';
};
return (
<StreamRenderer
source={htmlSource}
adapter="html"
options={{ delay: 50 }}
/>
);
}
// 组件流式渲染
function ComponentStreamExample() {
const componentSource = async function* () {
yield { type: 'h1', props: { children: '标题' } };
yield { type: 'p', props: { children: '段落1' } };
yield { type: 'p', props: { children: '段落2' } };
};
return (
<StreamRenderer
source={componentSource}
adapter="component"
/>
);
}
高级用法
// 自定义适配器
import { StreamRenderer, createStreamAdapter } from 'dhx-tool/stream-renderer';
const customAdapter = createStreamAdapter({
init: (container, options) => {
// 初始化逻辑
},
renderChunk: async (chunk) => {
// 渲染单个块的逻辑
const element = document.createElement('div');
element.textContent = chunk;
container.appendChild(element);
},
cleanup: () => {
// 清理逻辑
},
});
// 使用自定义适配器
<StreamRenderer
source={dataSource}
adapter={customAdapter}
/>
// 从 API 流式渲染
function APIStreamExample() {
const apiSource = async () => {
const response = await fetch('/api/stream-content');
return response.body;
};
return (
<StreamRenderer
source={apiSource}
adapter="markdown"
/>
);
}
// 控制渲染速度
function ControlledStreamExample() {
const [speed, setSpeed] = useState(100);
return (
<div>
<Slider
value={speed}
onChange={setSpeed}
min={0}
max={1000}
/>
<StreamRenderer
source={content}
adapter="markdown"
options={{ delay: speed }}
/>
</div>
);
}
2. Animation 动画模块
统一的动画交互工具,通过适配器支持 Live2D、Lottie、Three.js 等多种动画技术。
核心特性
- 统一接口: 所有动画技术使用统一的 API
- 按需加载: 每个适配器独立,按需导入
- 性能优化: 内置性能优化和内存管理
- 交互支持: 完整的交互事件处理
- 可扩展: 易于添加新的动画适配器
统一适配器接口
// 动画适配器接口
interface AnimationAdapter {
// 初始化
init: (container: HTMLElement, config: AnimationConfig) => Promise<void>;
// 播放控制
play: () => Promise<void>;
pause: () => void;
stop: () => void;
reset: () => void;
// 动画状态
getState: () => 'idle' | 'playing' | 'paused' | 'stopped';
getProgress: () => number; // 0-1
// 时间控制
seek: (time: number) => void;
setSpeed: (speed: number) => void; // 播放速度
// 事件监听
on: (event: AnimationEvent, handler: EventHandler) => void;
off: (event: AnimationEvent, handler: EventHandler) => void;
// 交互
setInteraction?: (enabled: boolean) => void;
// 清理
destroy: () => void;
}
interface AnimationConfig {
// 资源路径
source: string | object;
// 播放配置
autoplay?: boolean;
loop?: boolean;
speed?: number;
// 样式配置
width?: number;
height?: number;
// 交互配置
interactive?: boolean;
// 自定义配置
[key: string]: any;
}
type AnimationEvent = 'play' | 'pause' | 'stop' | 'complete' | 'error' | 'interact';
type EventHandler = (...args: any[]) => void;
2.1 Live2DAdapter - Live2D 交互工具
Live2D 模型的加载、渲染和交互控制。
API 设计
interface Live2DAdapter extends AnimationAdapter {
// Live2D 特定方法
setExpression: (expressionId: string) => void;
setMotion: (motionGroup: string, motionId: number) => void;
hitTest: (x: number, y: number) => string[]; // 返回命中的部件ID
getModelInfo: () => Live2DModelInfo;
}
interface Live2DConfig extends AnimationConfig {
source: string; // .model3.json 文件路径
resources?: {
textures?: string[];
motions?: Record<string, string[]>;
expressions?: string[];
};
physics?: boolean;
eyeBlink?: boolean;
lipSync?: boolean;
}
基础用法
import { Live2DAdapter, AnimationPlayer } from 'dhx-tool/animation/live2d';
function Live2DExample() {
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!containerRef.current) return;
const adapter = new Live2DAdapter();
const player = new AnimationPlayer(adapter);
player.init(containerRef.current, {
source: '/models/character.model3.json',
autoplay: true,
interactive: true,
width: 300,
height: 400,
});
// 事件监听
player.on('interact', (hitAreas) => {
console.log('点击区域:', hitAreas);
if (hitAreas.includes('Head')) {
player.setExpression('happy');
}
});
return () => {
player.destroy();
};
}, []);
return <div ref={containerRef} />;
}
高级用法
// 表达式和动作控制
function Live2DAdvancedExample() {
const player = useAnimationPlayer(Live2DAdapter);
useEffect(() => {
player.init(containerRef.current, {
source: '/models/character.model3.json',
});
// 设置表情
player.setExpression('surprised');
// 播放动作
player.setMotion('tap_body', 0);
// 点击交互
player.on('interact', (hitAreas) => {
if (hitAreas.includes('Body')) {
player.setMotion('tap_body', Math.floor(Math.random() * 3));
}
});
}, []);
return (
<div>
<div ref={containerRef} />
<div>
<Button onClick={() => player.setExpression('happy')}>开心</Button>
<Button onClick={() => player.setExpression('sad')}>难过</Button>
<Button onClick={() => player.setMotion('idle', 0)}>待机</Button>
</div>
</div>
);
}
2.2 LottieAdapter - Lottie 动画工具
Lottie JSON 动画的渲染和控制。
API 设计
interface LottieAdapter extends AnimationAdapter {
// Lottie 特定方法
goToAndPlay: (value: number, isFrame?: boolean) => void;
goToAndStop: (value: number, isFrame?: boolean) => void;
setDirection: (direction: 1 | -1) => void;
playSegments: (segments: [number, number][], forceFlag?: boolean) => void;
setSubframe: (useSubFrames: boolean) => void;
getDuration: (inFrames?: boolean) => number;
}
interface LottieConfig extends AnimationConfig {
source: string | object; // JSON 文件路径或对象
renderer?: 'svg' | 'canvas' | 'html';
rendererSettings?: {
preserveAspectRatio?: string;
clearCanvas?: boolean;
context?: CanvasRenderingContext2D;
progressiveLoad?: boolean;
hideOnTransparent?: boolean;
};
}
基础用法
import { LottieAdapter, AnimationPlayer } from 'dhx-tool/animation/lottie';
function LottieExample() {
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!containerRef.current) return;
const adapter = new LottieAdapter();
const player = new AnimationPlayer(adapter);
player.init(containerRef.current, {
source: '/animations/loading.json',
autoplay: true,
loop: true,
renderer: 'svg',
});
return () => {
player.destroy();
};
}, []);
return <div ref={containerRef} />;
}
高级用法
// 控制播放片段
function LottieSegmentsExample() {
const player = useAnimationPlayer(LottieAdapter);
useEffect(() => {
player.init(containerRef.current, {
source: '/animations/character.json',
});
// 播放特定片段
player.playSegments([[0, 30], [60, 90]], true);
}, []);
return (
<div>
<div ref={containerRef} />
<div>
<Button onClick={() => player.playSegments([[0, 30]])}>播放片段1</Button>
<Button onClick={() => player.playSegments([[30, 60]])}>播放片段2</Button>
<Button onClick={() => player.setSpeed(0.5)}>慢速</Button>
<Button onClick={() => player.setSpeed(2)}>快速</Button>
</div>
</div>
);
}
// 响应式尺寸
function ResponsiveLottieExample() {
const containerRef = useRef<HTMLDivElement>(null);
const [size, setSize] = useState({ width: 400, height: 400 });
useEffect(() => {
const updateSize = () => {
setSize({
width: containerRef.current?.clientWidth || 400,
height: containerRef.current?.clientHeight || 400,
});
};
window.addEventListener('resize', updateSize);
updateSize();
return () => window.removeEventListener('resize', updateSize);
}, []);
return (
<div ref={containerRef} style={{ width: '100%', height: '100%' }}>
<LottiePlayer
source="/animations/animation.json"
width={size.width}
height={size.height}
autoplay
loop
/>
</div>
);
}
2.3 ThreeAdapter - Three.js 交互工具
Three.js 场景的管理和动画控制。
API 设计
interface ThreeAdapter extends AnimationAdapter {
// Three.js 特定方法
getScene: () => THREE.Scene;
getCamera: () => THREE.Camera;
getRenderer: () => THREE.WebGLRenderer;
addObject: (object: THREE.Object3D) => void;
removeObject: (object: THREE.Object3D) => void;
setCameraPosition: (x: number, y: number, z: number) => void;
setControls: (controls: THREE.OrbitControls | THREE.FlyControls | any) => void;
render: () => void;
}
interface ThreeConfig extends AnimationConfig {
source?: string | object; // GLTF/GLB 文件路径或场景配置对象
camera?: {
type?: 'perspective' | 'orthographic';
fov?: number;
near?: number;
far?: number;
position?: [number, number, number];
};
renderer?: {
antialias?: boolean;
alpha?: boolean;
shadowMap?: boolean;
};
controls?: {
type?: 'orbit' | 'fly' | 'first-person';
enabled?: boolean;
[key: string]: any;
};
lights?: Array<{
type: 'ambient' | 'directional' | 'point' | 'spot';
[key: string]: any;
}>;
}
基础用法
import { ThreeAdapter, AnimationPlayer } from 'dhx-tool/animation/three';
function ThreeExample() {
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!containerRef.current) return;
const adapter = new ThreeAdapter();
const player = new AnimationPlayer(adapter);
player.init(containerRef.current, {
source: '/models/scene.gltf',
autoplay: true,
camera: {
type: 'perspective',
fov: 75,
position: [0, 0, 5],
},
controls: {
type: 'orbit',
enabled: true,
},
});
// 添加自定义对象
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
adapter.addObject(cube);
return () => {
player.destroy();
};
}, []);
return <div ref={containerRef} style={{ width: '100%', height: '100vh' }} />;
}
高级用法
// 复杂场景管理
function ThreeAdvancedExample() {
const player = useAnimationPlayer(ThreeAdapter);
useEffect(() => {
player.init(containerRef.current, {
camera: {
type: 'perspective',
fov: 75,
position: [0, 5, 10],
},
lights: [
{ type: 'ambient', color: 0xffffff, intensity: 0.5 },
{ type: 'directional', position: [10, 10, 5], intensity: 1 },
],
renderer: {
antialias: true,
shadowMap: true,
},
});
// 加载模型
const loader = new THREE.GLTFLoader();
loader.load('/models/scene.gltf', (gltf) => {
const scene = player.getScene();
scene.add(gltf.scene);
player.play();
});
// 动画循环
const animate = () => {
requestAnimationFrame(animate);
player.render();
};
animate();
}, []);
return (
<div>
<div ref={containerRef} style={{ width: '100%', height: '600px' }} />
<div>
<Button onClick={() => player.setCameraPosition(0, 5, 10)}>视角1</Button>
<Button onClick={() => player.setCameraPosition(10, 5, 0)}>视角2</Button>
</div>
</div>
);
}
// 统一动画播放器 Hook
function useAnimationPlayer<T extends AnimationAdapter>(
AdapterClass: new () => T
) {
const containerRef = useRef<HTMLDivElement>(null);
const playerRef = useRef<AnimationPlayer<T> | null>(null);
useEffect(() => {
if (!containerRef.current) return;
const adapter = new AdapterClass();
const player = new AnimationPlayer(adapter);
playerRef.current = player;
return () => {
player.destroy();
};
}, []);
return {
containerRef,
player: playerRef.current,
};
}
3. AI 模块
LangChain 工具的基础功能整合,提供简单配置和一步调用。
核心特性
- 简单配置: 最少的配置即可使用
- 一步调用: 统一的调用接口,无需了解底层细节
- 链式调用: 支持链式调用和组合
- 错误处理: 统一的错误处理和重试机制
- 流式响应: 支持流式响应处理
- 可扩展: 通过适配器扩展新的 AI 服务
适配器接口设计
// AI 适配器接口
interface AIAdapter {
// 初始化
init: (config: AIConfig) => Promise<void>;
// 调用
call: (input: AIInput) => Promise<AIOutput>;
// 流式调用
stream?: (input: AIInput) => AsyncIterable<AIChunk>;
// 链式调用
chain?: (steps: AIStep[]) => AICallable;
// 清理
destroy: () => void;
}
interface AIConfig {
// API 配置
apiKey?: string;
baseURL?: string;
model?: string;
// 请求配置
temperature?: number;
maxTokens?: number;
timeout?: number;
// 重试配置
retries?: number;
retryDelay?: number;
// 自定义配置
[key: string]: any;
}
interface AIInput {
prompt?: string;
messages?: Array<{ role: string; content: string }>;
[key: string]: any;
}
interface AIOutput {
text: string;
usage?: {
promptTokens?: number;
completionTokens?: number;
totalTokens?: number;
};
[key: string]: any;
}
interface AIChunk {
text: string;
done?: boolean;
[key: string]: any;
}
3.1 LangChainAdapter - LangChain 工具整合
LangChain 功能的简化封装。
API 设计
interface LangChainAdapter extends AIAdapter {
// LangChain 特定方法
createChain: (chainConfig: ChainConfig) => AICallable;
createAgent: (agentConfig: AgentConfig) => AIAgent;
loadTool: (toolName: string, config?: any) => Promise<AITool>;
}
interface ChainConfig {
type: 'llm' | 'sequential' | 'router' | 'custom';
steps?: AIStep[];
prompt?: string | PromptTemplate;
outputParser?: (output: any) => any;
}
interface AgentConfig {
type: 'zero-shot' | 'react' | 'conversational';
tools?: AITool[];
memory?: boolean;
maxIterations?: number;
}
interface AIStep {
name: string;
call: (input: any) => Promise<any>;
}
基础用法
import { LangChainAdapter, createAIClient } from 'dhx-tool/ai/langchain';
// 简单调用
async function SimpleAIExample() {
const client = createAIClient({
apiKey: process.env.OPENAI_API_KEY,
model: 'gpt-3.5-turbo',
});
const response = await client.call({
prompt: '解释一下什么是 React Hooks',
});
console.log(response.text);
}
// 组件中使用
function AIComponentExample() {
const [response, setResponse] = useState('');
const [loading, setLoading] = useState(false);
const handleAsk = async (question: string) => {
setLoading(true);
const client = createAIClient();
const result = await client.call({ prompt: question });
setResponse(result.text);
setLoading(false);
};
return (
<div>
<Input onEnter={handleAsk} />
{loading && <Loading />}
<div>{response}</div>
</div>
);
}
高级用法
// 链式调用
async function ChainExample() {
const client = createAIClient();
const chain = client.createChain({
type: 'sequential',
steps: [
{
name: 'translate',
call: async (input) => {
const result = await client.call({
prompt: `将以下文本翻译成英文: ${input.text}`,
});
return { translated: result.text };
},
},
{
name: 'summarize',
call: async (input) => {
const result = await client.call({
prompt: `总结以下文本: ${input.translated}`,
});
return { summary: result.text };
},
},
],
});
const result = await chain({ text: '这是一段中文文本' });
console.log(result.summary);
}
// 流式响应
function StreamingExample() {
const [text, setText] = useState('');
const handleStream = async () => {
const client = createAIClient();
const stream = client.stream({
prompt: '写一个关于 React 的短文',
});
for await (const chunk of stream) {
setText((prev) => prev + chunk.text);
}
};
return (
<div>
<Button onClick={handleStream}>生成文本</Button>
<div>{text}</div>
</div>
);
}
// Agent 使用
async function AgentExample() {
const client = createAIClient();
// 加载工具
const calculator = await client.loadTool('calculator');
const webSearch = await client.loadTool('web-search');
// 创建 Agent
const agent = client.createAgent({
type: 'react',
tools: [calculator, webSearch],
memory: true,
});
// 使用 Agent
const result = await agent.call({
input: '计算 123 + 456,然后搜索这个结果的相关信息',
});
console.log(result.output);
}
// 自定义 Prompt 模板
function PromptTemplateExample() {
const client = createAIClient();
const template = `
你是一个专业的技术文档编写助手。
用户问题: {question}
上下文: {context}
请基于以上信息,提供详细的回答。
`;
const chain = client.createChain({
type: 'llm',
prompt: template,
});
const result = await chain({
question: '如何优化 React 性能?',
context: '项目使用 React 18,TypeScript,Next.js',
});
console.log(result);
}
统一 AI 客户端
// 创建 AI 客户端
function createAIClient(config?: AIConfig): AIClient {
const adapter = new LangChainAdapter();
return new AIClient(adapter, config);
}
// AI 客户端接口
interface AIClient {
// 简单调用
call: (input: AIInput) => Promise<AIOutput>;
// 流式调用
stream: (input: AIInput) => AsyncIterable<AIChunk>;
// 链式调用
chain: (config: ChainConfig) => AICallable;
// Agent
agent: (config: AgentConfig) => AIAgent;
// 工具
loadTool: (name: string, config?: any) => Promise<AITool>;
}
🛠️ 安装和配置
安装
npm install dhx-tool
# 或
yarn add dhx-tool
# 或
pnpm add dhx-tool
按需导入
所有模块支持按需导入:
// 流渲染模块
import { StreamRenderer } from 'dhx-tool/stream-renderer';
import { MarkdownAdapter } from 'dhx-tool/stream-renderer/markdown';
// 动画模块
import { Live2DAdapter } from 'dhx-tool/animation/live2d';
import { LottieAdapter } from 'dhx-tool/animation/lottie';
import { ThreeAdapter } from 'dhx-tool/animation/three';
// AI 模块
import { createAIClient } from 'dhx-tool/ai/langchain';
依赖要求
StreamRenderer 模块
- React 18.0+
- TypeScript 5.0+
Animation 模块
- Live2DAdapter:
@pixi/live2d-display(可选,按需安装) - LottieAdapter:
lottie-web(可选,按需安装) - ThreeAdapter:
three(可选,按需安装)
AI 模块
langchain(可选,按需安装)@langchain/openai或其他 LLM 提供者适配器
基础配置
// 配置 AI 客户端(可选)
import { configureAI } from 'dhx-tool/ai';
configureAI({
defaultProvider: 'openai',
apiKey: process.env.OPENAI_API_KEY,
baseURL: process.env.AI_BASE_URL,
});
// 配置动画适配器(可选)
import { configureAnimation } from 'dhx-tool/animation';
configureAnimation({
defaultRenderer: 'webgl',
performanceMode: 'auto',
});
📋 最佳实践
1. 模块组合使用
// 组合流渲染和 AI
function AIStreamingContent() {
const [content, setContent] = useState('');
useEffect(() => {
const client = createAIClient();
const stream = client.stream({
prompt: '生成一篇技术文章',
});
(async () => {
for await (const chunk of stream) {
setContent((prev) => prev + chunk.text);
}
})();
}, []);
return (
<StreamRenderer
source={content}
adapter="markdown"
/>
);
}
// 组合动画和交互
function InteractiveAnimation() {
const player = useAnimationPlayer(Live2DAdapter);
const aiClient = createAIClient();
const handleInteraction = async (hitAreas: string[]) => {
if (hitAreas.includes('Head')) {
// 播放动画
player.setExpression('happy');
// 同时调用 AI 生成回应
const response = await aiClient.call({
prompt: '生成一个开心的回应',
});
console.log(response.text);
}
};
return (
<div>
<AnimationPlayer
adapter={Live2DAdapter}
onInteraction={handleInteraction}
/>
</div>
);
}
2. 性能优化
// 懒加载适配器
const LottieAdapter = lazy(() => import('dhx-tool/animation/lottie'));
// 使用 React.memo 优化渲染
const StreamContent = React.memo(({ content }) => (
<StreamRenderer source={content} adapter="markdown" />
));
// 批处理流式内容
function BatchedStreamRenderer({ source }) {
const [batch, setBatch] = useState([]);
useEffect(() => {
const processor = async () => {
const buffer = [];
for await (const chunk of source) {
buffer.push(chunk);
if (buffer.length >= 10) {
setBatch((prev) => [...prev, ...buffer]);
buffer.length = 0;
await new Promise(resolve => requestAnimationFrame(resolve));
}
}
if (buffer.length > 0) {
setBatch((prev) => [...prev, ...buffer]);
}
};
processor();
}, [source]);
return <StreamRenderer source={batch.join('')} adapter="markdown" />;
}
3. 错误处理
// 统一的错误处理
function RobustAIComponent() {
const client = createAIClient({
retries: 3,
retryDelay: 1000,
});
const handleCall = async (prompt: string) => {
try {
const response = await client.call({ prompt });
return response.text;
} catch (error) {
if (error instanceof AITimeoutError) {
console.error('请求超时,请重试');
} else if (error instanceof AIAPIError) {
console.error('API 错误:', error.message);
} else {
console.error('未知错误:', error);
}
throw error;
}
};
return <div>...</div>;
}
🚧 开发路线图
v1.0 (当前开发中)
- StreamRenderer 核心功能实现
- MarkdownAdapter、HTMLAdapter、ComponentAdapter 实现
- Live2DAdapter 基础功能
- LottieAdapter 基础功能
- ThreeAdapter 基础功能
- LangChainAdapter 基础功能整合
- 完善的文档和示例
- 单元测试覆盖率 > 80%
v1.1 (计划中)
- 更多流渲染适配器(PDF、Office 文档等)
- 动画适配器性能优化
- AI 模块更多工具支持
- 统一的配置管理
- 性能监控和分析
- 可视化调试工具
v2.0 (未来)
- WebAssembly 支持
- 更多 AI 服务提供商适配
- 可视化流程构建器
- 插件系统
- 社区适配器市场
🤝 贡献指南
我们欢迎社区贡献!特别是适配器的扩展和优化。
创建自定义适配器
// 创建自定义流渲染适配器
import { createStreamAdapter } from 'dhx-tool/stream-renderer';
export const CustomAdapter = createStreamAdapter({
init: (container, options) => {
// 初始化
},
renderChunk: async (chunk) => {
// 渲染逻辑
},
cleanup: () => {
// 清理逻辑
},
});
// 创建自定义动画适配器
import { createAnimationAdapter } from 'dhx-tool/animation';
export const CustomAnimationAdapter = createAnimationAdapter({
init: async (container, config) => {
// 初始化
},
play: async () => {
// 播放逻辑
},
// ... 其他方法
});
📄 许可证
MIT License - 查看 LICENSE 文件了解详细信息。
🙏 致谢
最后更新:2024年12月