@cago-frame/agents-client
v0.1.0
Published
Headless UI library for Cago Agents - React hooks and adapters for AI agent conversations
Downloads
112
Maintainers
Readme
@cago/agents-client
一个用于构建 AI Agent 聊天界面的 React Headless UI 库。提供 hooks、context、无样式组件和流式传输适配器 —— 样式完全由你掌控。
特性
- Headless UI 组件 — 无样式、基于 render-prop 的组件(
ChatRoot、MessageList、MessageInput等),完全控制渲染输出 - React Hooks —
useChat、useMessages、useStream,灵活的状态管理 - 流式传输 — 内置 SSE 流式传输,支持实时文本增量更新
- 适配器模式 — 可插拔的适配器接口,内置 OpenAI 兼容适配器
- Tool Calls — 原生支持函数/工具调用消息
- TypeScript — 完整的类型定义
安装
npm install @cago/agents-client
# 或
pnpm add @cago/agents-client需要 peer dependencies:react >= 18.0.0、react-dom >= 18.0.0
快速开始
import {
ChatProvider,
createOpenAIAdapter,
ChatRoot,
MessageList,
MessageInput,
SendButton,
} from '@cago/agents-client';
const adapter = createOpenAIAdapter({
baseUrl: 'https://api.openai.com/v1',
apiKey: 'sk-...',
model: 'gpt-4',
});
function App() {
return (
<ChatProvider adapter={adapter}>
<ChatRoot>
<MessageList>
{({ messages }) =>
messages.map((msg) => (
<div key={msg.id}>
<strong>{msg.role}:</strong> {msg.content}
</div>
))
}
</MessageList>
<MessageInput>
{({ inputProps }) => <input {...inputProps} placeholder="输入消息..." />}
</MessageInput>
<SendButton>
{({ buttonProps }) => <button {...buttonProps}>发送</button>}
</SendButton>
</ChatRoot>
</ChatProvider>
);
}Hooks
useChat()
核心 hook,提供消息列表、状态和操作方法。
const { messages, status, error, sendMessage, abort, retry } = useChat();useMessages()
直接访问和操作消息列表。
const { messages, setMessages, appendMessage } = useMessages();useStream()
流式传输状态和控制。
const { isStreaming, status, abort, retry } = useStream();Headless 组件
所有组件均支持 render-prop 模式,只暴露状态而不附带任何样式:
| 组件 | 说明 |
| --- | --- |
| ChatRoot | 容器组件,带有 data-status 属性,支持多态 as prop |
| MessageList | 通过 render-prop 渲染消息列表 |
| MessageItem | 单条消息,暴露 role/content 等 render props |
| MessageInput | 受控输入框,内置提交处理 |
| SendButton | 发送按钮,自动管理 disabled 状态 |
| StreamControl | 流式传输的中止/重试控制 |
| MarkdownContent | 通过 render-prop 渲染 Markdown 内容 |
自定义适配器
实现 ChatAdapter 接口即可对接任意 LLM 后端:
import type { ChatAdapter, ChatStreamEvent, SendMessageParams } from '@cago/agents-client';
class MyAdapter implements ChatAdapter {
async *sendMessage(params: SendMessageParams): AsyncIterable<ChatStreamEvent> {
// yield { type: 'text-delta', content: '...' }
// yield { type: 'tool-call', toolCall: { ... } }
// yield { type: 'finish' }
}
abort() {
// 取消请求
}
}许可证
MIT
