DashScope Node.js SDK - Official Node.js client library for Alibaba Cloud DashScope API
npm install dashscope-sdk-nodejssrc/common/constants.ts - 常量定义
src/common/error.ts - 异常类定义
src/common/api_key.ts - API密钥管理
src/common/utils.ts - 工具函数
src/version.ts - SDK版本信息
src/api_entities/dashscope_response.ts - 响应数据结构
DashScopeAPIResponse - 基础响应类
GenerationResponse - 生成响应
MultiModalConversationResponse - 多模态对话响应
Message, Role, Choice等辅助类型
src/client/base_api.ts - 基础API客户端
BaseApi - 同步API基类
BaseAsyncApi - 异步API基类
BaseAioApi - 异步/等待API基类
src/aigc/generation.ts - 文本生成API
Generation - 同步生成API
AioGeneration - 异步生成API
src/index.ts - 主导出文件
typescript
// Python SDK风格
import { Generation } from 'dashscope-sdk-nodejs';
const response = await Generation.call(
'qwen-turbo',
'你好,请介绍一下自己',
undefined, // history
apiKey,
messages,
plugins,
workspace,
options
);
`
$3
- 所有API都有完整的类型定义
- 自动类型推断
- 编译时类型检查
$3
`typescript
import { AuthenticationError, InvalidParameter } from 'dashscope-sdk-nodejs';
try {
await Generation.call(...);
} catch (error) {
if (error instanceof AuthenticationError) {
// 处理认证错误
}
}
`
$3
`typescript
const stream = await Generation.call(
'qwen-turbo',
'写一个故事',
undefined,
apiKey,
undefined,
undefined,
undefined,
{ stream: true }
);
for await (const chunk of stream) {
console.log(chunk.output.text);
}
`
安装和使用
$3
`bash
npm install dashscope-sdk-nodejs
`
$3
`typescript
import { Generation, saveApiKey } from 'dashscope-sdk-nodejs';
// 设置API密钥
saveApiKey('your-api-key');
// 调用生成API
const response = await Generation.call(
'qwen-turbo',
'你好,请介绍一下自己'
);
console.log(response.output.text);
`
$3
`typescript
import { AioGeneration } from 'dashscope-sdk-nodejs';
const response = await AioGeneration.call(
'qwen-turbo',
'写一首关于春天的诗'
);
console.log(response.output.text);
`
项目结构
`
dashscope-sdk-nodejs/
├── src/
│ ├── common/ # 通用模块
│ │ ├── constants.ts
│ │ ├── error.ts
│ │ ├── api_key.ts
│ │ └── utils.ts
│ ├── api_entities/ # API实体
│ │ └── dashscope_response.ts
│ ├── client/ # 客户端
│ │ └── base_api.ts
│ ├── aigc/ # AIGC功能
│ │ └── generation.ts
│ ├── version.ts # 版本信息
│ └── index.ts # 主入口
├── package.json
├── tsconfig.json
├── rollup.config.js
└── README.md
``