模型自定义接入:高级接入

更新时间: 2025-02-19 23:45:29

高级接入换你来做主:server.js 导出一个对象,启动、探活、停止、取配置、执行调用都由你实现,AIGCPanel 只负责按名字调方法。适合模型本身是个常驻服务、需要固定端口、或者推理前后要连一堆外部资源的情况。

前置条件是 Node 能跑起来,并且看得懂 async/await。你写的是主进程里的模块,不是浏览器环境,fs、child_process 都能用。

软件怎么加载它

模型目录里有 server.js 时,软件 import() 它并取 default 导出的对象;没有 server.js 才回头看 config.json 的 entry。所以两个文件都放时,server.js 优先,entry 不参与启动。

加载后会做三件事:把 this.ServerApi 指向内部接口集合,把 this.ServerInfo 指向当前模型信息,再挂上 this.send 和 this.sendLog。你的方法里直接用 this 就能拿到这些。

config.json

有 server.js 时 config.json 只负责声明,entry 不参与启动,写入口文件名即可。别写 __EasyServer__,写了会连带打开「导入后默认自启动」。

{
"name": "server-mymodel",
"version": "1.0.0",
"title": "我的模型",
"description": "常驻 HTTP 服务的模型",
"platformName": "win",
"platformArch": "x86",
"serverRequire": ">=2.7.0",
"entry": "main.py",
"functions": ["soundTts", "videoGen"],
"settings": [
{
"name": "port",
"title": "服务端口",
"type": "text",
"placeholder": "留空自动分配"
}
]
}

这里的 functions 用数组就够了,能力的参数表单由 config() 的返回值决定,不用在 config.json 里重复写一遍。

要实现的五个入口

方法什么时候被调必须做什么
start()用户点「启动」拉起模型进程或服务,成功后 send('success')
ping()界面轮询状态时返回 true/false,决定卡片显示运行中还是已停止
stop()用户点「停止」、退出软件结束进程,send('stopped')
config()打开功能页、渲染参数表单前返回 httpUrl、content、functions
能力方法功能页提交任务执行一次推理,返回 {code, msg, data}

start 和 stop

start() 里选端口、起进程。端口优先用用户在设置面板填的,没填就找空闲的:

module.exports = {
ServerInfo: null,
ServerApi: null,
runtime: { port: 0, proc: null, busy: false },

url() {
return `http://127.0.0.1:${this.runtime.port}/`;
},

async start() {
this.send('starting', this.ServerInfo);
const setting = this.ServerInfo.setting || {};
let port = parseInt(setting.port || '0', 10);
if (!port || !(await this.ServerApi.app.isPortAvailable(port))) {
port = await this.ServerApi.app.availablePort(50617);
}
this.runtime.port = port;

const root = this.ServerInfo.localPath;
const python = process.platform === 'win32'
? `${root}/_aienv/python.exe`
: `${root}/_aienv/bin/python`;

this.runtime.proc = await this.ServerApi.app.spawnShell(
[python, 'main.py', '--port', String(port)],
{
cwd: root,
env: {
PATH: this.ServerApi.getPathEnv([root, `${root}/binary`]),
PYTHONIOENCODING: 'utf-8',
},
stdout: (data) => this.sendLog(data),
stderr: (data) => this.sendLog(data),
success: () => this.send('success', this.ServerInfo),
error: (msg) => {
this.sendLog(msg);
this.send('error', this.ServerInfo);
},
},
);
},

async ping() {
if (!this.runtime.port) {
return false;
}
try {
const res = await this.ServerApi.request(`${this.url()}ping`);
return res && res.code === 0;
} catch (e) {
return false;
}
},

async stop() {
this.send('stopping', this.ServerInfo);
if (this.runtime.proc) {
this.runtime.proc.stop();
this.runtime.proc = null;
}
this.runtime.port = 0;
this.send('stopped', this.ServerInfo);
},
// ...
};

spawnShell 返回的控制器有 stop()、kill()、send()、result()、pid。stop() 在 Windows 走 taskkill /T /F,会把子进程一起带走;kill() 是直接杀当前进程。

