feat(ai): add vector DB assistant tools
This commit is contained in:
@@ -17,7 +17,7 @@ import { connectionIconType } from "@/lib/connectionPresentation";
|
||||
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
|
||||
import { useQueryStore } from "@/stores/queryStore";
|
||||
import { useToast } from "@/composables/useToast";
|
||||
import { buildAiContext, runAgentStream, type AiAction } from "@/lib/ai";
|
||||
import { buildAiContext, runAgentStream, isVectorDbType, type AiAction } from "@/lib/ai";
|
||||
import { formatAiModelOption } from "@/lib/aiModelPresentation";
|
||||
import type { AgentEvent } from "@/lib/tauri";
|
||||
import { buildAiAgentPlan } from "@/lib/aiAgentPlan";
|
||||
@@ -287,6 +287,11 @@ const actionMenuItems = computed(() =>
|
||||
);
|
||||
const aiCodeAppearance = computed(() => (isDark.value ? "dark" : "light"));
|
||||
|
||||
const showActionButtons = computed(() => {
|
||||
if (!props.connection) return true;
|
||||
return !isVectorDbType(props.connection.db_type);
|
||||
});
|
||||
|
||||
const { databaseOptions: allDbOptions, loadDatabaseOptions } = useDatabaseOptions();
|
||||
|
||||
const dbOptions = computed(() => {
|
||||
@@ -1312,6 +1317,7 @@ async function openExternalUrl(url: string) {
|
||||
item-class="text-xs px-2"
|
||||
/>
|
||||
<LightDropdown
|
||||
v-if="showActionButtons"
|
||||
:model-value="activeAction"
|
||||
:items="actionMenuItems"
|
||||
content-class="w-max min-w-0"
|
||||
|
||||
+124
-6
@@ -10,6 +10,28 @@ import { effectiveDatabaseTypeForConnection } from "@/lib/jdbcDialect";
|
||||
|
||||
import type { AgentEvent } from "@/lib/tauri";
|
||||
|
||||
const VECTOR_DB_TYPES: ReadonlySet<DatabaseType> = new Set([
|
||||
"qdrant",
|
||||
"milvus",
|
||||
"weaviate",
|
||||
"chromadb",
|
||||
// If modifying this, also update is_vector_db() in crates/dbx-core/src/agent_tools.rs.
|
||||
]);
|
||||
|
||||
export function isVectorDbType(dbType: DatabaseType): boolean {
|
||||
return VECTOR_DB_TYPES.has(dbType);
|
||||
}
|
||||
|
||||
function dbLabel(dbType: DatabaseType): string {
|
||||
const labels: Partial<Record<DatabaseType, string>> = {
|
||||
qdrant: "Qdrant",
|
||||
milvus: "Milvus",
|
||||
weaviate: "Weaviate",
|
||||
chromadb: "ChromaDB",
|
||||
};
|
||||
return labels[dbType] || dbType;
|
||||
}
|
||||
|
||||
export type AiAction = "generate" | "explain" | "optimize" | "fix" | "convert" | "sampleData";
|
||||
export type AiAssistantMode = "ask" | "agent";
|
||||
|
||||
@@ -50,10 +72,8 @@ export interface AiRequestInput {
|
||||
|
||||
function buildAgentRequest(input: AiRequestInput, history?: api.AiMessage[]): { messages: api.AiMessage[]; systemPrompt: string; taskContract: api.AiTaskContract; maxTokens: number; temperature: number } {
|
||||
const isZh = isChineseLocale(currentLocale());
|
||||
const skill = aiSkillForAction(input.action);
|
||||
const systemPrompt = buildSystemPrompt(input.action, input.context, input.mode);
|
||||
const instruction = isZh ? skill.userInstruction.zh : skill.userInstruction.en;
|
||||
const userPrompt = [`Action: ${input.action}`, instruction, "", "User request:", input.instruction.trim() || "(No extra instruction provided.)"].join("\n");
|
||||
const userPrompt = buildUserPrompt(input.action, input.context, input.instruction, isZh);
|
||||
const taskContract: api.AiTaskContract = {
|
||||
action: input.action,
|
||||
mode: input.mode || "ask",
|
||||
@@ -124,6 +144,17 @@ export async function runAgentStream(input: AiRequestInput, history: api.AiMessa
|
||||
);
|
||||
}
|
||||
|
||||
export function buildUserPrompt(action: AiAction, context: AiContext, instruction: string, isZh: boolean): string {
|
||||
const userRequest = instruction.trim() || (isZh ? "(无额外说明)" : "(No extra instruction provided.)");
|
||||
if (isVectorDbType(context.databaseType)) {
|
||||
// Vector databases: skip SQL action instructions, only send the user's request
|
||||
return userRequest;
|
||||
}
|
||||
const skill = aiSkillForAction(action);
|
||||
const skillInstruction = isZh ? skill.userInstruction.zh : skill.userInstruction.en;
|
||||
return [`Action: ${action}`, skillInstruction, "", "User request:", userRequest].join("\n");
|
||||
}
|
||||
|
||||
function actionParams(action: AiAction): { maxTokens: number; temperature: number } {
|
||||
switch (action) {
|
||||
case "explain":
|
||||
@@ -142,6 +173,9 @@ export function extractSql(text: string): string {
|
||||
}
|
||||
|
||||
export function buildSystemPrompt(action: AiAction, context: AiContext, mode: AiAssistantMode = "ask"): string {
|
||||
if (isVectorDbType(context.databaseType)) {
|
||||
return buildVectorSystemPrompt(context, mode);
|
||||
}
|
||||
const schema = formatSchema(context);
|
||||
const resultPreview = context.lastResultPreview ? `\nLast result preview:\n${context.lastResultPreview}\n` : "";
|
||||
const lastError = context.lastError ? `\nLast error:\n${context.lastError}\n` : "";
|
||||
@@ -207,6 +241,50 @@ function buildBasePromptLines(isZh: boolean): string[] {
|
||||
];
|
||||
}
|
||||
|
||||
function buildVectorSystemPrompt(context: AiContext, mode: AiAssistantMode): string {
|
||||
const isZh = isChineseLocale(currentLocale());
|
||||
const schema = formatSchema(context);
|
||||
const resultPreview = context.lastResultPreview ? `\nLast result preview:\n${context.lastResultPreview}\n` : "";
|
||||
const lastError = context.lastError ? `\nLast error:\n${context.lastError}\n` : "";
|
||||
const lines: string[] = [
|
||||
isZh ? `你是 DBX 内置的向量数据库助手。当前连接的是 ${dbLabel(context.databaseType)} 数据库。用中文回复。` : `You are DBX's vector database assistant. Connected to ${dbLabel(context.databaseType)}. Reply in English.`,
|
||||
isZh ? "数据存储在集合(collections)中,每条记录包含唯一标识及可选的元数据负载(payload/metadata)。" : "Data is stored in collections. Each record has a unique identifier and optional metadata payload.",
|
||||
...buildVectorModePromptLines(context, mode, isZh),
|
||||
"",
|
||||
`Database type: ${context.databaseType}`,
|
||||
`Connection: ${context.connectionName}`,
|
||||
`Database: ${context.database}`,
|
||||
schemaCoverageLine(context, isZh),
|
||||
"",
|
||||
`Current collection:\n${context.currentSql.trim() || "(none)"}`,
|
||||
lastError,
|
||||
resultPreview,
|
||||
"",
|
||||
`Schema:\n${schema}`,
|
||||
];
|
||||
|
||||
if (context.schemaScope === "focused_table") {
|
||||
lines.push(
|
||||
isZh
|
||||
? "Schema 上下文只覆盖当前打开的集合;数据库中可能还有其他集合。用户询问当前有哪些集合或提到上下文中不存在的集合时,不要直接断言不存在,先用 list_collections 工具确认。"
|
||||
: "Schema context covers only the currently opened collection; the database may contain other collections. When the user asks what collections exist or mentions a collection absent from context, do not conclude it is missing; use list_collections to verify first.",
|
||||
);
|
||||
}
|
||||
|
||||
return lines.filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
function buildVectorModePromptLines(context: AiContext, mode: AiAssistantMode, isZh: boolean): string[] {
|
||||
if (mode === "agent") {
|
||||
return [isZh ? "你处于 Agent 模式。你有以下工具可用:list_collections、browse_collection。" : "You are in Agent mode. You have the following tools available: list_collections, browse_collection."];
|
||||
}
|
||||
return [
|
||||
isZh
|
||||
? `你处于 Ask 模式。你只能使用 list_collections 确认集合清单;不要浏览集合数据。${dbLabel(context.databaseType)} 的查询格式为 REST API(METHOD /path + JSON body),具体格式因数据库类型而异。只生成查询请求文本和说明,不要暗示已经执行。`
|
||||
: `You are in Ask mode. You may only use list_collections to inspect collection names; do not browse collection data. ${dbLabel(context.databaseType)} uses a REST API query format (METHOD /path + JSON body) that varies by database type. Generate query strings and explanations only; do not imply execution.`,
|
||||
];
|
||||
}
|
||||
|
||||
function buildModePromptLines(mode: AiAssistantMode, isZh: boolean): string[] {
|
||||
if (mode === "agent") {
|
||||
return [
|
||||
@@ -226,7 +304,10 @@ function buildModePromptLines(mode: AiAssistantMode, isZh: boolean): string[] {
|
||||
|
||||
function schemaCoverageLine(context: AiContext, isZh: boolean): string {
|
||||
if (context.schemaScope === "focused_table") {
|
||||
return isZh ? "Schema context scope: focused table only; not a complete database table list." : "Schema context scope: focused table only; not a complete database table list.";
|
||||
if (isVectorDbType(context.databaseType)) {
|
||||
return isZh ? "Schema 上下文只覆盖当前打开的集合,不是完整的集合列表。" : "Schema context scope: focused collection only; not a complete collection list.";
|
||||
}
|
||||
return "Schema context scope: focused table only; not a complete database table list.";
|
||||
}
|
||||
return context.truncated ? "Schema context is truncated." : "Schema context is complete for the loaded database scope.";
|
||||
}
|
||||
@@ -279,6 +360,7 @@ export async function buildAiContext(tab: QueryTab, connection: ConnectionConfig
|
||||
const tableKeys = new Set<string>();
|
||||
let truncated = false;
|
||||
let schemaScope: AiContext["schemaScope"] = "database";
|
||||
let currentCollectionName: string | undefined;
|
||||
|
||||
if (tab.tableMeta) {
|
||||
schemaScope = "focused_table";
|
||||
@@ -308,7 +390,43 @@ export async function buildAiContext(tab: QueryTab, connection: ConnectionConfig
|
||||
tables.push(entry);
|
||||
}
|
||||
|
||||
if (!tab.tableMeta && !["redis", "mongodb"].includes(connection.db_type)) {
|
||||
// Vector databases: load collections instead of SQL tables
|
||||
if (isVectorDbType(databaseType)) {
|
||||
try {
|
||||
const collections = await api.vectorListCollections(tab.connectionId);
|
||||
|
||||
// Find the currently opened collection (tab.sql is UUID for ChromaDB, name for others)
|
||||
const currentCollection = collections.find((c) => c.id === tab.sql || c.name === tab.sql);
|
||||
if (currentCollection) {
|
||||
schemaScope = "focused_table";
|
||||
currentCollectionName = currentCollection.name;
|
||||
tables.push({
|
||||
name: currentCollection.name,
|
||||
tableType: "COLLECTION",
|
||||
comment: currentCollection.dimension ? `${currentCollection.dimension}d vector` : undefined,
|
||||
columns: [],
|
||||
});
|
||||
tableKeys.add(aiTableMentionKey(undefined, currentCollection.name));
|
||||
}
|
||||
|
||||
for (const col of collections.slice(0, maxTables)) {
|
||||
const key = aiTableMentionKey(undefined, col.name);
|
||||
if (tableKeys.has(key)) continue;
|
||||
tables.push({
|
||||
name: col.name,
|
||||
tableType: "COLLECTION",
|
||||
comment: col.dimension ? `${col.dimension}d vector` : undefined,
|
||||
columns: [],
|
||||
});
|
||||
tableKeys.add(key);
|
||||
}
|
||||
if (collections.length > maxTables) truncated = true;
|
||||
} catch {
|
||||
truncated = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!tab.tableMeta && !["redis", "mongodb"].includes(connection.db_type) && !isVectorDbType(databaseType)) {
|
||||
try {
|
||||
const schemas = await loadCandidateSchemas(tab, connection);
|
||||
for (const schema of schemas) {
|
||||
@@ -355,7 +473,7 @@ export async function buildAiContext(tab: QueryTab, connection: ConnectionConfig
|
||||
connectionName: connection.name,
|
||||
databaseType,
|
||||
database: tab.database,
|
||||
currentSql: tab.sql,
|
||||
currentSql: currentCollectionName ?? tab.sql,
|
||||
lastError: extractLastError(tab.result),
|
||||
lastResultPreview: formatResultPreview(tab.result),
|
||||
tables,
|
||||
|
||||
Reference in New Issue
Block a user