diff --git a/src/commands/form/_ai.ts b/src/commands/form/_ai.ts index 59a117f..2bade93 100644 --- a/src/commands/form/_ai.ts +++ b/src/commands/form/_ai.ts @@ -1,15 +1,23 @@ /** - * _ai.ts — AI 端点封装 (白皮书 5.10) + * _ai.ts — AI 端点封装 (v0.11+ model-agnostic 双路径) * - * 复用 JNPF 平台已部署的 AI 能力, 不重复造 LLM 调用: - * - POST /api/visualdev/ai/form → 5.10.1 AI 快速建表 (描述 → form schema) - * - POST /api/workflow/ai → 5.10.3 AI 创建流程 (描述 → BPMN xml) + * 设计: + * 路径 1 (直连 AI): env 配 DACLI_AI_BASE_URL/AUTH_TOKEN/MODEL + * - 不依赖 JNPF backend, 可用任何 OpenAI/Anthropic 兼容 API + * - 调 GEN_MODEL_QUESTION prompt (来自 JNPF 后端原版) + * - 适合 dacli 自部署 / 多模型场景 * - * 平台在 AI 模型管理 (5.10.5) 配置 default model, 后端自动用; - * dacli 不需要选模型, 也不存 LLM API key。 + * 路径 2 (JNPF backend): 默认 fallback + * - POST /api/visualdev/ai/form → JNPF 后端内部调配置的 AI + * - 适合多用户共享 Qwen 配置 + 走 JNPF 权限审计 + * + * 切换: + * 配 env → 走路径 1 + * 不配 → 走路径 2 */ import { JnpfClient } from '../../core/client.ts' import { log } from '../../core/log.ts' +import { GEN_MODEL_QUESTION, GEN_FLOW_QUESTION } from './_ai_prompts.ts' /** AI 返回的 form 模型 (5.10.1) */ export interface AiFormModel { @@ -39,10 +47,154 @@ export interface AiWorkflowResponse { sortCode?: number } -/** 5.10.1 — AI 快速建表 */ +/** 5.10.1 — AI 快速建表(双路径) */ export async function callAiForm(keyword: string): Promise { + if (hasDirectAiConfig()) { + return callDirectAi(keyword) + } + return callJnpfBackendAi(keyword) +} + +/** 5.10.3 — AI 创建流程(双路径) */ +export async function callAiWorkflow(keyword: string): Promise { + if (hasDirectAiConfig()) { + return callDirectAiFlow(keyword) + } + return callJnpfBackendAiFlow(keyword) +} + +// ============ 路径 1: 直连 AI ============ + +interface DirectAiConfig { + baseUrl: string + authToken: string + model: string + isAnthropic: boolean // true=Anthropic 格式, false=OpenAI 兼容 +} + +function hasDirectAiConfig(): boolean { + return !!(process.env.DACLI_AI_BASE_URL && process.env.DACLI_AI_AUTH_TOKEN && process.env.DACLI_AI_MODEL) +} + +function readDirectAiConfig(): DirectAiConfig { + const baseUrl = process.env.DACLI_AI_BASE_URL! + const authToken = process.env.DACLI_AI_AUTH_TOKEN! + const model = process.env.DACLI_AI_MODEL! + // 简单判断: URL 含 '/anthropic' 用 Anthropic 格式, 否则 OpenAI + const isAnthropic = baseUrl.includes('/anthropic') + return { baseUrl, authToken, model, isAnthropic } +} + +async function callDirectAi(keyword: string): Promise { + const cfg = readDirectAiConfig() + log.info(`[直连 AI] model=${cfg.model} baseUrl=${cfg.baseUrl} format=${cfg.isAnthropic ? 'Anthropic' : 'OpenAI'}`) + const userInput = `当前业务需求是:${keyword}` + const text = cfg.isAnthropic + ? await callAnthropic(cfg, GEN_MODEL_QUESTION, userInput) + : await callOpenAi(cfg, GEN_MODEL_QUESTION, userInput) + return parseAiFormText(text, keyword) +} + +async function callDirectAiFlow(keyword: string): Promise { + const cfg = readDirectAiConfig() + log.info(`[直连 AI - flow] model=${cfg.model} baseUrl=${cfg.baseUrl}`) + const userInput = `当前业务需求是:${keyword}` + const text = cfg.isAnthropic + ? await callAnthropic(cfg, GEN_FLOW_QUESTION, userInput) + : await callOpenAi(cfg, GEN_FLOW_QUESTION, userInput) + return parseAiFlowText(text) +} + +async function callOpenAi(cfg: DirectAiConfig, systemPrompt: string, userInput: string): Promise { + const resp = await fetch(`${cfg.baseUrl}/v1/chat/completions`, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${cfg.authToken}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + model: cfg.model, + messages: [ + { role: 'system', content: systemPrompt }, + { role: 'user', content: userInput }, + ], + max_tokens: 2000, + }), + }) + if (!resp.ok) { + const errText = await resp.text() + throw new Error(`OpenAI 兼容 API 调用失败: HTTP ${resp.status} ${errText.slice(0, 200)}`) + } + const data: any = await resp.json() + return data.choices?.[0]?.message?.content || '' +} + +async function callAnthropic(cfg: DirectAiConfig, systemPrompt: string, userInput: string): Promise { + const resp = await fetch(`${cfg.baseUrl}/v1/messages`, { + method: 'POST', + headers: { + 'x-api-key': cfg.authToken, + 'anthropic-version': '2023-06-01', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + model: cfg.model, + max_tokens: 2000, + system: systemPrompt, + messages: [{ role: 'user', content: userInput }], + }), + }) + if (!resp.ok) { + const errText = await resp.text() + throw new Error(`Anthropic API 调用失败: HTTP ${resp.status} ${errText.slice(0, 200)}`) + } + const data: any = await resp.json() + return (data.content?.filter((b: any) => b.type === 'text').map((b: any) => b.text).join('\n')) || '' +} + +function parseAiFormText(text: string, keyword: string): AiFormResponse { + // 提取第一个 [...] JSON 数组 + const startIdx = text.indexOf('[') + const endIdx = text.lastIndexOf(']') + if (startIdx === -1 || endIdx === -1) { + throw new Error(`AI 返回中没有 JSON 数组: ${text.slice(0, 200)}`) + } + const jsonStr = text.slice(startIdx, endIdx + 1) + let aiModelList: AiFormModel[] + try { + aiModelList = JSON.parse(jsonStr) + } catch (e: any) { + throw new Error(`AI 返回 JSON 解析失败: ${e.message}, 原文: ${jsonStr.slice(0, 200)}`) + } + if (!Array.isArray(aiModelList) || aiModelList.length === 0) { + throw new Error(`AI 返回为空或不是数组: ${jsonStr.slice(0, 200)}`) + } + // 强制 isMain(对齐 JNPF 后端 VisualAiServiceImpl.setIsMain(0, i==0)) + aiModelList.forEach((m, i) => { m.isMain = (i === 0) }) + // 兼容字段: enCode = lowerCamel(tableName), fullName = tableTitle (JNPF 后端 VisualAiServiceImpl 行为) + const first = aiModelList[0] + const enCode = first.tableName ? lowerCamel(first.tableName) : '' + return { + enCode, + fullName: first.tableTitle, + aiModelList, + } +} + +function parseAiFlowText(text: string): AiWorkflowResponse { + // TODO: flow 解析(暂不实现,等流程场景触发再补) + return { flowXml: text } +} + +function lowerCamel(s: string): string { + return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase()) +} + +// ============ 路径 2: JNPF backend (原版) ============ + +async function callJnpfBackendAi(keyword: string): Promise { const c = await JnpfClient.fromToken() - log.info(`POST /visualdev/ai/form keyword="${keyword}"`) + log.info(`[JNPF backend] POST /visualdev/ai/form keyword="${keyword}"`) const r = await c.postJson('/visualdev/ai/form', { keyword }) if (r.code !== 200) { throw new Error(`AI 建表失败 (code=${r.code}): ${r.msg}`) @@ -50,10 +202,9 @@ export async function callAiForm(keyword: string): Promise { return r.data || {} } -/** 5.10.3 — AI 创建流程 */ -export async function callAiWorkflow(keyword: string): Promise { +async function callJnpfBackendAiFlow(keyword: string): Promise { const c = await JnpfClient.fromToken() - log.info(`POST /workflow/ai keyword="${keyword}"`) + log.info(`[JNPF backend] POST /workflow/ai keyword="${keyword}"`) const r = await c.postJson('/workflow/ai', { keyword }) if (r.code !== 200) { throw new Error(`AI 创建流程失败 (code=${r.code}): ${r.msg}`) @@ -61,6 +212,8 @@ export async function callAiWorkflow(keyword: string): Promise