npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

midwayjs-art-openai

v0.0.1

Published

OpenAI integration for Midway.js framework

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 Key
  • OPENAI_ORG_ID: 组织 ID(可选)
  • OPENAI_PROJECT_ID: 项目 ID(可选)

特性

  • ✅ 支持所有 OpenAI API 和参数
  • ✅ 直接使用 OpenAI 原生类型和方法
  • ✅ 支持流式和非流式响应
  • ✅ 通过 Midway 配置系统管理
  • ✅ 支持多客户端配置
  • ✅ 支持自定义 API 地址(如私有部署)
  • ✅ 完整的 TypeScript 类型支持