@ egain/ai- agent- sdk
TypeScript-First SDK用于eGain的AI Agent平台,与WebSocket通信,自动重接,并全面处理消息.
当前发布 : 页:1
特征
- 🔌 WebSocket 通讯 - 实时双向通讯,自动重联
- 📬 信件排队 - 离线时自动排队,再连接时冲出
- 🔐 多个 Auth 策略 - 预先授权、匿名、PCE、客户证
- 🎯 类型安全事件 - 完全类型脚本支持,并有强烈类型的事件
- 📝 记录管理 - 内设的过滤对话历史
- 🧠 背景持久性 - 在重新连接时自动缓存和恢复
- 🛡️ 处理错误 - 保护应用程序的全面输入错误
- 🌐 通用 - 在浏览器和Node.js中工作
- 🏢 门户初始化 - WebSocket之前的联络中心REST管道(门户、代理、简介)
connect() - 🔌 平台连接器 - 装入CC 连接脚本;已键入
HookContract编号 :PlatformComponentService集成器 - 🎭 数据掩码 - 在代理配置中启用部门聊天模式
maskContent()用于UI/升级
安装
npm install @egain/ai-agent-sdk
快速启动
以下样本使用 自动前 选项,其中您的服务器获得访问符并直接传递给 SDK 。 在运行前, 使用 PKCE 流量生成访问令牌 :
使用 PKCE 流程生成访问文件夹
所需范围 :
core.aiservices.readknowledge.portalmgr.managecore.customermgr.read(仅要求AI代理客户自我服务)
样本代码
import { AiAgent } from "@egain/ai-agent-sdk";
const agent = new AiAgent({
id: "your-agent-id",
endpoint: "https://your-endpoint.com",
auth: { type: "pre-auth", accessToken: "your-access-token" },
autoConnect: true
});
agent.on("agentMessage", (event) => {
console.log("Agent:", event.payload.message?.content);
});
agent.on("error", (event) => {
console.error("Error:", event.payload.error);
});
await agent.initialize();
await agent.send("Hello!");
联络点(门户流量)
对于使用门户/剖析管道的代理商,请收听选择事件并呼叫 connect() 之后 initialized数字 :
import { AiAgent } from "@egain/ai-agent-sdk";
const agent = new AiAgent({
id: "your-agent-id",
endpoint: "https://your-endpoint.com",
initParams: { authType: "user", userid: "user-1", platform: "standalone" },
authScheme: "popup"
});
agent.on("portalsAvailable", (e) => agent.selectPortal(e.payload.portals[0]));
agent.on("profilesAvailable", (e) =>
agent.selectUserProfile(e.payload.profiles[0])
);
agent.on("initialized", async () => {
await agent.connect();
});
await agent.initialize();
见 门户初始化 引导全流.
文档
以下网站上公布的文件和类型文件描述 当前发布 (在本文件上方的版本).
📚 完整文档
| 指南 | 说明 |
|---|---|
| 开始 | 导言和概念 |
| 安装 | 设置指令 |
| 快速启动 | 第一次整合 |
| 认证 | 认证策略 |
| 活动 | 事件处理 |
| 门户初始化 | CC 门户/代理/配置管道 |
| 平台连接器 | 连接脚本和 HookContract |
| 信件流动 | 发送/接收信件 |
| API 参考 | 类型Doc:类、界面和方法 |
| 类型 | Portal, (中文(简体) ), UserProfile, (中文(简体) ), AgentListItem,API选项(参见类型Doc索引) |
认证选项
// Pre-Auth (API Key / Token)
auth: { type: "pre-auth", accessToken: "your-access-token" }
// Anonymous
auth: { type: "anonymous" }
// PKCE (Browser OAuth)
auth: {
type: "pkce",
config: {
authorizationUrl: "https://auth.example.com/authorize",
tokenUrl: "https://auth.example.com/token",
clientId: "your-client-id",
redirectUri: "https://your-app.com/callback"
}
}
// Pre-Auth (Server-provided token)
auth: {
type: "pre-auth",
accessToken: "token-from-server"
}
所有内置策略都将访问符视为已失效 5分钟 来文日期 exp,所以会话创建和其他API在服务器的~290s"token"即将到期"的后卫中保持领先. 自定义主机的输出值相同 :
import {
ACCESS_TOKEN_REFRESH_BUFFER_MS,
ACCESS_TOKEN_REFRESH_BUFFER_MINUTES
} from "@egain/ai-agent-sdk";
活动
agent.on("connected", (event) => {
/* Connected */
});
agent.on("agentMessage", (event) => {
/* Agent response */
});
agent.on("message", (event) => {
/* Any message */
});
agent.on("heartbeat", (event) => {
/* Agent typing */
});
agent.on("error", (event) => {
/* Error occurred */
});
agent.on("closed", (event) => {
/* Disconnected */
});
agent.on("stateChanged", (event) => {
/* State change */
});
agent.on("queueFlushed", (event) => {
/* Queue sent */
});
agent.on("tokenExpiring", (event) => {
/* Token refresh needed */
});
agent.on("transcriptUpdate", (event) => {
/* Chat transcript line */
});
agent.on("initialized", (event) => {
/* CC init done; safe to connect */
});
agent.on("portalsAvailable", (event) => {
/* Call selectPortal */
});
agent.on("agentsAvailable", (event) => {
/* Call selectAgent */
});
agent.on("profilesAvailable", (event) => {
/* Call selectUserProfile */
});
agent.on("contextValidation", (event) => {
/* Rejected context attributes */
});
信件帮助
import {
createContextMessage,
createFeedbackMessage,
createEscalationMessage
} from "@egain/ai-agent-sdk";
// Send context (auto-cached for reconnect)
await agent.send(
createContextMessage({
context: { userId: "123", language: "en" }
})
);
// Send feedback
await agent.send(
createFeedbackMessage({
rating: 5,
answerMessageId: "msg-456"
})
);
// Trigger escalation
await agent.send(
createEscalationMessage({
escalationEvent: { type: "transfer", reason: "complex" }
})
);
节点.js 设置
npm install ws
SDK 自动加载 ws 在 Node.js 中运行时的软件包。 只是导入和使用 :
import { AiAgent } from "@egain/ai-agent-sdk";
const agent = new AiAgent({
id: "your-agent-id",
endpoint: "https://your-endpoint.com",
auth: { type: "pre-auth", accessToken: process.env.AI_AGENT_TOKEN }
});
// ... rest of code
如果自动多填在您的环境中不起作用,您可以手动设置:
import WebSocket from "ws";
(global as any).WebSocket = WebSocket;
import { AiAgent } from "@egain/ai-agent-sdk";
// ... rest of code
浏览器( UMD)
<script src="https://unpkg.com/@egain/ai-agent-sdk/dist/browser.js"></script>
<script>
const agent = new eGain.AiAgent({ ... });
</script>
发展
# Install dependencies
npm install
# Build
npm run build:all
# Test
npm test
# Documentation
npm run docs:dev # Dev server
npm run docs:build # Build docs
实例
见 使用实例 完整示例:
- 基本用途 - 简单开始
- 浏览器测试 - 与UI的浏览器集成
- 服务器测试 - 节点执行
API 参考
代理方法
| 方法 | 说明 |
|---|---|
initialize(options?) | 初始化代理( 可选) { context } 用于门户/配置自动选择) |
connect() | 连接到服务器 |
disconnect(options?) | 从服务器断开连接 |
restartConnection() | 重新开始新会话 |
send(data, options?) | 发送消息 |
maskContent(text) | 带有加载图案(UI/升级; send() 自动保存符合条件的口罩信件) |
getState() | 获取连接状态 |
isConnected() | 检查是否连接 |
getTranscript(options?) | 拿谈话记录 |
getContext() | 获取存储上下文 |
removeContext() | 删除已存储的上下文 |
updateAccessToken(token) | 更新认证令牌 |
selectPortal(portal) | CC: 继续 portalsAvailable |
selectAgent(agent) | CC 流程B: 之后继续 agentsAvailable |
selectUserProfile(profile) | CC: 继续 profilesAvailable |
getInitParams() | 已配置副本 initParams |
getIsInitialized() | 是否为 initialize() 完成 |
restartPortalInitializer() | CC门户管道(或 restartConnection 倒计时) |
updateUserProfile(profile) | 在 CC init 后切换配置文件( Persists 选择, 抓取配置文件列表缓存, 重新启动会话) |
getUserDetails() | 用户/客户在代理人被认证时从init(或 null(中文(简体) ) |
getCallTranscript() 编号 : clearCallTranscript() | 电话通话记录(连接器) |
getCallerInfo() 编号 : getConversationId() | 连接器提供的 CTI 状态 |
配置
new AiAgent({
id: string, // Required: Agent ID
endpoint: string, // Required: Endpoint URL
auth?: AuthenticationInput, // Optional: Auth config (defaults to anonymous)
autoConnect?: boolean, // Auto-connect (default: false)
maxQueueSize?: number, // Queue size (default: 1000)
maxReconnectAttempts?: number, // Reconnect attempts (default: Infinity)
baseReconnectDelay?: number, // Base delay ms (default: 1000)
maxReconnectDelay?: number, // Max delay ms (default: 30000)
logLevel?: LogLevel, // Log level (default: INFO)
transcriptConfig?: TranscriptConfig,
cache?: CacheConfig,
sessionId?: string | number, // Skip session fetch if already known
initParams?: Record<string, string>, // CC: portalIds, authType, platform, etc.
context?: Record<string, unknown>, // Optional; merged with initialize({ context })
platformScriptUrl?: string, // Override connector script URL
authScheme?: "popup" | "redirect" // Auto-built PKCE only
});
许可证
麻省理工学院