@h-ai/ai 0.1.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,266 @@
1
+ import { ac as ChatCompletionRequest, ad as ChatCompletionResponse, aa as ChatCompletionChunk, aD as KnowledgeRetrieveResult, aq as KnowledgeAskResult, az as KnowledgeIngestResult, ar as KnowledgeDocumentInfo, aJ as MemoryEntry, be as StorePage, aK as MemoryEntryInput, aR as MemoryUpdateInput, bc as SessionInfo, ag as ChatRecord, aY as RagResult, b0 as ReasoningResult, O as A2AAgentCardConfig, _ as A2AMessageRecord, V as A2ACallResult } from '../ai-reasoning-types-CGUgkLF7.js';
2
+ import { HaiResult } from '@h-ai/core';
3
+ import '@a2a-js/sdk/server';
4
+ import '@h-ai/datapipe';
5
+ import 'zod';
6
+ import 'openai';
7
+
8
+ /**
9
+ * @h-ai/ai — 前端 AI 客户端
10
+ *
11
+ * 基于 @h-ai/api-client 的 AI 领域客户端。
12
+ * 通过 `createAIClient()` 工厂函数创建,消除自建 HTTP 层,
13
+ * 复用 api-client 提供的 Token 管理、超时、拦截器等基础能力。
14
+ * @module ai-client
15
+ */
16
+
17
+ /**
18
+ * AI 客户端所需的 API 调用能力
19
+ *
20
+ * 结构兼容 `@h-ai/api-client` 的 `api` 单例(鸭子类型)。
21
+ * 传入 `api` 单例即可,无需额外适配。
22
+ */
23
+ interface AIApiAdapter {
24
+ /** POST 请求(返回 HaiResult) */
25
+ post: <T>(path: string, body?: unknown) => Promise<HaiResult<T>>;
26
+ /** 流式请求(返回 SSE data 行的 AsyncIterable) */
27
+ stream: (path: string, body?: unknown) => AsyncIterable<string>;
28
+ }
29
+ /**
30
+ * AI 客户端配置
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * import { api } from '@h-ai/api-client'
35
+ * import { createAIClient } from '@h-ai/ai/client'
36
+ *
37
+ * await api.init({ baseUrl: '/api', auth: { ... } })
38
+ * const aiClient = createAIClient({ api })
39
+ * ```
40
+ */
41
+ interface AIClientConfig {
42
+ /**
43
+ * API 调用适配器
44
+ *
45
+ * 传入 `api` 单例(初始化后)。
46
+ * baseUrl、Token 管理、超时等通过 api-client 配置。
47
+ */
48
+ api: AIApiAdapter;
49
+ }
50
+ /** 流式响应进度(`onProgress` 回调参数) */
51
+ interface StreamProgress {
52
+ /** 当前累积的文本内容 */
53
+ content: string;
54
+ /** 是否已完成 */
55
+ done: boolean;
56
+ /** 完成原因(仅 `done=true` 时有值,如 `'stop'`) */
57
+ finishReason?: string;
58
+ }
59
+ /** 流式响应选项 */
60
+ interface StreamOptions {
61
+ /** 进度回调(每次收到 chunk 时触发) */
62
+ onProgress?: (progress: StreamProgress) => void;
63
+ }
64
+ /**
65
+ * AI 客户端接口
66
+ *
67
+ * 提供浏览器端调用 AI API 的能力,HTTP 基础设施委托给 @h-ai/api-client。
68
+ */
69
+ interface AIClient {
70
+ /** 发送对话请求(非流式) */
71
+ chat: (request: ChatCompletionRequest) => Promise<ChatCompletionResponse>;
72
+ /** 发送流式对话请求,返回异步迭代器 */
73
+ chatStream: (request: ChatCompletionRequest, options?: StreamOptions) => AsyncIterable<ChatCompletionChunk>;
74
+ /** 便捷方法:发送纯文本消息并返回回复文本 */
75
+ sendMessage: (message: string, systemPrompt?: string) => Promise<string>;
76
+ /** 便捷方法:流式发送纯文本消息并返回完整回复 */
77
+ sendMessageStream: (message: string, options?: StreamOptions, systemPrompt?: string) => Promise<string>;
78
+ /** 简单问答(单轮,自动构造 messages) */
79
+ ask: (question: string, options?: {
80
+ systemPrompt?: string;
81
+ model?: string;
82
+ }) => Promise<string>;
83
+ /** 流式简单问答,返回异步文本流 */
84
+ askStream: (question: string, options?: {
85
+ systemPrompt?: string;
86
+ model?: string;
87
+ }) => AsyncIterable<string>;
88
+ /** 知识检索(向量 + 实体增强) */
89
+ knowledgeRetrieve: (query: string, options?: {
90
+ topK?: number;
91
+ collection?: string;
92
+ }) => Promise<KnowledgeRetrieveResult>;
93
+ /** 知识问答(RAG + 信源) */
94
+ knowledgeAsk: (query: string, options?: {
95
+ model?: string;
96
+ collection?: string;
97
+ }) => Promise<KnowledgeAskResult>;
98
+ /** 导入文档 */
99
+ knowledgeIngest: (input: {
100
+ documentId: string;
101
+ content: string;
102
+ title?: string;
103
+ collection?: string;
104
+ metadata?: Record<string, unknown>;
105
+ }) => Promise<KnowledgeIngestResult>;
106
+ /** 列出已导入文档 */
107
+ knowledgeListDocuments: (options?: {
108
+ collection?: string;
109
+ offset?: number;
110
+ limit?: number;
111
+ }) => Promise<KnowledgeDocumentInfo[]>;
112
+ /** 删除已导入文档 */
113
+ knowledgeRemoveDocument: (documentId: string, options?: {
114
+ collection?: string;
115
+ }) => Promise<void>;
116
+ /** 检索相关记忆 */
117
+ recallMemories: (query: string, options?: {
118
+ topK?: number;
119
+ types?: string[];
120
+ minImportance?: number;
121
+ objectId?: string;
122
+ }) => Promise<MemoryEntry[]>;
123
+ /** 列出记忆(分页) */
124
+ listMemories: (options?: {
125
+ types?: string[];
126
+ objectId?: string;
127
+ offset?: number;
128
+ limit?: number;
129
+ }) => Promise<StorePage<MemoryEntry>>;
130
+ /** 添加记忆 */
131
+ addMemory: (entry: MemoryEntryInput) => Promise<MemoryEntry>;
132
+ /** 更新记忆 */
133
+ updateMemory: (memoryId: string, updates: MemoryUpdateInput) => Promise<MemoryEntry>;
134
+ /** 删除记忆 */
135
+ removeMemory: (memoryId: string) => Promise<void>;
136
+ /** 列出会话 */
137
+ listSessions: (objectId: string) => Promise<SessionInfo[]>;
138
+ /** 重命名会话 */
139
+ renameSession: (sessionId: string, title: string) => Promise<void>;
140
+ /** 删除会话 */
141
+ removeSession: (sessionId: string) => Promise<void>;
142
+ /** 获取对话历史 */
143
+ chatHistory: (objectId: string, sessionId: string, options?: {
144
+ limit?: number;
145
+ order?: 'asc' | 'desc';
146
+ }) => Promise<ChatRecord[]>;
147
+ /** RAG 查询(检索 + 生成) */
148
+ ragQuery: (query: string, options?: {
149
+ collection?: string;
150
+ topK?: number;
151
+ model?: string;
152
+ }) => Promise<RagResult>;
153
+ /** RAG 流式查询,返回 SSE 数据行 */
154
+ ragQueryStream: (query: string, options?: {
155
+ collection?: string;
156
+ topK?: number;
157
+ model?: string;
158
+ }) => AsyncIterable<string>;
159
+ /** 推理(多步思考) */
160
+ reasoningRun: (query: string, options?: {
161
+ model?: string;
162
+ maxSteps?: number;
163
+ }) => Promise<ReasoningResult>;
164
+ /** 推理流式,返回 SSE 数据行 */
165
+ reasoningRunStream: (query: string, options?: {
166
+ model?: string;
167
+ maxSteps?: number;
168
+ }) => AsyncIterable<string>;
169
+ /** 估算文本的 Token 数 */
170
+ estimateTokens: (text: string) => Promise<{
171
+ tokens: number;
172
+ }>;
173
+ }
174
+ /**
175
+ * 创建 AI 客户端
176
+ *
177
+ * 通过 @h-ai/api-client 的 ApiClient 实例调用后端 AI API。
178
+ * HTTP 层(Token、超时、拦截器)全部复用 api-client,本模块仅负责:
179
+ * - 非流式 / 流式 ChatCompletion 协议适配
180
+ * - SSE 解析与 ChatCompletionChunk 类型化
181
+ * - onProgress 进度回调
182
+ *
183
+ * @param config - 客户端配置
184
+ * @returns AI 客户端实例
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * import { api } from '@h-ai/api-client'
189
+ * import { createAIClient } from '@h-ai/ai/client'
190
+ *
191
+ * await api.init({ baseUrl: '/api' })
192
+ * const client = createAIClient({ api })
193
+ * const reply = await client.sendMessage('你好')
194
+ * ```
195
+ */
196
+ declare function createAIClient(config: AIClientConfig): AIClient;
197
+ /**
198
+ * 从 fetch Response 中解析 SSE data 字段
199
+ *
200
+ * 自动处理分片缓冲和 `[DONE]` 结束标记。
201
+ *
202
+ * @param response - fetch 响应对象
203
+ * @yields SSE data 字符串(不含 `[DONE]`)
204
+ *
205
+ * @example
206
+ * ```ts
207
+ * const resp = await fetch('/api/chat', { method: 'POST', body })
208
+ * for await (const data of parseSSE(resp)) {
209
+ * const chunk = JSON.parse(data) // ChatCompletionChunk
210
+ * }
211
+ * ```
212
+ */
213
+ declare function parseSSE(response: Response): AsyncIterable<string>;
214
+ /**
215
+ * 收集流式响应的完整文本内容
216
+ *
217
+ * 完整消费流并拼接所有 `delta.content` 片段。
218
+ *
219
+ * @param stream - 聊天响应块流
220
+ * @returns 完整文本
221
+ *
222
+ * @example
223
+ * ```ts
224
+ * const client = createAIClient({ api })
225
+ * const stream = client.chatStream({ messages })
226
+ * const fullText = await collectStreamContent(stream)
227
+ * ```
228
+ */
229
+ declare function collectStreamContent(stream: AsyncIterable<ChatCompletionChunk>): Promise<string>;
230
+
231
+ /**
232
+ * @h-ai/ai — 前端 A2A 客户端
233
+ *
234
+ * 浏览器端 A2A 操作客户端,通过 API 服务调用后端 A2A 能力。
235
+ * @module ai-a2a-client
236
+ */
237
+
238
+ /**
239
+ * A2A 客户端接口
240
+ *
241
+ * 提供浏览器端调用后端 A2A API 的能力。
242
+ */
243
+ interface A2AClientOperations {
244
+ /** 获取当前 Agent Card 配置 */
245
+ getAgentCard: () => Promise<A2AAgentCardConfig>;
246
+ /** 查询 A2A 消息记录 */
247
+ listMessages: (filter?: {
248
+ contextId?: string;
249
+ status?: string;
250
+ limit?: number;
251
+ offset?: number;
252
+ }) => Promise<StorePage<A2AMessageRecord>>;
253
+ /** 作为客户端调用远端 Agent */
254
+ callRemoteAgent: (remoteUrl: string, message: string, options?: {
255
+ timeout?: number;
256
+ }) => Promise<A2ACallResult>;
257
+ }
258
+ /**
259
+ * 创建 A2A 客户端
260
+ *
261
+ * @param api - API 适配器(来自 @h-ai/api-client)
262
+ * @returns A2A 客户端操作实例
263
+ */
264
+ declare function createA2AClient(api: AIApiAdapter): A2AClientOperations;
265
+
266
+ export { type A2AClientOperations, type AIApiAdapter, type AIClient, type AIClientConfig, type StreamOptions, type StreamProgress, collectStreamContent, createA2AClient, createAIClient, parseSSE };
@@ -0,0 +1,3 @@
1
+ export { collectStreamContent, createA2AClient, createAIClient, parseSSE } from '../chunk-ABP7RKIP.js';
2
+ //# sourceMappingURL=index.js.map
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -0,0 +1,40 @@
1
+ export { O as A2AAgentCardConfig, P as A2AApiKeySecurity, Q as A2AAuthenticator, U as A2ACallOptions, V as A2ACallResult, W as A2ACallerIdentity, X as A2AClientCallRecord, A as A2AConfig, a as A2AConfigSchema, Y as A2AContextInfo, Z as A2AHandleResult, _ as A2AMessageRecord, $ as A2AOperations, a0 as A2ASecurityConfig, b as A2ASkillConfigSchema, a1 as A2ATaskFilter, c as AIConfig, d as AIConfigInput, e as AIConfigSchema, a2 as AILLMFunctionsDeps, a3 as AIRelStore, a4 as AIRelStoreOptions, a5 as AIStoreProvider, a6 as AIVectorStore, a7 as AskOptions, a8 as AssistantMessage, a9 as ChatCompletionChoice, aa as ChatCompletionChunk, ab as ChatCompletionDelta, ac as ChatCompletionRequest, ad as ChatCompletionResponse, ae as ChatHistoryOptions, af as ChatMessage, ag as ChatRecord, ah as Citation, C as CompressConfig, f as CompressConfigSchema, ai as DefineToolOptions, E as EmbeddingConfig, g as EmbeddingConfigSchema, aj as EntityDocumentRelation, ak as EntityDocumentResult, al as EntityListOptions, am as EntityQueryOptions, h as EntityType, i as EntityTypeSchema, F as FileConfig, j as FileConfigSchema, an as ImageContent, ao as InteractionScope, ap as KnowledgeAskOptions, aq as KnowledgeAskResult, K as KnowledgeConfig, k as KnowledgeConfigSchema, ar as KnowledgeDocumentInfo, as as KnowledgeDocumentListOptions, at as KnowledgeDocumentRemoveOptions, au as KnowledgeEntity, av as KnowledgeIngestBatchProgress, aw as KnowledgeIngestBatchResult, ax as KnowledgeIngestFileInput, ay as KnowledgeIngestInput, az as KnowledgeIngestResult, aA as KnowledgeOperations, aB as KnowledgeRetrieveItem, aC as KnowledgeRetrieveOptions, aD as KnowledgeRetrieveResult, aE as KnowledgeSetupOptions, aF as KnowledgeStore, L as LLMConfig, l as LLMConfigSchema, aG as LLMOperations, aH as LLMProvider, M as MCPConfig, m as MCPConfigSchema, n as MCPServerCapabilities, o as MCPServerCapabilitiesSchema, p as MCPServerConfig, q as MCPServerConfigSchema, aI as MemoryClearOptions, r as MemoryConfig, s as MemoryConfigSchema, aJ as MemoryEntry, aK as MemoryEntryInput, aL as MemoryExtractOptions, aM as MemoryInjectionOptions, aN as MemoryListOptions, aO as MemoryListPageOptions, aP as MemoryOperations, aQ as MemoryRecallOptions, t as MemoryType, u as MemoryTypeSchema, aR as MemoryUpdateInput, aS as MessageContent, aT as MessageRole, v as ModelEntry, w as ModelEntrySchema, x as ModelScenario, y as ModelScenarioSchema, aU as ObjectRef, aV as RagContextItem, aW as RagOperations, aX as RagOptions, aY as RagResult, aZ as RagStreamEvent, a_ as ReasoningOperations, a$ as ReasoningOptions, b0 as ReasoningResult, b1 as ReasoningStep, b2 as ReasoningStepType, b3 as ReasoningStrategy, b4 as ReasoningStreamEvent, R as ResolveRequiredModelEntryOptions, z as ResolvedModelConfig, B as RetrievalConfig, D as RetrievalConfigSchema, b5 as RetrievalOperations, b6 as RetrievalRequest, b7 as RetrievalResult, b8 as RetrievalResultItem, b9 as RetrievalSource, G as RetrievalSourceConfig, H as RetrievalSourceSchema, ba as SSEDecoder, bb as SSEEvent, bc as SessionInfo, bd as StoreFilter, be as StorePage, bf as StoreScope, bg as StreamOperations, bh as StreamProcessor, bi as StreamResult, S as SummaryConfig, I as SummaryConfigSchema, bj as SystemMessage, bk as TextContent, T as TokenConfig, J as TokenConfigSchema, bl as TokenUsage, bm as Tool, bn as ToolCall, bo as ToolDefinition, bp as ToolErrorType, bq as ToolMessage, br as ToolRegistryOperations, bs as ToolsOperations, bt as UserMessage, bu as WhereClause, bv as WhereOperator, bw as WhereValue, N as resolveModelEntry } from './ai-reasoning-types-CGUgkLF7.js';
2
+ import { A as AIFunctions } from './ai-types-CRCjluXI.js';
3
+ export { a as AIInitOptions, c as AIMCPFunctionsDeps, d as CompressOperations, e as CompressOptions, f as CompressResult, C as CompressionStrategy, b as CompressionStrategySchema, g as ContextChatOptions, h as ContextChatResult, i as ContextDeps, j as ContextManager, k as ContextManagerOptions, l as ContextOperations, m as ContextStreamEvent, E as EmbeddingItem, n as EmbeddingOperations, o as EmbeddingProvider, p as EmbeddingRequest, q as EmbeddingResponse, F as FileOperations, r as FileParseMethod, s as FileParseOptions, t as FileParseRequest, u as FileParseResult, H as HaiAIError, M as MCPContext, v as MCPOperations, w as MCPPrompt, x as MCPPromptArgument, y as MCPPromptContent, z as MCPPromptMessage, B as MCPProvider, D as MCPResource, G as MCPResourceContent, I as MCPToolDefinition, J as MCPToolHandler, K as McpServerOptions, O as OutputFormat, R as RerankDocument, L as RerankItem, N as RerankOperations, P as RerankRequest, Q as RerankResponse, S as SummaryOperations, T as SummaryOptions, U as SummaryResult, V as TokenOperations } from './ai-types-CRCjluXI.js';
4
+ export { TaskStore as A2ATaskStore, AgentExecutor, ExecutionEventBus, RequestContext, ServerCallContext } from '@a2a-js/sdk/server';
5
+ export { AgentCapabilities, AgentCard, AgentProvider, AgentSkill, Artifact, DataPart, FilePart, FileWithBytes, FileWithUri, Message, MessageSendParams, Part, PushNotificationConfig, Task, TaskArtifactUpdateEvent, TaskIdParams, TaskQueryParams, TaskState, TaskStatus, TaskStatusUpdateEvent, TextPart } from '@a2a-js/sdk';
6
+ import '@h-ai/core';
7
+ import '@h-ai/datapipe';
8
+ import 'zod';
9
+ import 'openai';
10
+ import 'node:buffer';
11
+
12
+ /**
13
+ * @h-ai/ai — AI 服务主入口
14
+ *
15
+ * 提供统一的 `ai` 对象,聚合所有 AI 操作功能。
16
+ * @module ai-main
17
+ */
18
+
19
+ /**
20
+ * AI 服务对象,统一的 AI 访问入口
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * import { ai } from '@h-ai/ai'
25
+ *
26
+ * // 初始化
27
+ * await ai.init({ llm: { model: 'gpt-4o-mini', apiKey: process.env.HAI_AI_LLM_API_KEY } })
28
+ *
29
+ * // LLM 调用
30
+ * const result = await ai.llm.chat({
31
+ * messages: [{ role: 'user', content: '你好' }],
32
+ * })
33
+ *
34
+ * // 关闭
35
+ * ai.close()
36
+ * ```
37
+ */
38
+ declare const ai: AIFunctions;
39
+
40
+ export { AIFunctions, ai };