mirror of
https://github.com/basketikun/infinite-canvas.git
synced 2026-08-05 08:54:23 +08:00
style(code): 格式化代码缩进和布局样式
- 统一调整 admin.ts 文件中的接口定义缩进格式 - 优化 animated-theme-toggler.tsx 组件的代码结构和缩进 - 规范 app-config-modal.tsx 中 JSX 元素的嵌套格式 - 整理 app-providers.tsx 中的组件层级缩进 - 标准化 app-theme.ts 中的对象属性缩进格式
This commit is contained in:
+163
-158
@@ -7,207 +7,212 @@ import { imageToDataUrl } from "@/services/image-storage";
|
||||
import type { ReferenceImage } from "@/types/image";
|
||||
|
||||
export type ChatCompletionMessage = {
|
||||
role: "system" | "user" | "assistant";
|
||||
content: string | Array<{ type: "text"; text: string } | { type: "image_url"; image_url: { url: string } }>;
|
||||
role: "system" | "user" | "assistant";
|
||||
content: string | Array<{ type: "text"; text: string } | { type: "image_url"; image_url: { url: string } }>;
|
||||
};
|
||||
|
||||
type ImageApiResponse = {
|
||||
data?: Array<Record<string, unknown>>;
|
||||
error?: { message?: string };
|
||||
code?: number;
|
||||
msg?: string;
|
||||
data?: Array<Record<string, unknown>>;
|
||||
error?: { message?: string };
|
||||
code?: number;
|
||||
msg?: string;
|
||||
};
|
||||
|
||||
function resolveImageDataUrl(item: Record<string, unknown>) {
|
||||
if (typeof item.b64_json === "string" && item.b64_json) {
|
||||
return `data:image/png;base64,${item.b64_json}`;
|
||||
}
|
||||
if (typeof item.url === "string" && item.url) {
|
||||
return item.url;
|
||||
}
|
||||
return null;
|
||||
if (typeof item.b64_json === "string" && item.b64_json) {
|
||||
return `data:image/png;base64,${item.b64_json}`;
|
||||
}
|
||||
if (typeof item.url === "string" && item.url) {
|
||||
return item.url;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseImagePayload(payload: ImageApiResponse) {
|
||||
if (typeof payload.code === "number" && payload.code !== 0) {
|
||||
throw new Error(payload.msg || "请求失败");
|
||||
}
|
||||
const images =
|
||||
payload.data
|
||||
?.map(resolveImageDataUrl)
|
||||
.filter((value): value is string => Boolean(value))
|
||||
.map((dataUrl) => ({ id: nanoid(), dataUrl })) || [];
|
||||
if (typeof payload.code === "number" && payload.code !== 0) {
|
||||
throw new Error(payload.msg || "请求失败");
|
||||
}
|
||||
const images =
|
||||
payload.data
|
||||
?.map(resolveImageDataUrl)
|
||||
.filter((value): value is string => Boolean(value))
|
||||
.map((dataUrl) => ({ id: nanoid(), dataUrl })) || [];
|
||||
|
||||
if (images.length === 0) {
|
||||
throw new Error("接口没有返回图片");
|
||||
}
|
||||
if (images.length === 0) {
|
||||
throw new Error("接口没有返回图片");
|
||||
}
|
||||
|
||||
return images;
|
||||
return images;
|
||||
}
|
||||
|
||||
function readAxiosError(error: unknown, fallback: string) {
|
||||
if (axios.isAxiosError<{ error?: { message?: string }; msg?: string; code?: number }>(error)) {
|
||||
const responseData = error.response?.data;
|
||||
return responseData?.msg || responseData?.error?.message || (error.response?.status ? `${fallback}:${error.response.status}` : fallback);
|
||||
}
|
||||
return error instanceof Error ? error.message : fallback;
|
||||
if (axios.isAxiosError<{ error?: { message?: string }; msg?: string; code?: number }>(error)) {
|
||||
const responseData = error.response?.data;
|
||||
return responseData?.msg || responseData?.error?.message || (error.response?.status ? `${fallback}:${error.response.status}` : fallback);
|
||||
}
|
||||
return error instanceof Error ? error.message : fallback;
|
||||
}
|
||||
|
||||
function parseStreamChunk(chunk: string, onDelta: (value: string) => void) {
|
||||
let deltaText = "";
|
||||
for (const eventBlock of chunk.split("\n\n")) {
|
||||
const data = eventBlock.split("\n").find((line) => line.startsWith("data: "))?.slice(6);
|
||||
if (!data || data === "[DONE]") continue;
|
||||
const delta = (JSON.parse(data) as { choices?: Array<{ delta?: { content?: string } }> }).choices?.[0]?.delta?.content || "";
|
||||
deltaText += delta;
|
||||
}
|
||||
if (deltaText) onDelta(deltaText);
|
||||
let deltaText = "";
|
||||
for (const eventBlock of chunk.split("\n\n")) {
|
||||
const data = eventBlock
|
||||
.split("\n")
|
||||
.find((line) => line.startsWith("data: "))
|
||||
?.slice(6);
|
||||
if (!data || data === "[DONE]") continue;
|
||||
const delta = (JSON.parse(data) as { choices?: Array<{ delta?: { content?: string } }> }).choices?.[0]?.delta?.content || "";
|
||||
deltaText += delta;
|
||||
}
|
||||
if (deltaText) onDelta(deltaText);
|
||||
}
|
||||
|
||||
function withSystemPrompt(config: AiConfig, prompt: string) {
|
||||
const systemPrompt = config.systemPrompt.trim();
|
||||
return systemPrompt ? `${systemPrompt}\n\n${prompt}` : prompt;
|
||||
const systemPrompt = config.systemPrompt.trim();
|
||||
return systemPrompt ? `${systemPrompt}\n\n${prompt}` : prompt;
|
||||
}
|
||||
|
||||
function aiApiUrl(config: AiConfig, path: string) {
|
||||
return config.channelMode === "remote" ? `/api/v1${path}` : buildApiUrl(config.baseUrl, path);
|
||||
return config.channelMode === "remote" ? `/api/v1${path}` : buildApiUrl(config.baseUrl, path);
|
||||
}
|
||||
|
||||
function aiHeaders(config: AiConfig, contentType?: string) {
|
||||
return config.channelMode === "remote"
|
||||
? contentType ? { "Content-Type": contentType } : undefined
|
||||
: {
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
...(contentType ? { "Content-Type": contentType } : {}),
|
||||
};
|
||||
return config.channelMode === "remote"
|
||||
? contentType
|
||||
? { "Content-Type": contentType }
|
||||
: undefined
|
||||
: {
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
...(contentType ? { "Content-Type": contentType } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function withSystemMessage(config: AiConfig, messages: ChatCompletionMessage[]) {
|
||||
const systemPrompt = config.systemPrompt.trim();
|
||||
return systemPrompt ? [{ role: "system" as const, content: systemPrompt }, ...messages] : messages;
|
||||
const systemPrompt = config.systemPrompt.trim();
|
||||
return systemPrompt ? [{ role: "system" as const, content: systemPrompt }, ...messages] : messages;
|
||||
}
|
||||
|
||||
export async function requestGeneration(config: AiConfig, prompt: string) {
|
||||
const n = Math.max(1, Math.min(15, Math.floor(Math.abs(Number(config.count)) || 1)));
|
||||
try {
|
||||
const response = await axios.post<ImageApiResponse>(
|
||||
aiApiUrl(config, "/images/generations"),
|
||||
{
|
||||
model: config.model,
|
||||
prompt: withSystemPrompt(config, prompt),
|
||||
n,
|
||||
quality: config.quality || undefined,
|
||||
size: config.size || undefined,
|
||||
response_format: "b64_json",
|
||||
},
|
||||
{
|
||||
headers: aiHeaders(config, "application/json"),
|
||||
},
|
||||
);
|
||||
return parseImagePayload(response.data);
|
||||
} catch (error) {
|
||||
throw new Error(readAxiosError(error, "请求失败"));
|
||||
}
|
||||
const n = Math.max(1, Math.min(15, Math.floor(Math.abs(Number(config.count)) || 1)));
|
||||
try {
|
||||
const response = await axios.post<ImageApiResponse>(
|
||||
aiApiUrl(config, "/images/generations"),
|
||||
{
|
||||
model: config.model,
|
||||
prompt: withSystemPrompt(config, prompt),
|
||||
n,
|
||||
quality: config.quality || undefined,
|
||||
size: config.size || undefined,
|
||||
response_format: "b64_json",
|
||||
},
|
||||
{
|
||||
headers: aiHeaders(config, "application/json"),
|
||||
},
|
||||
);
|
||||
return parseImagePayload(response.data);
|
||||
} catch (error) {
|
||||
throw new Error(readAxiosError(error, "请求失败"));
|
||||
}
|
||||
}
|
||||
|
||||
export async function requestEdit(config: AiConfig, prompt: string, references: ReferenceImage[]) {
|
||||
const n = Math.max(1, Math.min(15, Math.floor(Math.abs(Number(config.count)) || 1)));
|
||||
const formData = new FormData();
|
||||
formData.set("model", config.model);
|
||||
formData.set("prompt", withSystemPrompt(config, prompt));
|
||||
formData.set("n", String(n));
|
||||
formData.set("response_format", "b64_json");
|
||||
if (config.quality) {
|
||||
formData.set("quality", config.quality);
|
||||
}
|
||||
if (config.size) {
|
||||
formData.set("size", config.size);
|
||||
}
|
||||
const files = await Promise.all(references.map(async (image) => dataUrlToFile({ ...image, dataUrl: await imageToDataUrl(image) })));
|
||||
files.forEach((file) => formData.append("image", file));
|
||||
const n = Math.max(1, Math.min(15, Math.floor(Math.abs(Number(config.count)) || 1)));
|
||||
const formData = new FormData();
|
||||
formData.set("model", config.model);
|
||||
formData.set("prompt", withSystemPrompt(config, prompt));
|
||||
formData.set("n", String(n));
|
||||
formData.set("response_format", "b64_json");
|
||||
if (config.quality) {
|
||||
formData.set("quality", config.quality);
|
||||
}
|
||||
if (config.size) {
|
||||
formData.set("size", config.size);
|
||||
}
|
||||
const files = await Promise.all(references.map(async (image) => dataUrlToFile({ ...image, dataUrl: await imageToDataUrl(image) })));
|
||||
files.forEach((file) => formData.append("image", file));
|
||||
|
||||
try {
|
||||
const response = await axios.post<ImageApiResponse>(aiApiUrl(config, "/images/edits"), formData, { headers: aiHeaders(config) });
|
||||
return parseImagePayload(response.data);
|
||||
} catch (error) {
|
||||
throw new Error(readAxiosError(error, "请求失败"));
|
||||
}
|
||||
try {
|
||||
const response = await axios.post<ImageApiResponse>(aiApiUrl(config, "/images/edits"), formData, { headers: aiHeaders(config) });
|
||||
return parseImagePayload(response.data);
|
||||
} catch (error) {
|
||||
throw new Error(readAxiosError(error, "请求失败"));
|
||||
}
|
||||
}
|
||||
|
||||
export async function requestImageQuestion(config: AiConfig, messages: ChatCompletionMessage[], onDelta: (text: string) => void) {
|
||||
let buffer = "";
|
||||
let answer = "";
|
||||
let processedLength = 0;
|
||||
let buffer = "";
|
||||
let answer = "";
|
||||
let processedLength = 0;
|
||||
|
||||
try {
|
||||
const response = await axios.post(
|
||||
aiApiUrl(config, "/chat/completions"),
|
||||
{
|
||||
model: config.model,
|
||||
messages: withSystemMessage(config, messages),
|
||||
stream: true,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
...aiHeaders(config, "application/json"),
|
||||
} as Record<string, string>,
|
||||
responseType: "text",
|
||||
onDownloadProgress: (event) => {
|
||||
const responseText = String(event.event?.target?.responseText || "");
|
||||
const nextText = responseText.slice(processedLength);
|
||||
processedLength = responseText.length;
|
||||
buffer += nextText;
|
||||
const chunks = buffer.split("\n\n");
|
||||
buffer = chunks.pop() || "";
|
||||
for (const chunk of chunks) {
|
||||
parseStreamChunk(chunk, (delta) => {
|
||||
answer += delta;
|
||||
onDelta(answer);
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
if (typeof response.data === "object" && response.data && "code" in response.data && (response.data as { code?: number; msg?: string }).code !== 0) {
|
||||
throw new Error((response.data as { msg?: string }).msg || "请求失败");
|
||||
}
|
||||
if (typeof response.data === "string") {
|
||||
let apiError = "";
|
||||
try {
|
||||
const payload = JSON.parse(response.data) as { code?: number; msg?: string };
|
||||
if (typeof payload.code === "number" && payload.code !== 0) {
|
||||
apiError = payload.msg || "请求失败";
|
||||
try {
|
||||
const response = await axios.post(
|
||||
aiApiUrl(config, "/chat/completions"),
|
||||
{
|
||||
model: config.model,
|
||||
messages: withSystemMessage(config, messages),
|
||||
stream: true,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
...aiHeaders(config, "application/json"),
|
||||
} as Record<string, string>,
|
||||
responseType: "text",
|
||||
onDownloadProgress: (event) => {
|
||||
const responseText = String(event.event?.target?.responseText || "");
|
||||
const nextText = responseText.slice(processedLength);
|
||||
processedLength = responseText.length;
|
||||
buffer += nextText;
|
||||
const chunks = buffer.split("\n\n");
|
||||
buffer = chunks.pop() || "";
|
||||
for (const chunk of chunks) {
|
||||
parseStreamChunk(chunk, (delta) => {
|
||||
answer += delta;
|
||||
onDelta(answer);
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
if (typeof response.data === "object" && response.data && "code" in response.data && (response.data as { code?: number; msg?: string }).code !== 0) {
|
||||
throw new Error((response.data as { msg?: string }).msg || "请求失败");
|
||||
}
|
||||
} catch {
|
||||
// ignore plain text stream content
|
||||
}
|
||||
if (apiError) throw new Error(apiError);
|
||||
if (typeof response.data === "string") {
|
||||
let apiError = "";
|
||||
try {
|
||||
const payload = JSON.parse(response.data) as { code?: number; msg?: string };
|
||||
if (typeof payload.code === "number" && payload.code !== 0) {
|
||||
apiError = payload.msg || "请求失败";
|
||||
}
|
||||
} catch {
|
||||
// ignore plain text stream content
|
||||
}
|
||||
if (apiError) throw new Error(apiError);
|
||||
}
|
||||
if (buffer) {
|
||||
parseStreamChunk(buffer, (delta) => {
|
||||
answer += delta;
|
||||
onDelta(answer);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(readAxiosError(error, "请求失败"));
|
||||
}
|
||||
if (buffer) {
|
||||
parseStreamChunk(buffer, (delta) => {
|
||||
answer += delta;
|
||||
onDelta(answer);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(readAxiosError(error, "请求失败"));
|
||||
}
|
||||
return answer || "没有返回内容";
|
||||
return answer || "没有返回内容";
|
||||
}
|
||||
|
||||
export async function fetchImageModels(config: AiConfig) {
|
||||
if (config.channelMode === "remote") return config.models;
|
||||
try {
|
||||
const response = await axios.get<{ data?: Array<{ id?: string }>; error?: { message?: string } }>(buildApiUrl(config.baseUrl, "/models"), {
|
||||
headers: {
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
},
|
||||
});
|
||||
return (response.data.data || [])
|
||||
.map((model) => model.id)
|
||||
.filter((id): id is string => Boolean(id))
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
} catch (error) {
|
||||
throw new Error(readAxiosError(error, "读取模型失败"));
|
||||
}
|
||||
if (config.channelMode === "remote") return config.models;
|
||||
try {
|
||||
const response = await axios.get<{ data?: Array<{ id?: string }>; error?: { message?: string } }>(buildApiUrl(config.baseUrl, "/models"), {
|
||||
headers: {
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
},
|
||||
});
|
||||
return (response.data.data || [])
|
||||
.map((model) => model.id)
|
||||
.filter((id): id is string => Boolean(id))
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
} catch (error) {
|
||||
throw new Error(readAxiosError(error, "读取模型失败"));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user