身份认证
SDK 需要 NovelAI API Key 进行身份认证。
获取 API Key
- 登录 NovelAI
- 进入账户设置
- 导航到 API 部分
- 生成或复制你的 API Key
配置方式
环境变量(推荐)
设置 NOVELAI_API_KEY 环境变量:
bash
export NOVELAI_API_KEY=your_api_key_here然后无需参数初始化客户端:
typescript
import { NovelAI } from 'novelai-sdk-unofficial';
const client = new NovelAI();直接初始化
直接将 API Key 传递给构造函数:
typescript
import { NovelAI } from 'novelai-sdk-unofficial';
const client = new NovelAI({ apiKey: 'your-api-key' });使用 .env 文件
配合 dotenv 等包使用:
typescript
import 'dotenv/config';
import { NovelAI } from 'novelai-sdk-unofficial';
const client = new NovelAI();客户端选项
typescript
const client = new NovelAI({
apiKey: 'your-api-key', // API Key
imageBase: 'https://...', // 自定义图像 API 基础 URL
textBase: 'https://...', // 自定义文本 API 基础 URL
timeout: 30000, // 请求超时时间(毫秒,默认 30000)
});错误处理
如果未提供 API Key,SDK 会抛出 MissingAPIKeyError:
typescript
import { NovelAI, MissingAPIKeyError } from 'novelai-sdk-unofficial';
try {
const client = new NovelAI();
} catch (error) {
if (error instanceof MissingAPIKeyError) {
console.error('请提供 API Key');
}
}资源清理
客户端实例可以重复使用,无需每次请求都创建新实例。