feat: add Homarr assistant
This commit is contained in:
1 parent
3b6de1f91f
commit
fd69cd28f0
27 files changed
+5210
-772
No files matched your search
@@ -3,6 +3,7 @@ import { lazy } from "@trpc/server";
|
||||
import { createTRPCRouter } from "./trpc";
|
||||
|
||||
export const appRouter = createTRPCRouter({
|
||||
assistant: lazy(() => import("./router/assistant").then((mod) => mod.assistantRouter)),
|
||||
user: lazy(() => import("./router/user").then((mod) => mod.userRouter)),
|
||||
group: lazy(() => import("./router/group").then((mod) => mod.groupRouter)),
|
||||
invite: lazy(() => import("./router/invite").then((mod) => mod.inviteRouter)),
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { parse, stringify } from "superjson";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
import { decryptSecret, encryptSecret } from "@homarr/common/server";
|
||||
import { and, desc, eq, inArray } from "@homarr/db";
|
||||
import type { Database } from "@homarr/db";
|
||||
import { assistantConfigurations, assistantMessages, assistantThreads } from "@homarr/db/schema";
|
||||
|
||||
import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure } from "../trpc";
|
||||
|
||||
const adminProcedure = permissionRequiredProcedure.requiresPermission("admin");
|
||||
const configurationId = "default";
|
||||
const providerSchema = z.enum(["openrouter", "openai", "ollama", "lm-studio", "custom"]);
|
||||
|
||||
const modelSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string().nullable(),
|
||||
contextLength: z.number().nullable(),
|
||||
promptPrice: z.string().nullable(),
|
||||
completionPrice: z.string().nullable(),
|
||||
toolSupport: z.enum(["confirmed", "unknown"]),
|
||||
});
|
||||
|
||||
type CompatibleModel = {
|
||||
id?: unknown;
|
||||
name?: unknown;
|
||||
model?: unknown;
|
||||
description?: unknown;
|
||||
context_length?: unknown;
|
||||
supported_parameters?: unknown;
|
||||
architecture?: { output_modalities?: unknown };
|
||||
pricing?: { prompt?: unknown; completion?: unknown };
|
||||
};
|
||||
|
||||
type AssistantConfiguration = typeof assistantConfigurations.$inferSelect;
|
||||
|
||||
const customHeadersSchema = z
|
||||
.record(
|
||||
z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(128)
|
||||
.regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/),
|
||||
z
|
||||
.string()
|
||||
.max(2048)
|
||||
.refine((value) => !value.includes("\r") && !value.includes("\n")),
|
||||
)
|
||||
.refine((headers) => Object.keys(headers).length <= 20)
|
||||
.refine(
|
||||
(headers) =>
|
||||
!Object.keys(headers).some((name) =>
|
||||
["connection", "content-length", "host", "transfer-encoding"].includes(name.toLowerCase()),
|
||||
),
|
||||
"Hop-by-hop and transport headers cannot be configured.",
|
||||
);
|
||||
|
||||
const normalizeBaseUrl = (value: string) => {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Enter a valid provider URL." });
|
||||
}
|
||||
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "The provider URL must use HTTP or HTTPS without credentials, query parameters, or fragments.",
|
||||
});
|
||||
}
|
||||
return url.toString().replace(/\/$/, "");
|
||||
};
|
||||
|
||||
const normalizeDiscoveryPath = (value: string | null) => {
|
||||
if (value === null || value.trim() === "") return null;
|
||||
const path = value.trim();
|
||||
if (!path.startsWith("/") || path.startsWith("//") || path.includes("?") || path.includes("#")) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "The model discovery path must be an absolute path such as /models.",
|
||||
});
|
||||
}
|
||||
return path;
|
||||
};
|
||||
|
||||
const getConfigurationAsync = async (db: Database) => {
|
||||
return await db.query.assistantConfigurations.findFirst({
|
||||
where: eq(assistantConfigurations.id, configurationId),
|
||||
});
|
||||
};
|
||||
|
||||
const decryptCustomHeaders = (encryptedHeaders: `${string}.${string}` | null) => {
|
||||
if (!encryptedHeaders) return {};
|
||||
try {
|
||||
return customHeadersSchema.parse(JSON.parse(decryptSecret(encryptedHeaders)));
|
||||
} catch {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "The stored provider headers could not be decrypted.",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const getProviderHeaders = (configuration: AssistantConfiguration) => {
|
||||
const headers: Record<string, string> = {};
|
||||
if (configuration.encryptedApiKey) {
|
||||
headers.Authorization = `Bearer ${decryptSecret(configuration.encryptedApiKey)}`;
|
||||
}
|
||||
if (configuration.provider === "openrouter") {
|
||||
headers["HTTP-Referer"] ??= "https://homarr.dev";
|
||||
headers["X-Title"] ??= "Homarr Assistant";
|
||||
}
|
||||
return { ...headers, ...decryptCustomHeaders(configuration.encryptedHeaders) };
|
||||
};
|
||||
|
||||
const fetchModelsAsync = async (configuration: AssistantConfiguration) => {
|
||||
if (!configuration.modelDiscoveryPath) {
|
||||
throw new TRPCError({
|
||||
code: "PRECONDITION_FAILED",
|
||||
message: "Model discovery is disabled for this provider. Enter a model ID manually.",
|
||||
});
|
||||
}
|
||||
|
||||
const endpoint = `${configuration.baseUrl}${configuration.modelDiscoveryPath}`;
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(endpoint, {
|
||||
headers: getProviderHeaders(configuration),
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
} catch {
|
||||
throw new TRPCError({
|
||||
code: "BAD_GATEWAY",
|
||||
message: "The model endpoint could not be reached from the Homarr server.",
|
||||
});
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED", message: "The provider rejected the configured credentials." });
|
||||
}
|
||||
throw new TRPCError({
|
||||
code: "BAD_GATEWAY",
|
||||
message: `Model discovery failed with status ${response.status}.`,
|
||||
});
|
||||
}
|
||||
|
||||
let body: { data?: CompatibleModel[]; models?: CompatibleModel[] };
|
||||
try {
|
||||
body = (await response.json()) as typeof body;
|
||||
} catch {
|
||||
throw new TRPCError({ code: "BAD_GATEWAY", message: "The model endpoint returned invalid JSON." });
|
||||
}
|
||||
const models = body.data ?? body.models ?? [];
|
||||
return models
|
||||
.filter((model) => {
|
||||
if (configuration.provider !== "openrouter") return true;
|
||||
const parameters = Array.isArray(model.supported_parameters) ? model.supported_parameters : [];
|
||||
const outputModalities = Array.isArray(model.architecture?.output_modalities)
|
||||
? model.architecture.output_modalities
|
||||
: [];
|
||||
return parameters.includes("tools") && (outputModalities.length === 0 || outputModalities.includes("text"));
|
||||
})
|
||||
.flatMap((model) => {
|
||||
const id = typeof model.id === "string" ? model.id : typeof model.model === "string" ? model.model : null;
|
||||
if (!id) return [];
|
||||
const name = typeof model.name === "string" ? model.name : id;
|
||||
return [
|
||||
{
|
||||
id,
|
||||
name,
|
||||
description: typeof model.description === "string" ? model.description : null,
|
||||
contextLength: typeof model.context_length === "number" ? model.context_length : null,
|
||||
promptPrice: typeof model.pricing?.prompt === "string" ? model.pricing.prompt : null,
|
||||
completionPrice: typeof model.pricing?.completion === "string" ? model.pricing.completion : null,
|
||||
toolSupport: configuration.provider === "openrouter" ? ("confirmed" as const) : ("unknown" as const),
|
||||
},
|
||||
];
|
||||
})
|
||||
.toSorted((left, right) => left.name.localeCompare(right.name));
|
||||
};
|
||||
|
||||
const ownedThreadAsync = async (db: Database, threadId: string, userId: string) => {
|
||||
const thread = await db.query.assistantThreads.findFirst({
|
||||
where: and(eq(assistantThreads.id, threadId), eq(assistantThreads.userId, userId)),
|
||||
});
|
||||
if (!thread) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Conversation not found." });
|
||||
}
|
||||
return thread;
|
||||
};
|
||||
|
||||
export const assistantRouter = createTRPCRouter({
|
||||
getAvailability: protectedProcedure.query(async ({ ctx }) => {
|
||||
const configuration = await getConfigurationAsync(ctx.db);
|
||||
const requiresApiKey = configuration?.provider === "openrouter" || configuration?.provider === "openai";
|
||||
return {
|
||||
enabled: Boolean(
|
||||
configuration?.enabled && configuration.modelId && (!requiresApiKey || configuration.encryptedApiKey),
|
||||
),
|
||||
};
|
||||
}),
|
||||
|
||||
getAdminConfiguration: adminProcedure.query(async ({ ctx }) => {
|
||||
const configuration = await getConfigurationAsync(ctx.db);
|
||||
return {
|
||||
connectionConfigured: Boolean(configuration),
|
||||
enabled: configuration?.enabled ?? false,
|
||||
provider: configuration?.provider ?? "openrouter",
|
||||
baseUrl: configuration?.baseUrl ?? "https://openrouter.ai/api/v1",
|
||||
modelDiscoveryPath: configuration?.modelDiscoveryPath ?? "/models",
|
||||
apiKeyConfigured: Boolean(configuration?.encryptedApiKey),
|
||||
customHeadersConfigured: Boolean(configuration?.encryptedHeaders),
|
||||
modelId: configuration?.modelId ?? null,
|
||||
updatedAt: configuration?.updatedAt ?? null,
|
||||
};
|
||||
}),
|
||||
|
||||
updateConnection: adminProcedure
|
||||
.input(
|
||||
z.object({
|
||||
provider: providerSchema,
|
||||
baseUrl: z.string().trim().min(1).max(2048),
|
||||
modelDiscoveryPath: z.string().trim().max(512).nullable(),
|
||||
apiKey: z.string().trim().min(1).max(2048).optional(),
|
||||
clearApiKey: z.boolean().default(false),
|
||||
customHeaders: customHeadersSchema.optional(),
|
||||
clearCustomHeaders: z.boolean().default(false),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const baseUrl = normalizeBaseUrl(input.baseUrl);
|
||||
const modelDiscoveryPath = normalizeDiscoveryPath(input.modelDiscoveryPath);
|
||||
const existing = await getConfigurationAsync(ctx.db);
|
||||
const destinationChanged =
|
||||
existing !== undefined && (existing.provider !== input.provider || existing.baseUrl !== baseUrl);
|
||||
const encryptedApiKey = input.apiKey
|
||||
? encryptSecret(input.apiKey)
|
||||
: input.clearApiKey || destinationChanged
|
||||
? null
|
||||
: (existing?.encryptedApiKey ?? null);
|
||||
const encryptedHeaders = input.customHeaders
|
||||
? encryptSecret(JSON.stringify(input.customHeaders))
|
||||
: input.clearCustomHeaders || destinationChanged
|
||||
? null
|
||||
: (existing?.encryptedHeaders ?? null);
|
||||
|
||||
if (existing) {
|
||||
await ctx.db
|
||||
.update(assistantConfigurations)
|
||||
.set({
|
||||
provider: input.provider,
|
||||
baseUrl,
|
||||
modelDiscoveryPath,
|
||||
encryptedApiKey,
|
||||
encryptedHeaders,
|
||||
modelId: destinationChanged ? null : existing.modelId,
|
||||
enabled: destinationChanged ? false : existing.enabled,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(assistantConfigurations.id, configurationId));
|
||||
} else {
|
||||
await ctx.db.insert(assistantConfigurations).values({
|
||||
id: configurationId,
|
||||
provider: input.provider,
|
||||
baseUrl,
|
||||
modelDiscoveryPath,
|
||||
encryptedApiKey,
|
||||
encryptedHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
apiKeyConfigured: Boolean(encryptedApiKey),
|
||||
customHeadersConfigured: Boolean(encryptedHeaders),
|
||||
credentialsClearedForDestinationChange: destinationChanged && !input.apiKey && !input.customHeaders,
|
||||
};
|
||||
}),
|
||||
|
||||
clearCredentials: adminProcedure.mutation(async ({ ctx }) => {
|
||||
const existing = await getConfigurationAsync(ctx.db);
|
||||
if (!existing) return;
|
||||
await ctx.db
|
||||
.update(assistantConfigurations)
|
||||
.set({
|
||||
encryptedApiKey: null,
|
||||
encryptedHeaders: null,
|
||||
modelId: null,
|
||||
enabled: false,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(assistantConfigurations.id, configurationId));
|
||||
}),
|
||||
|
||||
discoverModels: adminProcedure.output(z.array(modelSchema)).query(async ({ ctx }) => {
|
||||
const configuration = await getConfigurationAsync(ctx.db);
|
||||
if (!configuration) {
|
||||
throw new TRPCError({ code: "PRECONDITION_FAILED", message: "Save a provider connection first." });
|
||||
}
|
||||
return await fetchModelsAsync(configuration);
|
||||
}),
|
||||
|
||||
updateConfiguration: adminProcedure
|
||||
.input(z.object({ enabled: z.boolean(), modelId: z.string().trim().min(1).max(256) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const configuration = await getConfigurationAsync(ctx.db);
|
||||
if (!configuration) {
|
||||
throw new TRPCError({ code: "PRECONDITION_FAILED", message: "Save a provider connection first." });
|
||||
}
|
||||
const requiresApiKey = configuration.provider === "openrouter" || configuration.provider === "openai";
|
||||
if (input.enabled && requiresApiKey && !configuration.encryptedApiKey) {
|
||||
throw new TRPCError({ code: "PRECONDITION_FAILED", message: "This provider requires an API key." });
|
||||
}
|
||||
await ctx.db
|
||||
.update(assistantConfigurations)
|
||||
.set({ enabled: input.enabled, modelId: input.modelId, updatedAt: new Date() })
|
||||
.where(eq(assistantConfigurations.id, configurationId));
|
||||
}),
|
||||
|
||||
listThreads: protectedProcedure.query(async ({ ctx }) => {
|
||||
return await ctx.db.query.assistantThreads.findMany({
|
||||
where: eq(assistantThreads.userId, ctx.session.user.id),
|
||||
orderBy: desc(assistantThreads.updatedAt),
|
||||
limit: 100,
|
||||
});
|
||||
}),
|
||||
|
||||
createThread: protectedProcedure
|
||||
.input(z.object({ localId: z.string().max(128).optional() }).optional())
|
||||
.mutation(async ({ ctx }) => {
|
||||
const configuration = await getConfigurationAsync(ctx.db);
|
||||
const id = createId();
|
||||
const now = new Date();
|
||||
await ctx.db.insert(assistantThreads).values({
|
||||
id,
|
||||
userId: ctx.session.user.id,
|
||||
modelId: configuration?.modelId ?? null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
return { id };
|
||||
}),
|
||||
|
||||
getThread: protectedProcedure.input(z.object({ threadId: z.string().max(64) })).query(async ({ ctx, input }) => {
|
||||
const thread = await ownedThreadAsync(ctx.db, input.threadId, ctx.session.user.id);
|
||||
const messages = await ctx.db.query.assistantMessages.findMany({
|
||||
where: eq(assistantMessages.threadId, thread.id),
|
||||
orderBy: assistantMessages.createdAt,
|
||||
});
|
||||
return {
|
||||
thread,
|
||||
messages: messages.map((message) => ({
|
||||
id: message.id,
|
||||
parentId: message.parentId,
|
||||
format: message.format,
|
||||
content: parse(message.content),
|
||||
})),
|
||||
};
|
||||
}),
|
||||
|
||||
renameThread: protectedProcedure
|
||||
.input(z.object({ threadId: z.string().max(64), title: z.string().trim().min(1).max(120) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await ownedThreadAsync(ctx.db, input.threadId, ctx.session.user.id);
|
||||
await ctx.db
|
||||
.update(assistantThreads)
|
||||
.set({ title: input.title, updatedAt: new Date() })
|
||||
.where(eq(assistantThreads.id, input.threadId));
|
||||
}),
|
||||
|
||||
setThreadStatus: protectedProcedure
|
||||
.input(z.object({ threadId: z.string().max(64), status: z.enum(["regular", "archived"]) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await ownedThreadAsync(ctx.db, input.threadId, ctx.session.user.id);
|
||||
await ctx.db
|
||||
.update(assistantThreads)
|
||||
.set({ status: input.status, updatedAt: new Date() })
|
||||
.where(eq(assistantThreads.id, input.threadId));
|
||||
}),
|
||||
|
||||
deleteThread: protectedProcedure
|
||||
.input(z.object({ threadId: z.string().max(64) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await ownedThreadAsync(ctx.db, input.threadId, ctx.session.user.id);
|
||||
await ctx.db.delete(assistantThreads).where(eq(assistantThreads.id, input.threadId));
|
||||
}),
|
||||
|
||||
appendMessage: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
threadId: z.string().max(64),
|
||||
id: z.string().min(1).max(128),
|
||||
parentId: z.string().max(128).nullable(),
|
||||
format: z.literal("ai-sdk/v6"),
|
||||
content: z.unknown(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const thread = await ownedThreadAsync(ctx.db, input.threadId, ctx.session.user.id);
|
||||
const existing = await ctx.db.query.assistantMessages.findFirst({
|
||||
where: and(eq(assistantMessages.id, input.id), eq(assistantMessages.threadId, thread.id)),
|
||||
});
|
||||
if (existing) {
|
||||
await ctx.db
|
||||
.update(assistantMessages)
|
||||
.set({ parentId: input.parentId, format: input.format, content: stringify(input.content) })
|
||||
.where(eq(assistantMessages.id, input.id));
|
||||
} else {
|
||||
await ctx.db.insert(assistantMessages).values({
|
||||
id: input.id,
|
||||
threadId: thread.id,
|
||||
parentId: input.parentId,
|
||||
format: input.format,
|
||||
content: stringify(input.content),
|
||||
});
|
||||
}
|
||||
|
||||
const title =
|
||||
thread.title ??
|
||||
(typeof input.content === "object" &&
|
||||
input.content !== null &&
|
||||
"role" in input.content &&
|
||||
input.content.role === "user" &&
|
||||
"parts" in input.content &&
|
||||
Array.isArray(input.content.parts)
|
||||
? input.content.parts
|
||||
.filter(
|
||||
(part): part is { type: "text"; text: string } =>
|
||||
typeof part === "object" &&
|
||||
part !== null &&
|
||||
"type" in part &&
|
||||
part.type === "text" &&
|
||||
"text" in part &&
|
||||
typeof part.text === "string",
|
||||
)
|
||||
.map((part) => part.text)
|
||||
.join(" ")
|
||||
.trim()
|
||||
.slice(0, 80) || null
|
||||
: null);
|
||||
|
||||
await ctx.db
|
||||
.update(assistantThreads)
|
||||
.set({ title, updatedAt: new Date() })
|
||||
.where(eq(assistantThreads.id, thread.id));
|
||||
}),
|
||||
|
||||
deleteMessages: protectedProcedure
|
||||
.input(z.object({ threadId: z.string().max(64), ids: z.array(z.string().max(128)).max(100) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await ownedThreadAsync(ctx.db, input.threadId, ctx.session.user.id);
|
||||
if (input.ids.length === 0) return;
|
||||
await ctx.db
|
||||
.delete(assistantMessages)
|
||||
.where(and(eq(assistantMessages.threadId, input.threadId), inArray(assistantMessages.id, input.ids)));
|
||||
await ctx.db
|
||||
.update(assistantThreads)
|
||||
.set({ updatedAt: new Date() })
|
||||
.where(eq(assistantThreads.id, input.threadId));
|
||||
}),
|
||||
});
|
||||
|
||||
export { fetchModelsAsync, getConfigurationAsync, ownedThreadAsync };
|
||||
@@ -0,0 +1,37 @@
|
||||
CREATE TABLE `assistant_configuration` (
|
||||
`id` varchar(64) DEFAULT 'default' NOT NULL,
|
||||
`enabled` boolean DEFAULT false NOT NULL,
|
||||
`provider` varchar(32) DEFAULT 'openrouter' NOT NULL,
|
||||
`base_url` varchar(2048) DEFAULT 'https://openrouter.ai/api/v1' NOT NULL,
|
||||
`model_discovery_path` varchar(512) DEFAULT '/models',
|
||||
`encrypted_api_key` text,
|
||||
`encrypted_headers` text,
|
||||
`model_id` varchar(256),
|
||||
`updated_at` timestamp DEFAULT (now()) NOT NULL,
|
||||
CONSTRAINT `assistant_configuration_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `assistant_thread` (
|
||||
`id` varchar(64) NOT NULL,
|
||||
`user_id` varchar(64) NOT NULL,
|
||||
`title` varchar(256),
|
||||
`model_id` varchar(256),
|
||||
`status` varchar(16) DEFAULT 'regular' NOT NULL,
|
||||
`created_at` timestamp DEFAULT (now()) NOT NULL,
|
||||
`updated_at` timestamp DEFAULT (now()) NOT NULL,
|
||||
CONSTRAINT `assistant_thread_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `assistant_message` (
|
||||
`id` varchar(64) NOT NULL,
|
||||
`thread_id` varchar(64) NOT NULL,
|
||||
`parent_id` varchar(64),
|
||||
`format` varchar(64) DEFAULT 'ai-sdk/v6' NOT NULL,
|
||||
`content` text DEFAULT ('{"json": {}}') NOT NULL,
|
||||
`created_at` timestamp DEFAULT (now()) NOT NULL,
|
||||
CONSTRAINT `assistant_message_id` PRIMARY KEY(`id`)
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `assistant_thread` ADD CONSTRAINT `assistant_thread_user_id_user_id_fk` FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON DELETE cascade ON UPDATE no action;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `assistant_message` ADD CONSTRAINT `assistant_message_thread_id_assistant_thread_id_fk` FOREIGN KEY (`thread_id`) REFERENCES `assistant_thread`(`id`) ON DELETE cascade ON UPDATE no action;
|
||||
@@ -330,6 +330,13 @@
|
||||
"when": 1786215199760,
|
||||
"tag": "0046_add_layout_role",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 47,
|
||||
"version": "5",
|
||||
"when": 1786217088950,
|
||||
"tag": "0047_add_assistant_tables",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
CREATE TABLE "assistant_configuration" (
|
||||
"id" varchar(64) PRIMARY KEY DEFAULT 'default' NOT NULL,
|
||||
"enabled" boolean DEFAULT false NOT NULL,
|
||||
"provider" varchar(32) DEFAULT 'openrouter' NOT NULL,
|
||||
"base_url" varchar(2048) DEFAULT 'https://openrouter.ai/api/v1' NOT NULL,
|
||||
"model_discovery_path" varchar(512) DEFAULT '/models',
|
||||
"encrypted_api_key" text,
|
||||
"encrypted_headers" text,
|
||||
"model_id" varchar(256),
|
||||
"updated_at" timestamp DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "assistant_message" (
|
||||
"id" varchar(64) PRIMARY KEY NOT NULL,
|
||||
"thread_id" varchar(64) NOT NULL,
|
||||
"parent_id" varchar(64),
|
||||
"format" varchar(64) DEFAULT 'ai-sdk/v6' NOT NULL,
|
||||
"content" text DEFAULT '{"json": {}}' NOT NULL,
|
||||
"created_at" timestamp DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "assistant_thread" (
|
||||
"id" varchar(64) PRIMARY KEY NOT NULL,
|
||||
"user_id" varchar(64) NOT NULL,
|
||||
"title" varchar(256),
|
||||
"model_id" varchar(256),
|
||||
"status" varchar(16) DEFAULT 'regular' NOT NULL,
|
||||
"created_at" timestamp DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "assistant_message" ADD CONSTRAINT "assistant_message_thread_id_assistant_thread_id_fk" FOREIGN KEY ("thread_id") REFERENCES "public"."assistant_thread"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "assistant_thread" ADD CONSTRAINT "assistant_thread_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;
|
||||
@@ -92,6 +92,13 @@
|
||||
"when": 1786215201393,
|
||||
"tag": "0012_add_layout_role",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 13,
|
||||
"version": "7",
|
||||
"when": 1786217088954,
|
||||
"tag": "0013_add_assistant_tables",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
CREATE TABLE `assistant_configuration` (
|
||||
`id` text PRIMARY KEY DEFAULT 'default' NOT NULL,
|
||||
`enabled` integer DEFAULT false NOT NULL,
|
||||
`provider` text DEFAULT 'openrouter' NOT NULL,
|
||||
`base_url` text DEFAULT 'https://openrouter.ai/api/v1' NOT NULL,
|
||||
`model_discovery_path` text DEFAULT '/models',
|
||||
`encrypted_api_key` text,
|
||||
`encrypted_headers` text,
|
||||
`model_id` text,
|
||||
`updated_at` integer DEFAULT (unixepoch()) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `assistant_message` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`thread_id` text NOT NULL,
|
||||
`parent_id` text,
|
||||
`format` text DEFAULT 'ai-sdk/v6' NOT NULL,
|
||||
`content` text DEFAULT '{"json": {}}' NOT NULL,
|
||||
`created_at` integer DEFAULT (unixepoch()) NOT NULL,
|
||||
FOREIGN KEY (`thread_id`) REFERENCES `assistant_thread`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `assistant_thread` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`user_id` text NOT NULL,
|
||||
`title` text,
|
||||
`model_id` text,
|
||||
`status` text DEFAULT 'regular' NOT NULL,
|
||||
`created_at` integer DEFAULT (unixepoch()) NOT NULL,
|
||||
`updated_at` integer DEFAULT (unixepoch()) NOT NULL,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
@@ -316,6 +316,13 @@
|
||||
"when": 1786215203092,
|
||||
"tag": "0044_add_layout_role",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 45,
|
||||
"version": "6",
|
||||
"when": 1786217088950,
|
||||
"tag": "0045_add_assistant_tables",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -19,6 +19,9 @@ export const schema = createSchema({
|
||||
export const {
|
||||
accounts,
|
||||
apiKeys,
|
||||
assistantConfigurations,
|
||||
assistantMessages,
|
||||
assistantThreads,
|
||||
apps,
|
||||
boardGroupPermissions,
|
||||
boardUserPermissions,
|
||||
@@ -58,6 +61,9 @@ export const {
|
||||
|
||||
export type User = InferSelectModel<typeof schema.users>;
|
||||
export type Account = InferSelectModel<typeof schema.accounts>;
|
||||
export type AssistantConfiguration = InferSelectModel<typeof schema.assistantConfigurations>;
|
||||
export type AssistantMessage = InferSelectModel<typeof schema.assistantMessages>;
|
||||
export type AssistantThread = InferSelectModel<typeof schema.assistantThreads>;
|
||||
export type Session = InferSelectModel<typeof schema.sessions>;
|
||||
export type VerificationToken = InferSelectModel<typeof schema.verificationTokens>;
|
||||
export type Integration = InferSelectModel<typeof schema.integrations>;
|
||||
|
||||
@@ -481,6 +481,44 @@ export const serverSettings = mysqlTable("serverSetting", {
|
||||
value: text().default(emptySuperJSON).notNull(),
|
||||
});
|
||||
|
||||
export const assistantConfigurations = mysqlTable("assistant_configuration", {
|
||||
id: varchar({ length: 64 }).notNull().primaryKey().default("default"),
|
||||
enabled: boolean().notNull().default(false),
|
||||
provider: varchar({ length: 32 })
|
||||
.$type<"openrouter" | "openai" | "ollama" | "lm-studio" | "custom">()
|
||||
.notNull()
|
||||
.default("openrouter"),
|
||||
baseUrl: varchar({ length: 2048 }).notNull().default("https://openrouter.ai/api/v1"),
|
||||
modelDiscoveryPath: varchar({ length: 512 }).default("/models"),
|
||||
encryptedApiKey: text().$type<`${string}.${string}`>(),
|
||||
encryptedHeaders: text().$type<`${string}.${string}`>(),
|
||||
modelId: varchar({ length: 256 }),
|
||||
updatedAt: timestamp().notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const assistantThreads = mysqlTable("assistant_thread", {
|
||||
id: varchar({ length: 64 }).notNull().primaryKey(),
|
||||
userId: varchar({ length: 64 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
title: varchar({ length: 256 }),
|
||||
modelId: varchar({ length: 256 }),
|
||||
status: varchar({ length: 16 }).$type<"regular" | "archived">().notNull().default("regular"),
|
||||
createdAt: timestamp().notNull().defaultNow(),
|
||||
updatedAt: timestamp().notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const assistantMessages = mysqlTable("assistant_message", {
|
||||
id: varchar({ length: 64 }).notNull().primaryKey(),
|
||||
threadId: varchar({ length: 64 })
|
||||
.notNull()
|
||||
.references(() => assistantThreads.id, { onDelete: "cascade" }),
|
||||
parentId: varchar({ length: 64 }),
|
||||
format: varchar({ length: 64 }).notNull().default("ai-sdk/v6"),
|
||||
content: text().default(emptySuperJSON).notNull(),
|
||||
createdAt: timestamp().notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const apiKeyRelations = relations(apiKeys, ({ one }) => ({
|
||||
user: one(users, {
|
||||
fields: [apiKeys.userId],
|
||||
|
||||
@@ -480,6 +480,44 @@ export const serverSettings = pgTable("serverSetting", {
|
||||
value: text().default(emptySuperJSON).notNull(),
|
||||
});
|
||||
|
||||
export const assistantConfigurations = pgTable("assistant_configuration", {
|
||||
id: varchar({ length: 64 }).notNull().primaryKey().default("default"),
|
||||
enabled: boolean().notNull().default(false),
|
||||
provider: varchar({ length: 32 })
|
||||
.$type<"openrouter" | "openai" | "ollama" | "lm-studio" | "custom">()
|
||||
.notNull()
|
||||
.default("openrouter"),
|
||||
baseUrl: varchar({ length: 2048 }).notNull().default("https://openrouter.ai/api/v1"),
|
||||
modelDiscoveryPath: varchar({ length: 512 }).default("/models"),
|
||||
encryptedApiKey: text().$type<`${string}.${string}`>(),
|
||||
encryptedHeaders: text().$type<`${string}.${string}`>(),
|
||||
modelId: varchar({ length: 256 }),
|
||||
updatedAt: timestamp().notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const assistantThreads = pgTable("assistant_thread", {
|
||||
id: varchar({ length: 64 }).notNull().primaryKey(),
|
||||
userId: varchar({ length: 64 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
title: varchar({ length: 256 }),
|
||||
modelId: varchar({ length: 256 }),
|
||||
status: varchar({ length: 16 }).$type<"regular" | "archived">().notNull().default("regular"),
|
||||
createdAt: timestamp().notNull().defaultNow(),
|
||||
updatedAt: timestamp().notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const assistantMessages = pgTable("assistant_message", {
|
||||
id: varchar({ length: 64 }).notNull().primaryKey(),
|
||||
threadId: varchar({ length: 64 })
|
||||
.notNull()
|
||||
.references(() => assistantThreads.id, { onDelete: "cascade" }),
|
||||
parentId: varchar({ length: 64 }),
|
||||
format: varchar({ length: 64 }).notNull().default("ai-sdk/v6"),
|
||||
content: text().default(emptySuperJSON).notNull(),
|
||||
createdAt: timestamp().notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const apiKeyRelations = relations(apiKeys, ({ one }) => ({
|
||||
user: one(users, {
|
||||
fields: [apiKeys.userId],
|
||||
|
||||
@@ -465,6 +465,49 @@ export const serverSettings = sqliteTable("serverSetting", {
|
||||
value: text().default(emptySuperJSON).notNull(),
|
||||
});
|
||||
|
||||
export const assistantConfigurations = sqliteTable("assistant_configuration", {
|
||||
id: text().notNull().primaryKey().default("default"),
|
||||
enabled: int({ mode: "boolean" }).notNull().default(false),
|
||||
provider: text().$type<"openrouter" | "openai" | "ollama" | "lm-studio" | "custom">().notNull().default("openrouter"),
|
||||
baseUrl: text().notNull().default("https://openrouter.ai/api/v1"),
|
||||
modelDiscoveryPath: text().default("/models"),
|
||||
encryptedApiKey: text().$type<`${string}.${string}`>(),
|
||||
encryptedHeaders: text().$type<`${string}.${string}`>(),
|
||||
modelId: text(),
|
||||
updatedAt: int({ mode: "timestamp" })
|
||||
.notNull()
|
||||
.default(sql`(unixepoch())`),
|
||||
});
|
||||
|
||||
export const assistantThreads = sqliteTable("assistant_thread", {
|
||||
id: text().notNull().primaryKey(),
|
||||
userId: text()
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
title: text(),
|
||||
modelId: text(),
|
||||
status: text().$type<"regular" | "archived">().notNull().default("regular"),
|
||||
createdAt: int({ mode: "timestamp" })
|
||||
.notNull()
|
||||
.default(sql`(unixepoch())`),
|
||||
updatedAt: int({ mode: "timestamp" })
|
||||
.notNull()
|
||||
.default(sql`(unixepoch())`),
|
||||
});
|
||||
|
||||
export const assistantMessages = sqliteTable("assistant_message", {
|
||||
id: text().notNull().primaryKey(),
|
||||
threadId: text()
|
||||
.notNull()
|
||||
.references(() => assistantThreads.id, { onDelete: "cascade" }),
|
||||
parentId: text(),
|
||||
format: text().notNull().default("ai-sdk/v6"),
|
||||
content: text().default(emptySuperJSON).notNull(),
|
||||
createdAt: int({ mode: "timestamp" })
|
||||
.notNull()
|
||||
.default(sql`(unixepoch())`),
|
||||
});
|
||||
|
||||
export const apiKeyRelations = relations(apiKeys, ({ one }) => ({
|
||||
user: one(users, {
|
||||
fields: [apiKeys.userId],
|
||||
|
||||
@@ -3,4 +3,5 @@ export const hotkeys = {
|
||||
toggleColorScheme: "mod+j",
|
||||
saveNotebook: "mod+s",
|
||||
openSpotlight: "mod+k",
|
||||
openAssistant: "mod+shift+k",
|
||||
};
|
||||
@@ -1950,6 +1950,7 @@
|
||||
"switchToDarkMode": "Switch to dark mode",
|
||||
"switchToLightMode": "Switch to light mode",
|
||||
"management": "Management",
|
||||
"assistant": "Homarr Assistant",
|
||||
"docker": "Docker",
|
||||
"preferences": "Your preferences",
|
||||
"logout": "Logout",
|
||||
@@ -1959,6 +1960,38 @@
|
||||
"updateAvailable": "{countUpdates} updates available: {tag}"
|
||||
}
|
||||
},
|
||||
"assistant": {
|
||||
"title": "Homarr Assistant",
|
||||
"subtitle": "Connected to this Homarr instance",
|
||||
"open": "Open Homarr Assistant",
|
||||
"close": "Close assistant",
|
||||
"spotlight": "Ask Homarr Assistant",
|
||||
"newConversation": "New conversation",
|
||||
"archivedConversation": "Archived conversation",
|
||||
"conversations": "Conversations",
|
||||
"archived": "Archived",
|
||||
"archive": "Archive",
|
||||
"restore": "Restore",
|
||||
"delete": "Delete",
|
||||
"closeHistory": "Close conversation history",
|
||||
"openHistory": "Open conversation history",
|
||||
"emptyTitle": "What can I help with?",
|
||||
"emptyDescription": "Ask about your Homarr setup, inspect live instance data, or approve actions when you want me to make a change.",
|
||||
"composerPlaceholder": "Ask Homarr Assistant…",
|
||||
"stop": "Stop response",
|
||||
"send": "Send message",
|
||||
"copy": "Copy response",
|
||||
"regenerate": "Regenerate response",
|
||||
"scrollToLatest": "Scroll to latest",
|
||||
"approvalRequired": "Approval required",
|
||||
"complete": "Complete",
|
||||
"denied": "Denied",
|
||||
"failed": "Failed",
|
||||
"working": "Working",
|
||||
"approvalDescription": "This action changes Homarr. Review the input before allowing it.",
|
||||
"allowOnce": "Allow once",
|
||||
"deny": "Deny"
|
||||
},
|
||||
"dangerZone": "Danger zone",
|
||||
"noResults": "No results found",
|
||||
"unsavedChanges": "You have unsaved changes!",
|
||||
@@ -5716,6 +5749,112 @@
|
||||
"text": "This helps us figure out what people actually use so we know where to spend our time. We see stuff like how many widgets or integrations you have, your Homarr version, and what database you're on. That's it — no personal info, no URLs, no names, nothing that could identify you or your setup."
|
||||
}
|
||||
},
|
||||
"assistant": {
|
||||
"title": "Homarr Assistant",
|
||||
"description": "Connect an OpenAI-compatible model endpoint for the instance-wide assistant.",
|
||||
"security": {
|
||||
"title": "Server-side secrets",
|
||||
"description": "API keys and additional header values are encrypted in the Homarr database. They are never returned to browsers. Model requests are sent from the Homarr server directly to the configured endpoint."
|
||||
},
|
||||
"connection": {
|
||||
"title": "Provider connection",
|
||||
"description": "Choose a preset or connect any service that implements the OpenAI Chat Completions API.",
|
||||
"saved": "Connection saved",
|
||||
"notSaved": "Not configured",
|
||||
"save": "Save provider connection",
|
||||
"clearCredentials": "Remove all credentials"
|
||||
},
|
||||
"provider": {
|
||||
"title": "Provider",
|
||||
"options": {
|
||||
"openrouter": {
|
||||
"label": "OpenRouter",
|
||||
"description": "Hosted model routing with a large tool-capable model catalog."
|
||||
},
|
||||
"openai": {
|
||||
"label": "OpenAI",
|
||||
"description": "OpenAI Chat Completions through the official API endpoint."
|
||||
},
|
||||
"ollama": {
|
||||
"label": "Ollama",
|
||||
"description": "A local or network Ollama server using its OpenAI-compatible API."
|
||||
},
|
||||
"lm-studio": {
|
||||
"label": "LM Studio",
|
||||
"description": "An LM Studio local server with OpenAI compatibility enabled."
|
||||
},
|
||||
"custom": {
|
||||
"label": "Custom endpoint",
|
||||
"description": "Any other endpoint compatible with OpenAI Chat Completions."
|
||||
}
|
||||
}
|
||||
},
|
||||
"baseUrl": {
|
||||
"title": "API base URL",
|
||||
"description": "Include the API prefix, usually /v1. In containers, localhost refers to the Homarr container."
|
||||
},
|
||||
"destinationChanged": {
|
||||
"title": "Credentials will not follow this endpoint",
|
||||
"description": "Changing the provider or base URL clears the stored API key and headers unless replacements are entered now. This prevents sending one provider's secrets to another service."
|
||||
},
|
||||
"apiKey": {
|
||||
"title": "API key",
|
||||
"required": "Required by this provider. The value is encrypted and write-only.",
|
||||
"optional": "Optional for local endpoints. Leave it blank when the service does not require bearer authentication.",
|
||||
"placeholder": "Enter an API key",
|
||||
"configured": "A key is configured. Enter a new key to replace it.",
|
||||
"configuredBadge": "Key configured",
|
||||
"pendingRemoval": "Removal pending",
|
||||
"clear": "Remove stored API key when saving",
|
||||
"keep": "Keep stored API key"
|
||||
},
|
||||
"headers": {
|
||||
"title": "Additional request headers",
|
||||
"description": "Optional authentication or routing headers. Header values are encrypted and write-only.",
|
||||
"add": "Add header",
|
||||
"name": "Header name",
|
||||
"value": "Header value",
|
||||
"valuePlaceholder": "Secret or routing value",
|
||||
"remove": "Remove header",
|
||||
"configured": "Additional encrypted headers are configured. Adding headers replaces the complete stored set.",
|
||||
"clear": "Remove stored headers when saving",
|
||||
"keep": "Keep stored headers"
|
||||
},
|
||||
"model": {
|
||||
"title": "Model",
|
||||
"description": "Select a discovered model or enter an exact endpoint model ID.",
|
||||
"placeholder": "Model ID",
|
||||
"refresh": "Refresh models",
|
||||
"discoveryPath": "Model discovery path",
|
||||
"discoveryPathDescription": "Appended to the API base URL. Leave blank to disable discovery and use a manual model ID.",
|
||||
"manual": "Enter a model ID manually or save the connection to discover models.",
|
||||
"manualFallback": "Discovery is unavailable. You can still enter a model ID manually.",
|
||||
"discovered": "Discovered {count} models. Tool support depends on the selected endpoint and model."
|
||||
},
|
||||
"enabled": {
|
||||
"label": "Enable Homarr Assistant",
|
||||
"description": "Shows the assistant to all signed-in users. Existing Homarr permissions still apply to every internal tool call."
|
||||
},
|
||||
"save": "Save assistant settings",
|
||||
"notification": {
|
||||
"connectionSaved": {
|
||||
"title": "Provider connection saved",
|
||||
"message": "The endpoint and encrypted credentials are ready for model selection.",
|
||||
"credentialsCleared": "The endpoint changed, so previous credentials were cleared. Add credentials for the new destination if required."
|
||||
},
|
||||
"credentialsCleared": {
|
||||
"title": "Provider credentials removed",
|
||||
"message": "The stored API key and headers were removed, and the assistant was disabled."
|
||||
},
|
||||
"saved": {
|
||||
"title": "Assistant settings saved",
|
||||
"message": "The new model and availability settings are active."
|
||||
},
|
||||
"error": {
|
||||
"title": "Assistant settings could not be saved"
|
||||
}
|
||||
}
|
||||
},
|
||||
"crawlingAndIndexing": {
|
||||
"title": "Crawling and Indexing",
|
||||
"warning": "Enabling or disabling any settings here will severely impact how search engines will index & crawl your page. Any setting is a request and it is up to the crawler to apply these settings. Any modification may take up to multiple days or weeks to apply. Some settings may be search engine specific.",
|
||||
@@ -6155,7 +6294,8 @@
|
||||
"toggleBoardEdit": "Toggle board edit mode",
|
||||
"toggleColorScheme": "Toggle light/dark mode",
|
||||
"saveNotebook": "Save notebook (only inside notebook widget)",
|
||||
"openSpotlight": "Open search"
|
||||
"openSpotlight": "Open search",
|
||||
"openAssistant": "Open Homarr Assistant"
|
||||
},
|
||||
"note": "Tip: Mod refers to both Ctrl key and ⌘ key on macOS"
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user