feat: 多功能更新
This commit is contained in:
@@ -1,23 +0,0 @@
|
||||
export interface IDownloadedImage {
|
||||
/** 图片 base64 原文,不包含 data URL 前缀 */
|
||||
base64: string;
|
||||
/** 图片 MIME 类型 */
|
||||
mimeType: string;
|
||||
}
|
||||
|
||||
/** 下载远程图片并转成 base64,用于生图结果归档 */
|
||||
export const downloadImageAsBase64 = async (
|
||||
imageUrl: string
|
||||
): Promise<IDownloadedImage> => {
|
||||
const response = await fetch(imageUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`图片下载失败:${response.status}`);
|
||||
}
|
||||
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
|
||||
return {
|
||||
base64: Buffer.from(arrayBuffer).toString("base64"),
|
||||
mimeType: response.headers.get("content-type") || "image/png"
|
||||
};
|
||||
};
|
||||
@@ -14,17 +14,19 @@ const DEFAULT_IMAGE_MODEL = "gpt-image-2";
|
||||
const DEFAULT_IMAGE_SIZE = "1024x1024";
|
||||
|
||||
interface IFinishImageGenerationSuccessInput {
|
||||
/** 生成图片 URL */
|
||||
/** NewAPI 上游返回的生成图片 URL */
|
||||
imageUrl: string;
|
||||
/** 生成图片 base64 原文 */
|
||||
imageBase64: string | null;
|
||||
/** 图片 MIME 类型 */
|
||||
/** Lsky 图床归档后的图片 URL,归档失败时为空 */
|
||||
hostedImageUrl: string | null;
|
||||
/** 图片 MIME 类型,优先来自图床上传结果 */
|
||||
imageMimeType: string | null;
|
||||
/** 上游返回的修订提示词 */
|
||||
/** 上游返回的修订提示词,流式生图通常为空 */
|
||||
revisedPrompt?: string | null;
|
||||
/** 完整上游响应 */
|
||||
/** 完整上游响应,当前为 chat completions 流式聚合对象 */
|
||||
upstreamResponse: unknown;
|
||||
/** 成功状态下的非阻断提示,例如 base64 保存失败 */
|
||||
/** 完整 Lsky 上传响应,归档失败时为空 */
|
||||
hostedResponse: unknown;
|
||||
/** 成功状态下的非阻断提示,例如图床归档失败 */
|
||||
errorMessage?: string | null;
|
||||
}
|
||||
|
||||
@@ -65,6 +67,23 @@ export const ensureUserRecord = (userId: number) => {
|
||||
});
|
||||
};
|
||||
|
||||
/** 读取用于 Lsky 文件命名的用户标识,缺失时由调用方使用兜底名 */
|
||||
export const getUserArchiveIdentity = async (userId: number) => {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: userId
|
||||
},
|
||||
select: {
|
||||
username: true,
|
||||
displayName: true
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
username: user?.username || user?.displayName || "user"
|
||||
};
|
||||
};
|
||||
|
||||
/** 创建进行中的生图记录,并递增全局请求与进行中统计 */
|
||||
export const createRunningImageGeneration = async (
|
||||
userId: number,
|
||||
@@ -94,56 +113,34 @@ export const createRunningImageGeneration = async (
|
||||
return record;
|
||||
};
|
||||
|
||||
/** 将生图记录标记为成功,并保存 URL、base64、完整上游响应和耗时 */
|
||||
/** 将生图记录标记为成功,并保存上游 URL、图床 URL、完整响应和耗时 */
|
||||
export const finishImageGenerationSuccess = async (
|
||||
recordId: bigint,
|
||||
startedAt: Date,
|
||||
input: IFinishImageGenerationSuccessInput
|
||||
) => {
|
||||
const endedAt = new Date();
|
||||
const successData = {
|
||||
status: ImageGenerationStatus.SUCCEEDED,
|
||||
endedAt,
|
||||
durationMs: getDurationMs(startedAt, endedAt),
|
||||
imageUrl: input.imageUrl,
|
||||
imageBase64: input.imageBase64,
|
||||
imageMimeType: input.imageMimeType,
|
||||
revisedPrompt: input.revisedPrompt || null,
|
||||
upstreamResponse: input.upstreamResponse as Prisma.InputJsonValue,
|
||||
errorMessage: input.errorMessage || null
|
||||
};
|
||||
|
||||
try {
|
||||
await prisma.imageGeneration.update({
|
||||
where: {
|
||||
id: recordId
|
||||
},
|
||||
data: successData
|
||||
});
|
||||
} catch (error) {
|
||||
if (!input.imageBase64) {
|
||||
throw error;
|
||||
await prisma.imageGeneration.update({
|
||||
where: {
|
||||
id: recordId
|
||||
},
|
||||
data: {
|
||||
status: ImageGenerationStatus.SUCCEEDED,
|
||||
endedAt,
|
||||
durationMs: getDurationMs(startedAt, endedAt),
|
||||
imageUrl: input.imageUrl,
|
||||
hostedImageUrl: input.hostedImageUrl,
|
||||
imageMimeType: input.imageMimeType,
|
||||
revisedPrompt: input.revisedPrompt || null,
|
||||
upstreamResponse: input.upstreamResponse as Prisma.InputJsonValue,
|
||||
hostedResponse:
|
||||
input.hostedResponse === null
|
||||
? Prisma.DbNull
|
||||
: (input.hostedResponse as Prisma.InputJsonValue),
|
||||
errorMessage: input.errorMessage || null
|
||||
}
|
||||
|
||||
consola.error("[imageGenerationRecords] 保存带 base64 的成功记录失败,重试仅保存 URL", {
|
||||
recordId: recordId.toString(),
|
||||
message: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
|
||||
await prisma.imageGeneration.update({
|
||||
where: {
|
||||
id: recordId
|
||||
},
|
||||
data: {
|
||||
...successData,
|
||||
imageBase64: null,
|
||||
errorMessage: mergeRecordMessages(
|
||||
input.errorMessage,
|
||||
"图片生成成功,但 base64 归档保存失败"
|
||||
)
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await safeUpsertGenerationStats({
|
||||
successRequests: {
|
||||
@@ -188,7 +185,7 @@ export const finishImageGenerationFailed = async (
|
||||
});
|
||||
};
|
||||
|
||||
/** 查询当前用户未删除的生图历史列表,不返回 base64 和完整上游响应 */
|
||||
/** 查询当前用户未删除的生图历史列表,不返回完整上游/图床响应 */
|
||||
export const listImageGenerationHistory = async ({
|
||||
userId,
|
||||
page,
|
||||
@@ -223,7 +220,7 @@ export const listImageGenerationHistory = async ({
|
||||
};
|
||||
};
|
||||
|
||||
/** 查询当前用户单条生图历史详情 */
|
||||
/** 查询当前用户单条生图历史详情,包含完整上游与图床响应 */
|
||||
export const getImageGenerationDetail = async (
|
||||
userId: number,
|
||||
recordId: bigint
|
||||
@@ -240,9 +237,9 @@ export const getImageGenerationDetail = async (
|
||||
|
||||
return {
|
||||
...mapImageGenerationItem(record),
|
||||
imageBase64: record.imageBase64,
|
||||
imageMimeType: record.imageMimeType,
|
||||
upstreamResponse: record.upstreamResponse
|
||||
upstreamResponse: record.upstreamResponse,
|
||||
hostedResponse: record.hostedResponse
|
||||
};
|
||||
};
|
||||
|
||||
@@ -345,6 +342,7 @@ const mapImageGenerationItem = (record: {
|
||||
endedAt: Date | null;
|
||||
durationMs: number | null;
|
||||
imageUrl: string | null;
|
||||
hostedImageUrl: string | null;
|
||||
revisedPrompt: string | null;
|
||||
errorMessage: string | null;
|
||||
createdAt: Date;
|
||||
@@ -360,6 +358,7 @@ const mapImageGenerationItem = (record: {
|
||||
endedAt: record.endedAt?.toISOString() ?? null,
|
||||
durationMs: record.durationMs,
|
||||
imageUrl: record.imageUrl,
|
||||
hostedImageUrl: record.hostedImageUrl,
|
||||
revisedPrompt: record.revisedPrompt,
|
||||
errorMessage: record.errorMessage,
|
||||
createdAt: record.createdAt.toISOString()
|
||||
@@ -370,13 +369,6 @@ const getDurationMs = (startedAt: Date, endedAt: Date) => {
|
||||
return Math.max(0, endedAt.getTime() - startedAt.getTime());
|
||||
};
|
||||
|
||||
const mergeRecordMessages = (
|
||||
currentMessage: string | null | undefined,
|
||||
nextMessage: string
|
||||
) => {
|
||||
return currentMessage ? `${currentMessage}; ${nextMessage}` : nextMessage;
|
||||
};
|
||||
|
||||
const getSafeErrorMessage = (error: unknown): string => {
|
||||
if (error instanceof Error) return error.message;
|
||||
if (typeof error === "string") return error;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
export * from "./createApiResponse";
|
||||
export * from "./fetch";
|
||||
export * from "./imageAssets";
|
||||
export * from "./imageGenerationRecords";
|
||||
export * from "./logging";
|
||||
export * from "./lsky";
|
||||
export * from "./newApiAuthCookies";
|
||||
export * from "./newApiTokens";
|
||||
export * from "./openai";
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { consola } from "consola";
|
||||
|
||||
type LogMeta = Record<string, unknown>;
|
||||
|
||||
export const createApiLogger = (scope: string) => {
|
||||
const requestId = randomUUID();
|
||||
const startedAt = Date.now();
|
||||
const prefix = `[${scope}]`;
|
||||
|
||||
const withBaseMeta = (meta?: LogMeta) => ({
|
||||
requestId,
|
||||
...(meta ?? {})
|
||||
});
|
||||
|
||||
return {
|
||||
requestId,
|
||||
info(message: string, meta?: LogMeta) {
|
||||
consola.info(`${prefix} ${message}`, withBaseMeta(meta));
|
||||
},
|
||||
warn(message: string, meta?: LogMeta) {
|
||||
consola.warn(`${prefix} ${message}`, withBaseMeta(meta));
|
||||
},
|
||||
error(message: string, meta?: LogMeta) {
|
||||
consola.error(`${prefix} ${message}`, withBaseMeta(meta));
|
||||
},
|
||||
done(message: string = "完成", meta?: LogMeta) {
|
||||
consola.info(
|
||||
`${prefix} ${message}`,
|
||||
withBaseMeta({
|
||||
...(meta ?? {}),
|
||||
elapsedMs: Date.now() - startedAt
|
||||
})
|
||||
);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export const toSafeLogError = (error: unknown) => {
|
||||
const maybeError = error as {
|
||||
message?: string;
|
||||
name?: string;
|
||||
response?: {
|
||||
status?: number;
|
||||
};
|
||||
stack?: string;
|
||||
status?: number;
|
||||
statusCode?: number;
|
||||
statusMessage?: string;
|
||||
};
|
||||
|
||||
return {
|
||||
name: maybeError.name,
|
||||
message: maybeError.message ?? maybeError.statusMessage,
|
||||
status:
|
||||
maybeError.status ?? maybeError.statusCode ?? maybeError.response?.status,
|
||||
stack: maybeError.stack
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,179 @@
|
||||
import { createError } from "h3";
|
||||
|
||||
interface ILskyUploadInput {
|
||||
imageUrl: string;
|
||||
userId: number;
|
||||
username?: string | null;
|
||||
recordId: bigint;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
interface ILskyUploadResponse {
|
||||
status?: string | boolean;
|
||||
message?: string;
|
||||
data?: {
|
||||
public_url?: string;
|
||||
filename?: string;
|
||||
mimetype?: string;
|
||||
extension?: string;
|
||||
[key: string]: unknown;
|
||||
} | null;
|
||||
time?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ILskyUploadedImage {
|
||||
publicUrl: string;
|
||||
filename: string;
|
||||
mimetype: string;
|
||||
response: ILskyUploadResponse;
|
||||
}
|
||||
|
||||
export const uploadImageFromUrl = async (
|
||||
input: ILskyUploadInput
|
||||
): Promise<ILskyUploadedImage> => {
|
||||
const config = getLskyConfig();
|
||||
const downloadedImage = await downloadImage(input.imageUrl);
|
||||
const extension = getImageExtension(downloadedImage.mimeType, input.imageUrl);
|
||||
const filename = buildArchiveFilename({
|
||||
userId: input.userId,
|
||||
username: input.username,
|
||||
recordId: input.recordId,
|
||||
createdAt: input.createdAt,
|
||||
extension
|
||||
});
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append(
|
||||
"file",
|
||||
new Blob([downloadedImage.bytes], {
|
||||
type: downloadedImage.mimeType
|
||||
}),
|
||||
filename
|
||||
);
|
||||
formData.append("storage_id", String(config.storageId));
|
||||
formData.append("is_remove_exif", "true");
|
||||
formData.append("intro", `AIArtStudio image generation ${input.recordId}`);
|
||||
|
||||
for (const tag of buildArchiveTags(input.userId, input.recordId)) {
|
||||
formData.append("tags[]", tag);
|
||||
}
|
||||
|
||||
const response = await $fetch<ILskyUploadResponse>("/upload", {
|
||||
baseURL: config.baseUrl,
|
||||
method: "POST",
|
||||
body: formData,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${config.token}`
|
||||
}
|
||||
});
|
||||
|
||||
const publicUrl = response.data?.public_url;
|
||||
if (!isSuccessStatus(response.status) || !publicUrl) {
|
||||
throw createError({
|
||||
statusCode: 502,
|
||||
statusMessage: response.message || "图床上传失败"
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
publicUrl,
|
||||
filename: response.data?.filename || filename,
|
||||
mimetype: response.data?.mimetype || downloadedImage.mimeType,
|
||||
response
|
||||
};
|
||||
};
|
||||
|
||||
const getLskyConfig = () => {
|
||||
const baseUrl = process.env.LSKY_BASE_URL?.replace(/\/+$/, "");
|
||||
const token = process.env.LSKY_TOKEN;
|
||||
const storageId = Number.parseInt(process.env.LSKY_STORAGE_ID ?? "", 10);
|
||||
|
||||
if (!baseUrl) {
|
||||
throw new Error("LSKY_BASE_URL 未配置");
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
throw new Error("LSKY_TOKEN 未配置");
|
||||
}
|
||||
|
||||
if (!Number.isInteger(storageId) || storageId <= 0) {
|
||||
throw new Error("LSKY_STORAGE_ID 未配置或不是有效数字");
|
||||
}
|
||||
|
||||
return {
|
||||
baseUrl,
|
||||
token,
|
||||
storageId
|
||||
};
|
||||
};
|
||||
|
||||
const downloadImage = async (imageUrl: string) => {
|
||||
const response = await fetch(imageUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`图片下载失败:${response.status}`);
|
||||
}
|
||||
|
||||
return {
|
||||
bytes: await response.arrayBuffer(),
|
||||
mimeType: response.headers.get("content-type") || "image/png"
|
||||
};
|
||||
};
|
||||
|
||||
const buildArchiveFilename = ({
|
||||
userId,
|
||||
username,
|
||||
recordId,
|
||||
createdAt,
|
||||
extension
|
||||
}: {
|
||||
userId: number;
|
||||
username?: string | null;
|
||||
recordId: bigint;
|
||||
createdAt: Date;
|
||||
extension: string;
|
||||
}) => {
|
||||
const safeUsername = sanitizeFilenamePart(username || "user");
|
||||
const timestamp = formatTimestamp(createdAt);
|
||||
return `${userId}_${safeUsername}_${timestamp}_${recordId.toString()}.${extension}`;
|
||||
};
|
||||
|
||||
const buildArchiveTags = (userId: number, recordId: bigint) => {
|
||||
return [
|
||||
"AIArtStudio",
|
||||
`user:${userId}`,
|
||||
`record:${recordId.toString()}`,
|
||||
"model:gpt-image-2"
|
||||
];
|
||||
};
|
||||
|
||||
const sanitizeFilenamePart = (value: string) => {
|
||||
const sanitized = value
|
||||
.trim()
|
||||
.replace(/[^\p{L}\p{N}_-]+/gu, "_")
|
||||
.replace(/_+/g, "_")
|
||||
.replace(/^_+|_+$/g, "");
|
||||
|
||||
return sanitized || "user";
|
||||
};
|
||||
|
||||
const formatTimestamp = (date: Date) => {
|
||||
return date.toISOString().replace(/\D/g, "").slice(0, 14);
|
||||
};
|
||||
|
||||
const getImageExtension = (mimeType: string, imageUrl: string) => {
|
||||
const fromMimeType = mimeType.split(";")[0]?.trim().toLowerCase();
|
||||
if (fromMimeType === "image/jpeg") return "jpg";
|
||||
if (fromMimeType === "image/png") return "png";
|
||||
if (fromMimeType === "image/webp") return "webp";
|
||||
if (fromMimeType === "image/gif") return "gif";
|
||||
|
||||
const pathname = new URL(imageUrl).pathname;
|
||||
const extension = pathname.split(".").pop()?.toLowerCase();
|
||||
return extension && /^[a-z0-9]+$/.test(extension) ? extension : "png";
|
||||
};
|
||||
|
||||
const isSuccessStatus = (status: unknown) => {
|
||||
return status === true || status === "success" || status === "ok";
|
||||
};
|
||||
+188
-28
@@ -2,27 +2,47 @@
|
||||
import OpenAI from "openai";
|
||||
import type { BaseOptions, IImageGenerateData } from "#shared/types/openai";
|
||||
|
||||
const IMAGE_GENERATION_URL = "https://api.qflink.xyz/v1/images/generations";
|
||||
/** 图像生成改走 Chat Completions 流式接口,通常能更快拿到中转平台返回的图片地址 */
|
||||
const CHAT_COMPLETIONS_URL = "https://api.qflink.xyz/v1/chat/completions";
|
||||
const IMAGE_GENERATION_MODEL = "gpt-image-2";
|
||||
const IMAGE_GENERATION_SIZE = "1024x1024";
|
||||
|
||||
interface IImageGenerationResponse {
|
||||
/** 上游创建时间 */
|
||||
/** Chat Completions SSE 每个 data chunk 的最小结构 */
|
||||
interface IChatCompletionStreamChunk {
|
||||
id?: string;
|
||||
object?: string;
|
||||
created?: number;
|
||||
/** 上游图片生成结果列表 */
|
||||
data?: Array<{
|
||||
/** 上游返回的修订提示词,可能为空 */
|
||||
revised_prompt?: string;
|
||||
/** 生成图片地址 */
|
||||
url?: string;
|
||||
model?: string;
|
||||
metadata?: unknown;
|
||||
choices?: Array<{
|
||||
delta?: {
|
||||
content?: string;
|
||||
role?: string;
|
||||
};
|
||||
finish_reason?: string | null;
|
||||
index?: number;
|
||||
}>;
|
||||
usage?: unknown;
|
||||
}
|
||||
|
||||
/** 聚合后的流式生图上游响应,供服务端入库排查使用,不包含 API Key */
|
||||
interface IImageStreamUpstreamResponse {
|
||||
content: string;
|
||||
imageUrl?: string;
|
||||
chunks: Array<{
|
||||
id?: string;
|
||||
created?: number;
|
||||
model?: string;
|
||||
content?: string;
|
||||
finishReason?: string | null;
|
||||
metadata?: unknown;
|
||||
hasUsage: boolean;
|
||||
}>;
|
||||
/** 上游 token 用量 */
|
||||
usage?: unknown;
|
||||
}
|
||||
|
||||
export interface IAskImageResult extends IImageGenerateData {
|
||||
/** 完整上游生图接口返回结果,仅服务端内部保存 */
|
||||
upstreamResponse: IImageGenerationResponse;
|
||||
upstreamResponse: unknown;
|
||||
}
|
||||
|
||||
/** 通用 AI 调用函数(支持文本 / 图文 / 多模态) */
|
||||
@@ -65,8 +85,7 @@ export const askText = async (
|
||||
* |------|--------------------------|
|
||||
* | low | 低分辨率(更快、更省成本) |
|
||||
* | high | 高分辨率(更精准) |
|
||||
* | auto | 自动选择 |
|
||||
*
|
||||
* | auto | 自动选择 |
|
||||
*/
|
||||
export const askVision = async (
|
||||
options: BaseOptions & {
|
||||
@@ -107,40 +126,77 @@ export const askVision = async (
|
||||
return res.output_text;
|
||||
};
|
||||
|
||||
/** 调用图片生成接口,完整 API Key 只在服务端使用 */
|
||||
export const askImg = async ({
|
||||
/** 调用流式图片生成接口,完整 API Key 只在服务端使用 */
|
||||
export const askImgStream = async ({
|
||||
apiKey,
|
||||
prompt
|
||||
}: {
|
||||
apiKey: string;
|
||||
prompt: string;
|
||||
}): Promise<IAskImageResult> => {
|
||||
const result = await $fetch<IImageGenerationResponse>(IMAGE_GENERATION_URL, {
|
||||
const response = await fetch(CHAT_COMPLETIONS_URL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: {
|
||||
body: JSON.stringify({
|
||||
model: IMAGE_GENERATION_MODEL,
|
||||
prompt,
|
||||
size: IMAGE_GENERATION_SIZE
|
||||
}
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: prompt
|
||||
}
|
||||
]
|
||||
})
|
||||
});
|
||||
|
||||
const image = result.data?.[0];
|
||||
if (!image?.url) {
|
||||
throw new Error("图片生成失败");
|
||||
if (!response.ok) {
|
||||
const message = await response.text().catch(() => "");
|
||||
throw new Error(message || `图片生成失败:${response.status}`);
|
||||
}
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error("图片生成失败:上游没有返回流");
|
||||
}
|
||||
|
||||
const upstreamResponse = await readChatCompletionStream(response.body);
|
||||
const imageUrl = extractImageUrlFromStreamText(upstreamResponse.content);
|
||||
|
||||
return {
|
||||
imageUrl: image.url,
|
||||
revisedPrompt: image.revised_prompt,
|
||||
upstreamResponse: result
|
||||
imageUrl,
|
||||
revisedPrompt: undefined,
|
||||
upstreamResponse: {
|
||||
...upstreamResponse,
|
||||
imageUrl
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/** 调用流式接口 */
|
||||
/** 从流式累积文本中提取图片地址,兼容 Markdown 图片、常见图片 URL 和无扩展下载链接 */
|
||||
export const extractImageUrlFromStreamText = (text: string): string => {
|
||||
const markdownImageMatch = text.match(/!\[[^\]]*]\((https?:\/\/[^)\s]+)\)/i);
|
||||
if (markdownImageMatch?.[1]) {
|
||||
return cleanupImageUrl(markdownImageMatch[1]);
|
||||
}
|
||||
|
||||
const imageUrlMatch = text.match(
|
||||
/https?:\/\/[^\s)>'"]+(?:\.(?:png|jpe?g|webp|gif)(?:\?[^\s)>'"]*)?|\/file_download\/[^\s)>'"]+)/i
|
||||
);
|
||||
if (imageUrlMatch?.[0]) {
|
||||
return cleanupImageUrl(imageUrlMatch[0]);
|
||||
}
|
||||
|
||||
const urlMatch = text.match(/https?:\/\/[^\s)>'"]+/i);
|
||||
if (urlMatch?.[0]) {
|
||||
return cleanupImageUrl(urlMatch[0]);
|
||||
}
|
||||
|
||||
throw new Error("图片生成失败:未找到图片地址");
|
||||
};
|
||||
|
||||
/** 调用 Responses API 流式接口,保留给其他文本/多模态场景复用 */
|
||||
export const askStream = async (
|
||||
options: BaseOptions & {
|
||||
input: OpenAI.Responses.ResponseCreateParams["input"];
|
||||
@@ -158,3 +214,107 @@ export const askStream = async (
|
||||
|
||||
return stream;
|
||||
};
|
||||
|
||||
/** 读取 Chat Completions SSE 流,累积 delta.content 并提取 usage/chunk 元信息 */
|
||||
const readChatCompletionStream = async (
|
||||
stream: ReadableStream<Uint8Array>
|
||||
): Promise<IImageStreamUpstreamResponse> => {
|
||||
const reader = stream.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
const chunks: IImageStreamUpstreamResponse["chunks"] = [];
|
||||
let buffer = "";
|
||||
let content = "";
|
||||
let usage: unknown;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const lines = buffer.split(/\r?\n/);
|
||||
buffer = lines.pop() ?? "";
|
||||
|
||||
for (const line of lines) {
|
||||
const chunk = parseSseDataLine(line);
|
||||
if (!chunk) continue;
|
||||
|
||||
const deltaContent = collectDeltaContent(chunk);
|
||||
if (deltaContent) {
|
||||
content += deltaContent;
|
||||
}
|
||||
|
||||
if (chunk.usage) {
|
||||
usage = chunk.usage;
|
||||
}
|
||||
|
||||
chunks.push({
|
||||
id: chunk.id,
|
||||
created: chunk.created,
|
||||
model: chunk.model,
|
||||
content: deltaContent || undefined,
|
||||
finishReason: chunk.choices?.find((choice) => choice.finish_reason)
|
||||
?.finish_reason,
|
||||
metadata: chunk.metadata,
|
||||
hasUsage: Boolean(chunk.usage)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const finalText = buffer + decoder.decode();
|
||||
for (const line of finalText.split(/\r?\n/)) {
|
||||
const chunk = parseSseDataLine(line);
|
||||
if (!chunk) continue;
|
||||
|
||||
const deltaContent = collectDeltaContent(chunk);
|
||||
if (deltaContent) {
|
||||
content += deltaContent;
|
||||
}
|
||||
|
||||
if (chunk.usage) {
|
||||
usage = chunk.usage;
|
||||
}
|
||||
|
||||
chunks.push({
|
||||
id: chunk.id,
|
||||
created: chunk.created,
|
||||
model: chunk.model,
|
||||
content: deltaContent || undefined,
|
||||
finishReason: chunk.choices?.find((choice) => choice.finish_reason)
|
||||
?.finish_reason,
|
||||
metadata: chunk.metadata,
|
||||
hasUsage: Boolean(chunk.usage)
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
content,
|
||||
chunks,
|
||||
usage
|
||||
};
|
||||
};
|
||||
|
||||
/** 解析单行 SSE data,跳过空行和 [DONE] */
|
||||
const parseSseDataLine = (line: string): IChatCompletionStreamChunk | null => {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed.startsWith("data:")) return null;
|
||||
|
||||
const data = trimmed.slice("data:".length).trim();
|
||||
if (!data || data === "[DONE]") return null;
|
||||
|
||||
return JSON.parse(data) as IChatCompletionStreamChunk;
|
||||
};
|
||||
|
||||
/** 收集一个 chunk 中所有 choice 的 delta.content */
|
||||
const collectDeltaContent = (chunk: IChatCompletionStreamChunk) => {
|
||||
return (
|
||||
chunk.choices
|
||||
?.map((choice) => choice.delta?.content || "")
|
||||
.filter(Boolean)
|
||||
.join("") || ""
|
||||
);
|
||||
};
|
||||
|
||||
/** 清理模型文本里 URL 后面可能粘上的句末标点 */
|
||||
const cleanupImageUrl = (url: string) => {
|
||||
return url.replace(/[,.!?,。!?]+$/u, "");
|
||||
};
|
||||
|
||||
+9
-15
@@ -3,7 +3,6 @@ import { PrismaClient } from "~~/app/generated/prisma/client";
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma?: PrismaClient;
|
||||
prismaLogged?: boolean;
|
||||
};
|
||||
|
||||
const databaseUrl = process.env.DATABASE_URL;
|
||||
@@ -12,7 +11,10 @@ if (!databaseUrl) {
|
||||
throw new Error("DATABASE_URL is required to initialize PrismaClient");
|
||||
}
|
||||
|
||||
type MariaDbPoolConfig = Exclude<ConstructorParameters<typeof PrismaMariaDb>[0], string>;
|
||||
type MariaDbPoolConfig = Exclude<
|
||||
ConstructorParameters<typeof PrismaMariaDb>[0],
|
||||
string
|
||||
>;
|
||||
|
||||
function getNumberParam(url: URL, name: string, fallback: number) {
|
||||
const value = url.searchParams.get(name);
|
||||
@@ -46,29 +48,21 @@ function createMariaDbConfig(urlString: string): MariaDbPoolConfig {
|
||||
database,
|
||||
connectionLimit: getNumberParam(url, "connection_limit", 5),
|
||||
acquireTimeout: getNumberParam(url, "pool_timeout", 30) * 1000,
|
||||
connectTimeout: getNumberParam(url, "connect_timeout", 10) * 1000,
|
||||
connectTimeout: getNumberParam(url, "connect_timeout", 10) * 1000
|
||||
};
|
||||
}
|
||||
|
||||
const mariaDbConfig = createMariaDbConfig(databaseUrl);
|
||||
const adapter = new PrismaMariaDb(mariaDbConfig, { database: mariaDbConfig.database });
|
||||
|
||||
if (!globalForPrisma.prismaLogged) {
|
||||
console.info("[prisma] initializing MariaDB pool", {
|
||||
host: mariaDbConfig.host,
|
||||
port: mariaDbConfig.port,
|
||||
database: mariaDbConfig.database,
|
||||
connectionLimit: mariaDbConfig.connectionLimit,
|
||||
});
|
||||
globalForPrisma.prismaLogged = true;
|
||||
}
|
||||
const adapter = new PrismaMariaDb(mariaDbConfig, {
|
||||
database: mariaDbConfig.database
|
||||
});
|
||||
|
||||
/** Reuse PrismaClient during dev hot reloads so Nuxt does not create duplicate pools. */
|
||||
export const prisma =
|
||||
globalForPrisma.prisma ??
|
||||
new PrismaClient({
|
||||
adapter,
|
||||
log: ["warn", "error"],
|
||||
log: ["warn", "error"]
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
|
||||
Reference in New Issue
Block a user