ping() 不要只看自己的变量。进程崩了但 runtime.port 还在,界面就会一直显示运行中。发一次真实请求最稳。

config() 决定界面长什么样

async config() {
return {
code: 0,
msg: 'ok',
data: {
httpUrl: this.runtime.port ? this.url() : null,
content: '模型说明,会显示在功能页的「模型说明」弹窗里。',
functions: {
soundTts: {
content: '支持中英文,单次 500 字以内。',
param: [
{
name: 'speed',
title: '语速',
type: 'slider',
defaultValue: 1,
min: 0.5,
max: 2,
step: 0.1,
},
],
result: [{ type: 'file', name: 'url', title: '合成音频' }],
},
videoGen: {
param: [],
result: [{ type: 'file', name: 'url', title: '合成视频' }],
},
},
},
};
}

httpUrl 会显示在模型信息里,带一个跳转按钮,可以指向模型自带的调试页面;没有就给 null。functions 必须是对象,键是能力名,param 的字段类型和简易接入完全一样。

能力方法

方法名就是能力名,参数是一个对象,返回 {code, msg, data}。

async soundTts(data) {
// data = { id, result, param, text }
if (this.runtime.busy) {
return { code: 0, msg: 'ok', data: { type: 'retry' } };
}
this.runtime.busy = true;
const start = Date.now();
try {
this.send('taskRunning', { id: data.id });
const ret = await this.ServerApi.requestPost(`${this.url()}tts`, {
text: data.text,
param: data.param || {},
});
return {
code: 0,
msg: 'ok',
data: {
type: 'success',
start,
end: Date.now(),
data: { url: `${this.ServerInfo.localPath}/${ret.data.file}` },
},
};
} finally {
this.runtime.busy = false;
}
},

data 里有什么,按能力固定:

能力字段
soundTtsid、result、param、text
soundCloneid、result、param、text、promptAudio、promptText
videoGenid、result、param、video、audio
asrid、result、param、audio
textToImageid、result、param、prompt
imageToImageid、result、param、image、prompt
textToVideoid、result、param、prompt
imageToVideoid、result、param、prompt、images

返回值的 data.type 只有两个合法值:success 和 retry。别写 querying、running 这类,界面会当成未知类型直接报错。忙的时候返回 retry,调用方每秒重试一次,最多 60 次。

结果字段要和 config() 里 result 声明的一致:合成、生成类给 url(本地绝对路径),语音识别给 records。

方法里抛异常不用自己包 try,软件会捕获并把 msg 显示在任务上:

if (!fs.existsSync(input)) {
throw new Error(`输入文件不存在:${input}`);
}

如果方法名写错或漏了,调用时会报 MethodNotFound : soundTts,这句只在模型日志里能看到,界面只显示「执行失败,请查看模型日志」。

这几个接口够用了

接口用途
this.ServerInfo.localPath模型目录绝对路径
this.ServerInfo.setting设置面板里填的值
this.ServerInfo.logFile日志文件路径
this.ServerApi.app.spawnShell(cmd, option)起子进程,拿控制器
this.ServerApi.app.availablePort(start)从 start 往上找空闲端口
this.ServerApi.app.isPortAvailable(port)判断端口能不能用
this.ServerApi.request / requestPost / requestGet发 HTTP 请求,默认返回 JSON
this.ServerApi.file.appendText(path, text)往文件追加内容
this.send(type, data)给界面推事件,如 starting、error、taskRunning
this.sendLog(text)写模型日志

和简易接入怎么选

要改现有的 Python 脚本、任务是一锤子买卖,用简易接入,少写一半代码。模型本身已经是常驻 HTTP 服务、要复用一个加载好的权重、或者要在启动阶段做很多准备,再用这条。

两种方式可以共存:先按简易接入跑通协议,再把 run.py 包成服务、换成 server.js,functions 和 param 一个字都不用改。

相关

语言
QQ
微信客服
微信群
客服