midwayjs-art-openai
v0.0.1
Published
OpenAI integration for Midway.js framework
Maintainers
Readme
midwayjs-art-openai
基于 Midway.js 的 OpenAI 组件封装,支持所有 OpenAI 原生 API 和参数。
安装
npm install midwayjs-art-openai openai快速开始
1. 引入组件
在 src/configuration.ts 中导入:
import { Configuration } from '@midwayjs/core';
import * as koa from '@midwayjs/koa';
import * as openai from 'midwayjs-art-openai';
@Configuration({
imports: [
koa,
openai, // 引入 OpenAI 组件
],
importConfigs: [
{
default: defaultConfig,
},
],
})
export class MainConfiguration {
// ...
}2. 配置
在 src/config/config.default.ts 中配置:
import { MidwayConfig } from '@midwayjs/core';
export default {
openai: {
default: {
apiKey: 'sk-xxxxx', // 您的 API Key
baseURL: 'https://api.openai.com/v1', // 或者自定义的 API 地址
timeout: 60000,
maxRetries: 2,
},
},
} as MidwayConfig;3. 使用
import { Controller, Get, Inject } from '@midwayjs/core';
import { OpenAIService } from 'midwayjs-art-openai';
@Controller('/')
export class HomeController {
@Inject()
openaiService: OpenAIService;
@Get('/chat')
async chat() {
// 直接使用 OpenAI 原生 API
const response = await this.openaiService.client.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: '你好' }],
stream: false,
});
return response.choices[0]?.message?.content;
}
}完整示例
控制器示例(支持流式和非流式响应)
import { Controller, Get, HttpServerResponse, Inject, Query } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { OpenAIService } from 'midwayjs-art-openai';
@Controller('/')
export class HomeController {
@Inject()
openaiService: OpenAIService;
@Inject()
ctx: Context;
@Get('/')
async home(@Query('isStream') isStream: string = 'false') {
const isStreamMode = isStream === 'true';
if (isStreamMode) {
// 流式响应
const res = new HttpServerResponse(this.ctx).sse();
setTimeout(async () => {
try {
const stream = await this.openaiService.client.chat.completions.create({
model: 'qwen-plus',
messages: [{ role: 'user', content: '你好' }],
stream: true,
});
for await (const chunk of stream) {
res.send({
data: JSON.stringify(chunk)
});
if (chunk.choices[0]?.finish_reason === 'stop' ||
chunk.choices[0]?.finish_reason === 'length') {
res.end();
return;
}
}
res.end();
} catch (error) {
res.sendError(error);
}
}, 0);
return res;
} else {
// 非流式响应
try {
const response = await this.openaiService.client.chat.completions.create({
model: 'qwen-plus',
messages: [{ role: 'user', content: '你好' }],
stream: false,
});
return new HttpServerResponse(this.ctx).success().json(response);
} catch (error) {
return new HttpServerResponse(this.ctx).fail().json({
error: error.message
});
}
}
}
}配置示例
// src/config/config.default.ts
export default {
openai: {
default: {
apiKey: 'sk-xxxxx',
baseURL: 'http://llm-openapi.xxx.com/v1', // 支持自定义 API 地址
timeout: 60000,
maxRetries: 2,
},
// 可选:多客户端配置
// clients: {
// image: {
// apiKey: 'sk-image-xxxxx',
// timeout: 120000,
// },
// },
},
} as MidwayConfig;支持的 API
此组件支持所有 OpenAI 原生 API,包括:
- 聊天完成:
client.chat.completions.create() - 图像生成:
client.images.generate() - 嵌入向量:
client.embeddings.create() - 音频转录:
client.audio.transcriptions.create() - 语音合成:
client.audio.speech.create() - 文件管理:
client.files.* - 微调:
client.fineTuning.* - 模型列表:
client.models.list()
配置选项
interface OpenAIConfig {
apiKey?: string; // API Key
baseURL?: string; // API 基础 URL
organization?: string; // 组织 ID
project?: string; // 项目 ID
timeout?: number; // 请求超时时间(毫秒)
maxRetries?: number; // 最大重试次数
defaultHeaders?: Record<string, string>; // 默认请求头
// ... 支持所有 OpenAI ClientOptions 参数
}环境变量
可通过环境变量设置(配置文件中的值会覆盖环境变量):
OPENAI_API_KEY: OpenAI API KeyOPENAI_ORG_ID: 组织 ID(可选)OPENAI_PROJECT_ID: 项目 ID(可选)
特性
- ✅ 支持所有 OpenAI API 和参数
- ✅ 直接使用 OpenAI 原生类型和方法
- ✅ 支持流式和非流式响应
- ✅ 通过 Midway 配置系统管理
- ✅ 支持多客户端配置
- ✅ 支持自定义 API 地址(如私有部署)
- ✅ 完整的 TypeScript 类型支持
