clear: old code
This commit is contained in:
@@ -1 +0,0 @@
|
||||
import './list.ts';
|
||||
@@ -1,137 +0,0 @@
|
||||
import { app } from '@/app.ts';
|
||||
import { AiAgent, AiProperties } from '@/models/agent.ts';
|
||||
import { CustomError } from '@kevisual/router';
|
||||
// import { agentManger } from '@kevisual/ai-lang';
|
||||
import { v4 } from 'uuid';
|
||||
app
|
||||
.route({
|
||||
path: 'agent',
|
||||
key: 'list',
|
||||
middleware: ['auth'],
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const agents = await AiAgent.findAll({
|
||||
order: [['updatedAt', 'DESC']],
|
||||
// 返回的内容,不包含apiKey的字段
|
||||
attributes: { exclude: ['apiKey'] },
|
||||
});
|
||||
ctx.body = agents;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route('agent', 'get')
|
||||
.define(async (ctx) => {
|
||||
const id = ctx.query.id;
|
||||
if (!id) {
|
||||
throw new CustomError('id is required');
|
||||
}
|
||||
ctx.body = await AiAgent.findByPk(id, {
|
||||
attributes: { exclude: ['apiKey'] },
|
||||
});
|
||||
return ctx;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route('agent', 'update')
|
||||
.define(async (ctx) => {
|
||||
const { id, ...rest } = ctx.query.data;
|
||||
let agent = await AiAgent.findByPk(id);
|
||||
if (!agent) {
|
||||
agent = await AiAgent.create(rest);
|
||||
ctx.body = agent;
|
||||
return ctx;
|
||||
}
|
||||
await agent.update(rest);
|
||||
ctx.body = agent;
|
||||
return ctx;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route('agent', 'delete')
|
||||
.define(async (ctx) => {
|
||||
const id = ctx.query.id;
|
||||
if (!id) {
|
||||
throw new CustomError('id is required');
|
||||
}
|
||||
const agent = await AiAgent.findByPk(id);
|
||||
if (!agent) {
|
||||
throw new CustomError('agent not found');
|
||||
}
|
||||
await agent.destroy();
|
||||
ctx.body = agent;
|
||||
return ctx;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
// app
|
||||
// .route('agent', 'test')
|
||||
// .define(async (ctx) => {
|
||||
// const { message } = ctx.query;
|
||||
// const data: AiProperties = {
|
||||
// type: 'ollama',
|
||||
// id: 'test',
|
||||
// model: 'qwen2.5:14b',
|
||||
// baseUrl: 'http://mz.zxj.im:11434',
|
||||
// cache: 'memory',
|
||||
// };
|
||||
// const agent = agentManger.createAgent(data as any);
|
||||
// const res = await agent.sendHumanMessage(message);
|
||||
// // agent.close();
|
||||
// agentManger.removeAgent(agent.id);
|
||||
// ctx.body = res;
|
||||
// return ctx;
|
||||
// })
|
||||
// .addTo(app);
|
||||
|
||||
export const agentModelList = ['qwen2.5:14b', 'qwen2.5-coder:7b', 'llama3.1:8b', 'bakllava:latest'] as const;
|
||||
export const openAiModels = ['gpt-4o'];
|
||||
const demoData: AiProperties[] = [
|
||||
{
|
||||
id: v4(),
|
||||
type: 'openai',
|
||||
model: 'gpt-4o',
|
||||
baseUrl: 'https://oneapi.on-ai.ai/v1',
|
||||
apiKey: 'sk-GJE6I8OJWDr2ErFBD4C4706a65Ad4cD9B596Cf7c76943e45',
|
||||
},
|
||||
...agentModelList.map((item) => {
|
||||
return {
|
||||
id: v4(),
|
||||
type: 'ollama',
|
||||
model: item,
|
||||
baseUrl: 'http://mz.zxj.im:11434',
|
||||
apiKey: 'sk-GJE6I8OJWDr2ErFBD4C4706a65Ad4cD9B596Cf7c76943e45',
|
||||
};
|
||||
}),
|
||||
];
|
||||
|
||||
// AiAgent.bulkCreate(demoData, { ignoreDuplicates: true }).then(() => {
|
||||
// console.log('create demo data success');
|
||||
// });
|
||||
const initManager = async () => {
|
||||
// const list = await AiAgent.findAll();
|
||||
const list = await AiAgent.findAll({
|
||||
where: {
|
||||
status: 'open',
|
||||
},
|
||||
logging: false,
|
||||
});
|
||||
const data = list.map((item) => {
|
||||
return {
|
||||
id: item.id,
|
||||
type: item.type as any,
|
||||
model: item.model as any,
|
||||
baseUrl: item.baseUrl,
|
||||
apiKey: item.apiKey,
|
||||
temperature: item.temperature,
|
||||
cache: item.cache as any,
|
||||
cacheName: item.cacheName,
|
||||
};
|
||||
});
|
||||
// agentManger.createAgentList(data);
|
||||
};
|
||||
// setTimeout(() => {
|
||||
// initManager();
|
||||
// }, 1000);
|
||||
@@ -1,201 +0,0 @@
|
||||
import { app } from '@/app.ts';
|
||||
import { AiAgent } from '@/models/agent.ts';
|
||||
import { ChatPrompt } from '@/models/chat-prompt.ts';
|
||||
import { ChatSession } from '@/models/chat-session.ts';
|
||||
import { Prompt } from '@/models/prompt.ts';
|
||||
import { agentManger } from '@kevisual/ai-lang';
|
||||
import { PromptTemplate } from '@kevisual/ai-graph';
|
||||
import { v4 } from 'uuid';
|
||||
import { ChatHistory } from '@/models/chat-history.ts';
|
||||
import { User } from '@/models/user.ts';
|
||||
const clients = [];
|
||||
export const compotedToken = () => {
|
||||
// 计算token消耗
|
||||
};
|
||||
export const getConfigByKey = async (key) => {
|
||||
const chatPrompt = await ChatPrompt.findOne({ where: { key } });
|
||||
const { promptId, aiAgentId } = chatPrompt.data;
|
||||
const prompt = await Prompt.findByPk(promptId);
|
||||
let aiAgent = agentManger.getAgent(aiAgentId);
|
||||
if (!aiAgent) {
|
||||
// throw new Error('aiAgent not found');
|
||||
const aiAgnetModel = await AiAgent.findByPk(aiAgentId);
|
||||
aiAgent = agentManger.createAgent({
|
||||
id: aiAgnetModel.id,
|
||||
type: aiAgnetModel.type as any,
|
||||
model: aiAgnetModel.model as any,
|
||||
baseUrl: aiAgnetModel.baseUrl,
|
||||
apiKey: aiAgnetModel.apiKey,
|
||||
temperature: aiAgnetModel.temperature,
|
||||
cache: aiAgnetModel.cache as any,
|
||||
cacheName: aiAgnetModel.cacheName,
|
||||
});
|
||||
}
|
||||
return { chatPrompt, prompt, aiAgent };
|
||||
};
|
||||
export const getTemplate = async ({ data, inputs }) => {
|
||||
const promptTemplate = new PromptTemplate({
|
||||
prompt: data.prompt,
|
||||
inputVariables: inputs.map((item) => {
|
||||
return {
|
||||
key: item.key,
|
||||
value: item.value,
|
||||
};
|
||||
}),
|
||||
localVariables: [],
|
||||
}); // 传入参数
|
||||
return await promptTemplate.getTemplate();
|
||||
};
|
||||
const onMessage = async ({ data, end, ws }) => {
|
||||
// messages的 data
|
||||
const client = clients.find((client) => client.ws === ws);
|
||||
if (!client) {
|
||||
end({ code: 404, data: {}, message: 'client not found' });
|
||||
return;
|
||||
}
|
||||
const { uid, id, key } = client.data;
|
||||
const {
|
||||
inputs,
|
||||
message: sendMessage,
|
||||
data: {},
|
||||
} = data;
|
||||
let root = data.root || false;
|
||||
let chatSession = await ChatSession.findByPk(id);
|
||||
const config = await getConfigByKey(key);
|
||||
const { prompt, aiAgent, chatPrompt } = config;
|
||||
let userQuestion = sendMessage;
|
||||
if (!chatSession) {
|
||||
chatSession = await ChatSession.create({ key, id, data: data, uid, chatPromptId: chatPrompt.id });
|
||||
root = true;
|
||||
} else {
|
||||
// 更新session context的值
|
||||
const newData = JSON.parse(data);
|
||||
if (newData !== '{}' && JSON.stringify(chatSession.data) !== JSON.stringify(data)) {
|
||||
await chatSession.update({ data: data });
|
||||
}
|
||||
if (root) {
|
||||
const chatHistory = await ChatHistory.findAll({ where: { chatId: id }, logging: false });
|
||||
chatHistory.forEach((item) => {
|
||||
end({ code: 200, data: item, message: 'success', type: 'messages' });
|
||||
});
|
||||
// return;
|
||||
}
|
||||
root = false;
|
||||
}
|
||||
if (!userQuestion) {
|
||||
if (!prompt?.presetData) {
|
||||
end({ code: 404, data: {}, message: 'prompt not set, need presetData' });
|
||||
return;
|
||||
}
|
||||
const template = await getTemplate({ data: prompt.presetData.data, inputs });
|
||||
if (!template) {
|
||||
end({ code: 404, data: {}, message: 'template not found' });
|
||||
return;
|
||||
}
|
||||
userQuestion = template;
|
||||
}
|
||||
// 保存到数据库
|
||||
const roleUser = await ChatHistory.create({
|
||||
data: {
|
||||
message: userQuestion,
|
||||
},
|
||||
chatId: id,
|
||||
chatPromptId: chatPrompt.id,
|
||||
root: root,
|
||||
uid: uid,
|
||||
show: true,
|
||||
role: 'user',
|
||||
});
|
||||
end({ code: 200, data: roleUser, message: 'success', type: 'messages' });
|
||||
const result = await aiAgent.sendHumanMessage(userQuestion, { thread_id: id });
|
||||
const lastMessage = result.messages[result.messages.length - 1];
|
||||
const message = result.messages[result.messages.length - 1].content;
|
||||
// 根据key找到对应的prompt
|
||||
// 保存到数据库
|
||||
const roleAi = await ChatHistory.create({
|
||||
data: {
|
||||
message,
|
||||
result: lastMessage,
|
||||
},
|
||||
chatId: id,
|
||||
chatPromptId: chatPrompt.id,
|
||||
root: false,
|
||||
uid: uid,
|
||||
show: true,
|
||||
role: 'ai',
|
||||
});
|
||||
end({ code: 200, data: roleAi, message: 'success', type: 'messages' });
|
||||
};
|
||||
const getHistory = async (id: string, { data, end, ws }) => {
|
||||
const chatHistory = await ChatHistory.findAll({ where: { chatId: id }, logging: false });
|
||||
chatHistory.forEach((item) => {
|
||||
end({ code: 200, data: item, message: 'success', type: 'messages' });
|
||||
});
|
||||
};
|
||||
app.io.addListener('chat', async ({ data, end, ws }) => {
|
||||
const { type } = data || {};
|
||||
if (type === 'subscribe') {
|
||||
const token = data?.token;
|
||||
if (!token) {
|
||||
end({ code: 401, data: {}, message: 'need token' });
|
||||
return;
|
||||
}
|
||||
let tokenUesr;
|
||||
try {
|
||||
tokenUesr = await User.verifyToken(token);
|
||||
} catch (e) {
|
||||
end({ code: 401, data: {}, message: 'token is invaild' });
|
||||
return;
|
||||
}
|
||||
const uid = tokenUesr.id;
|
||||
const id = v4();
|
||||
const clientData = { ...data?.data, uid };
|
||||
if (!clientData.id) {
|
||||
clientData.id = id;
|
||||
}
|
||||
const client = clients.find((client) => client.ws === ws);
|
||||
if (!client) {
|
||||
clients.push({ ws, data: clientData }); // 拆包,里面包含的type信息,去掉
|
||||
}
|
||||
end({ code: 200, data: clientData, message: 'subscribe success' });
|
||||
} else if (type === 'unsubscribe') {
|
||||
// 需要手动取消订阅
|
||||
const index = clients.findIndex((client) => client.ws === ws);
|
||||
if (index > -1) {
|
||||
const data = clients[index]?.data;
|
||||
clients.splice(index, 1);
|
||||
end({ code: 200, data, message: 'unsubscribe success' });
|
||||
return;
|
||||
}
|
||||
end({ code: 200, data: {}, message: 'unsubscribe success' });
|
||||
return;
|
||||
} else if (type === 'messages') {
|
||||
try {
|
||||
await onMessage({ data: data.data, end, ws });
|
||||
} catch (e) {
|
||||
console.error('onMessage error', e);
|
||||
end({ code: 500, data: {}, message: 'onMessage error' });
|
||||
}
|
||||
return;
|
||||
} else if (type === 'changeSession') {
|
||||
// 修改client的session的id
|
||||
const client = clients.find((client) => client.ws === ws);
|
||||
if (!client) {
|
||||
end({ code: 404, data: {}, message: 'client not found' });
|
||||
return;
|
||||
}
|
||||
const { id } = data?.data;
|
||||
client.data.id = id || v4();
|
||||
// 返回修改后的history的内容
|
||||
end({ code: 200, data: client.data, message: 'changeSession success' });
|
||||
getHistory(id, { data, end, ws });
|
||||
return;
|
||||
} else {
|
||||
end({ code: 404, data: {}, message: 'subscribe fail' });
|
||||
return;
|
||||
}
|
||||
ws.on('close', () => {
|
||||
const index = clients.findIndex((client) => client.ws === ws);
|
||||
if (index > -1) clients.splice(index, 1);
|
||||
});
|
||||
});
|
||||
@@ -1,3 +0,0 @@
|
||||
import './list.ts'
|
||||
import './session-list.ts'
|
||||
import './chat-io.ts'
|
||||
@@ -1,34 +0,0 @@
|
||||
import { app } from '@/app.ts';
|
||||
import { ChatHistory } from '@/models/chat-history.ts';
|
||||
import { CustomError } from '@kevisual/router';
|
||||
|
||||
// Admin only
|
||||
app
|
||||
.route({
|
||||
path: 'chat-history',
|
||||
key: 'list',
|
||||
middleware: ['auth'],
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const chatPrompt = await ChatHistory.findAll({
|
||||
order: [['updatedAt', 'DESC']],
|
||||
});
|
||||
ctx.body = chatPrompt;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route({
|
||||
path: 'chat-history',
|
||||
key: 'delete',
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const { id } = ctx.query;
|
||||
const chatHistory = await ChatHistory.findByPk(id);
|
||||
if (!chatHistory) {
|
||||
throw new CustomError('ChatHistory not found');
|
||||
}
|
||||
await chatHistory.destroy();
|
||||
ctx.body = chatHistory;
|
||||
})
|
||||
.addTo(app);
|
||||
@@ -1,84 +0,0 @@
|
||||
import { app } from '@/app.ts';
|
||||
import { ChatSession } from '@/models/chat-session.ts';
|
||||
import { ChatPrompt } from '@/models/chat-prompt.ts';
|
||||
import { CustomError } from '@kevisual/router';
|
||||
app
|
||||
.route({
|
||||
path: 'chat-session',
|
||||
key: 'list',
|
||||
middleware: ['auth'],
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const chatSession = await ChatSession.findAll({
|
||||
order: [['updatedAt', 'DESC']],
|
||||
});
|
||||
ctx.body = chatSession;
|
||||
})
|
||||
.addTo(app);
|
||||
// Admin only
|
||||
app
|
||||
.route({
|
||||
path: 'chat-session',
|
||||
key: 'list-history',
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const data = ctx.query.data;
|
||||
const chatPrompt = await ChatPrompt.findOne({
|
||||
where: {
|
||||
key: data.key,
|
||||
},
|
||||
});
|
||||
if (!chatPrompt) {
|
||||
throw new CustomError('ChatPrompt not found');
|
||||
}
|
||||
console.log('chatPrompt', chatPrompt.id);
|
||||
const chatSession = await ChatSession.findAll({
|
||||
order: [['updatedAt', 'DESC']],
|
||||
where: {
|
||||
chatPromptId: chatPrompt.id,
|
||||
},
|
||||
limit: data.limit || 10,
|
||||
});
|
||||
ctx.body = chatSession;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route({
|
||||
path: 'chat-session',
|
||||
key: 'update',
|
||||
middleware: ['auth'],
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const tokenUser = ctx.state.tokenUser;
|
||||
const uid = tokenUser.id;
|
||||
const { id, ...data } = ctx.query.data;
|
||||
if (id) {
|
||||
const session = await ChatSession.findByPk(id);
|
||||
if (session) {
|
||||
await session.update(data);
|
||||
} else {
|
||||
throw new CustomError('Session not found');
|
||||
}
|
||||
ctx.body = session;
|
||||
return;
|
||||
}
|
||||
const session = await ChatSession.create({ ...data, uid });
|
||||
ctx.body = session;
|
||||
})
|
||||
.addTo(app);
|
||||
app
|
||||
.route({
|
||||
path: 'chat-session',
|
||||
key: 'delete',
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const { id } = ctx.query;
|
||||
const session = await ChatSession.findByPk(id);
|
||||
if (!session) {
|
||||
throw new CustomError('Session not found');
|
||||
}
|
||||
await session.destroy();
|
||||
ctx.body = session;
|
||||
})
|
||||
.addTo(app);
|
||||
@@ -1 +0,0 @@
|
||||
import './list.ts';
|
||||
@@ -1,131 +0,0 @@
|
||||
import { app } from '@/app.ts';
|
||||
import { AiAgent } from '@/models/agent.ts';
|
||||
import { ChatPrompt } from '@/models/chat-prompt.ts';
|
||||
import { Prompt } from '@/models/prompt.ts';
|
||||
import { CustomError } from '@kevisual/router';
|
||||
|
||||
// Admin only
|
||||
app
|
||||
.route({
|
||||
path: 'chat-prompt',
|
||||
key: 'list',
|
||||
// middleware: ['auth'],
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const chatPrompt = await ChatPrompt.findAll({
|
||||
order: [['updatedAt', 'DESC']],
|
||||
// 列出被删除的
|
||||
// paranoid: false,
|
||||
});
|
||||
ctx.body = chatPrompt;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route({
|
||||
path: 'chat-prompt',
|
||||
key: 'get',
|
||||
validator: {
|
||||
id: {
|
||||
type: 'string',
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const { id } = ctx.query;
|
||||
const chatPrompt = await ChatPrompt.findByPk(id);
|
||||
if (!chatPrompt) {
|
||||
throw new CustomError('ChatPrompt not found');
|
||||
}
|
||||
ctx.body = chatPrompt;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route({
|
||||
path: 'chat-prompt',
|
||||
key: 'update',
|
||||
middleware: ['auth'],
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const tokenUser = ctx.state.tokenUser;
|
||||
const uid = tokenUser.id;
|
||||
const { data } = ctx.query;
|
||||
const { id, ...rest } = data;
|
||||
if (id) {
|
||||
const page = await ChatPrompt.findByPk(id);
|
||||
if (page) {
|
||||
if (rest.data) {
|
||||
rest.data = { ...page.data, ...rest.data };
|
||||
}
|
||||
const newPage = await page.update(rest);
|
||||
ctx.body = newPage;
|
||||
} else {
|
||||
throw new CustomError('page not found');
|
||||
}
|
||||
} else if (data) {
|
||||
const page = await ChatPrompt.create({ ...rest, uid });
|
||||
ctx.body = page;
|
||||
}
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route({
|
||||
path: 'chat-prompt',
|
||||
key: 'delete',
|
||||
validator: {
|
||||
id: {
|
||||
type: 'string',
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
middleware: ['auth'],
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const id = ctx.query.id;
|
||||
const chatPrompt = await ChatPrompt.findByPk(id);
|
||||
if (!chatPrompt) {
|
||||
throw new CustomError('chatPrompt not found');
|
||||
}
|
||||
await chatPrompt.destroy();
|
||||
ctx.body = 'success';
|
||||
})
|
||||
.addTo(app);
|
||||
app
|
||||
.route({
|
||||
path: 'chat-prompt',
|
||||
key: 'getByKey',
|
||||
middleware: ['auth'],
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const { key } = ctx.query.data || {};
|
||||
if (!key) {
|
||||
throw new CustomError('key is required');
|
||||
}
|
||||
const chatPrompt = await ChatPrompt.findOne({
|
||||
where: { key },
|
||||
});
|
||||
if (!chatPrompt) {
|
||||
throw new CustomError('chatPrompt not found');
|
||||
}
|
||||
const { promptId, aiAgentId } = chatPrompt.data;
|
||||
if (!aiAgentId) {
|
||||
throw new CustomError('promptId is required');
|
||||
}
|
||||
const aiAgent = await AiAgent.findByPk(aiAgentId, {
|
||||
// 只获取 id 和description 字段
|
||||
attributes: ['id', 'description', 'key'],
|
||||
});
|
||||
if (!aiAgent) {
|
||||
throw new CustomError('aiAgent not found');
|
||||
}
|
||||
const prompt = await Prompt.findByPk(promptId);
|
||||
ctx.body = {
|
||||
chatPrompt: chatPrompt,
|
||||
aiAgent,
|
||||
prompt,
|
||||
};
|
||||
})
|
||||
.addTo(app);
|
||||
@@ -4,16 +4,8 @@ import './page/index.ts';
|
||||
|
||||
import './resource/index.ts';
|
||||
|
||||
import './prompt-graph/index.ts';
|
||||
|
||||
import './agent/index.ts';
|
||||
|
||||
import './user/index.ts';
|
||||
|
||||
import './chat-prompt/index.ts';
|
||||
|
||||
import './chat-history/index.ts';
|
||||
|
||||
import './github/index.ts';
|
||||
|
||||
import './app-manager/index.ts';
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
import { app } from '@/app.ts';
|
||||
import { Prompt } from '@/models/prompt.ts';
|
||||
import { chat } from '@/modules/ollama.ts';
|
||||
import { CustomError } from '@kevisual/router';
|
||||
import { PromptTemplate } from '@kevisual/ai-graph';
|
||||
import { v4 } from 'uuid';
|
||||
app
|
||||
.route('ai', 'run', { nextRoute: { id: 'runOllama' } })
|
||||
.define({
|
||||
validator: {
|
||||
data: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
key: {
|
||||
type: 'string',
|
||||
required: true,
|
||||
message: 'Prompt key is required',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
// ctx.currentRoute?.verify(ctx, true);
|
||||
|
||||
const { key, inputs = [] } = ctx.query.data || {};
|
||||
if (!key) {
|
||||
throw new CustomError('Prompt key is required');
|
||||
}
|
||||
const prompt = await Prompt.findOne({ where: { key } });
|
||||
console.log('prompt', 'key', key, prompt);
|
||||
if (!prompt) {
|
||||
throw new CustomError('Prompt not found');
|
||||
}
|
||||
const { presetData } = prompt;
|
||||
const { data, validator } = presetData || {};
|
||||
// const { inputs = [] } = data;
|
||||
// TODO: 获取validator和inputs的内容
|
||||
const promptTemplate = new PromptTemplate({
|
||||
prompt: data.prompt,
|
||||
inputVariables: inputs.map((item) => {
|
||||
return {
|
||||
key: item.key,
|
||||
value: item.value,
|
||||
};
|
||||
}),
|
||||
localVariables: [],
|
||||
});
|
||||
const result = await promptTemplate.getTemplate();
|
||||
ctx.state = {
|
||||
prompt: result,
|
||||
};
|
||||
ctx.body = result;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route('ai', 'runOllama', {
|
||||
id: 'runOllama',
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const prompt = ctx.state.prompt;
|
||||
const uuid = v4();
|
||||
if (!prompt) {
|
||||
throw new CustomError('Prompt Template not found');
|
||||
}
|
||||
const res = await chat([
|
||||
{
|
||||
role: 'user',
|
||||
content: prompt,
|
||||
},
|
||||
]);
|
||||
ctx.body = { id: uuid, ...res };
|
||||
})
|
||||
.addTo(app);
|
||||
@@ -1,73 +0,0 @@
|
||||
import { getSession } from '@/modules/neo4j.ts';
|
||||
export async function fetchData() {
|
||||
const session = getSession();
|
||||
try {
|
||||
const query = `MATCH (n)
|
||||
OPTIONAL MATCH (n)-[r]->(m)
|
||||
RETURN n, r, m`;
|
||||
const queryConnect = 'MATCH (n)-[r]->(m) RETURN n, r, m LIMIT 25';
|
||||
const result = await session.run(query);
|
||||
|
||||
const graphData = { nodes: [], links: [] };
|
||||
const nodeMap = new Map();
|
||||
// n和n的关系用 relatedPrompts 进行关联
|
||||
result.records.forEach((record) => {
|
||||
const node = record.get('n');
|
||||
const relation = record.get('r');
|
||||
const target = record.get('m');
|
||||
if (!nodeMap.has(node.identity)) {
|
||||
nodeMap.set(node.identity, {
|
||||
id: node.identity.toString(),
|
||||
label: node.labels[0],
|
||||
properties: node.properties,
|
||||
});
|
||||
graphData.nodes.push(nodeMap.get(node.identity));
|
||||
}
|
||||
|
||||
if (relation && !nodeMap.has(relation.identity)) {
|
||||
nodeMap.set(relation.identity, {
|
||||
id: relation.identity.toString(),
|
||||
label: relation.type,
|
||||
properties: relation.properties,
|
||||
});
|
||||
graphData.nodes.push(nodeMap.get(relation.identity));
|
||||
}
|
||||
|
||||
if (target && !nodeMap.has(target.identity)) {
|
||||
nodeMap.set(target.identity, {
|
||||
id: target.identity.toString(),
|
||||
label: target.labels[0],
|
||||
properties: target.properties,
|
||||
});
|
||||
graphData.nodes.push(nodeMap.get(target.identity));
|
||||
}
|
||||
|
||||
if (relation) {
|
||||
graphData.links.push({
|
||||
source: node.identity.toString(),
|
||||
target: relation.identity.toString(),
|
||||
type: relation.type,
|
||||
properties: relation.properties,
|
||||
});
|
||||
}
|
||||
|
||||
if (target) {
|
||||
graphData.links.push({
|
||||
source: node.identity.toString(),
|
||||
target: target.identity.toString(),
|
||||
type: 'RELATED_TO',
|
||||
properties: {},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return graphData;
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
}
|
||||
|
||||
// fetchData().then((graphData) => {
|
||||
// console.log(graphData); // 用于验证获取的数据
|
||||
// drawGraph(graphData); // 调用 D3 绘制函数
|
||||
// });
|
||||
@@ -1,3 +0,0 @@
|
||||
import './list-graph.ts';
|
||||
import './list.ts';
|
||||
import './ai.ts';
|
||||
@@ -1,97 +0,0 @@
|
||||
import { PromptNeo, createRelationship, createRelationship2 } from '@/models/prompt-graph.ts';
|
||||
import { app } from '@/app.ts';
|
||||
import { v4 } from 'uuid';
|
||||
import { fetchData } from './d3/get-graph.ts';
|
||||
app
|
||||
.route('prompt-graph', 'list')
|
||||
.define(async (ctx) => {
|
||||
const prompts = await PromptNeo.all();
|
||||
const json = await prompts.toJson();
|
||||
// console.log('json', json);
|
||||
ctx.body = json;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route('prompt-graph', 'update')
|
||||
.define(async (ctx) => {
|
||||
const { id, title, description, prompt, inputVariables, localVariables } = ctx.query;
|
||||
const promptNode = await PromptNeo.first('id', id);
|
||||
|
||||
if (!promptNode) {
|
||||
const promptData = {
|
||||
id: v4(),
|
||||
title,
|
||||
description,
|
||||
prompt,
|
||||
inputVariables: JSON.stringify(inputVariables),
|
||||
localVariables: JSON.stringify(localVariables),
|
||||
};
|
||||
const _prompt = await PromptNeo.create(promptData);
|
||||
ctx.body = await _prompt.toJson();
|
||||
return;
|
||||
}
|
||||
|
||||
await promptNode.update({ title, description, prompt, inputVariables, localVariables });
|
||||
ctx.body = await promptNode.toJson();
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route('prompt-graph', 'delete')
|
||||
.define(async (ctx) => {
|
||||
const { id, title } = ctx.query;
|
||||
const promptNode = await PromptNeo.first('id', id);
|
||||
if (!promptNode) {
|
||||
ctx.body = 'prompt not found';
|
||||
return;
|
||||
}
|
||||
await promptNode.delete();
|
||||
ctx.body = 'delete success';
|
||||
})
|
||||
.addTo(app);
|
||||
app
|
||||
.route('prompt-graph', 'deleteAll')
|
||||
.define(async (ctx) => {
|
||||
const prompts = await PromptNeo.all();
|
||||
for (const prompt of prompts) {
|
||||
await prompt.delete();
|
||||
}
|
||||
ctx.body = 'delete all success';
|
||||
})
|
||||
.addTo(app);
|
||||
app
|
||||
.route('prompt-graph', 'createDemo')
|
||||
.define(async (ctx) => {
|
||||
const promptData = {
|
||||
id: v4(),
|
||||
title: 'test-' + v4(),
|
||||
description: '这是测试保存prompt的数据',
|
||||
prompt: '这是测试保存prompt的数据',
|
||||
inputVariables: JSON.stringify([{ key: 'test', value: 'test' }]),
|
||||
localVariables: JSON.stringify([{ key: 'test', value: 'test' }]),
|
||||
};
|
||||
const f = await PromptNeo.first('id', 'f5288cdb-bfca-4a65-b629-cae590ede719');
|
||||
if (!f) {
|
||||
ctx.body = 'not found f';
|
||||
return;
|
||||
}
|
||||
const prompt = await PromptNeo.create({ ...promptData });
|
||||
// await prompt.relateTo(f, 'RELATED_TO', { createdAt: new Date().toISOString() });
|
||||
// f.relateTo(prompt, 'RELATED_TO', { createdAt: new Date().toISOString() });
|
||||
// await createRelationship(f, prompt);
|
||||
const fj = await f.toJson() as any;
|
||||
const pj = await prompt.toJson() as any;
|
||||
|
||||
await createRelationship2(fj.id, pj.id);
|
||||
ctx.body = await prompt.toJson();
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route('prompt-graph', 'getD3')
|
||||
.define(async (ctx) => {
|
||||
const value = await fetchData();
|
||||
ctx.body = value;
|
||||
})
|
||||
.addTo(app);
|
||||
@@ -1,63 +0,0 @@
|
||||
import { Prompt } from '@/models/prompt.ts';
|
||||
|
||||
import { app } from '@/app.ts';
|
||||
import { CustomError } from '@kevisual/router';
|
||||
|
||||
app
|
||||
.route('prompt', 'list')
|
||||
.define(async (ctx) => {
|
||||
const prompts = await Prompt.findAll({
|
||||
order: [['updatedAt', 'DESC']],
|
||||
});
|
||||
ctx.body = prompts;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route('prompt', 'update')
|
||||
.define(async (ctx) => {
|
||||
const { id, title, description, presetData, key } = ctx.query.data || {};
|
||||
if (!key) {
|
||||
throw new CustomError('Prompt key is required');
|
||||
}
|
||||
const isEdit = !!id;
|
||||
const promptKey = await Prompt.findOne({ where: { key } });
|
||||
if (promptKey && promptKey.id !== id) {
|
||||
throw new CustomError(`Prompt key is already exist, use by ${promptKey.id}`);
|
||||
}
|
||||
if (!isEdit) {
|
||||
const prompt = new Prompt({
|
||||
title,
|
||||
key,
|
||||
description,
|
||||
presetData,
|
||||
});
|
||||
await prompt.save();
|
||||
ctx.body = prompt;
|
||||
return;
|
||||
}
|
||||
|
||||
const prompt = await Prompt.findByPk(id);
|
||||
if (!prompt) {
|
||||
throw new CustomError('Prompt not found');
|
||||
}
|
||||
await prompt.update({ title, description, presetData, key });
|
||||
ctx.body = prompt;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route('prompt', 'delete')
|
||||
.define(async (ctx) => {
|
||||
const { id } = ctx.query || {};
|
||||
if (!id) {
|
||||
throw new CustomError('Prompt id is required');
|
||||
}
|
||||
const prompt = await Prompt.findByPk(id);
|
||||
if (!prompt) {
|
||||
throw new CustomError('Prompt not found');
|
||||
}
|
||||
await prompt.destroy();
|
||||
ctx.body = 'delete success';
|
||||
})
|
||||
.addTo(app);
|
||||
@@ -1 +0,0 @@
|
||||
import './list.ts'
|
||||
@@ -1,13 +0,0 @@
|
||||
import { Snippet } from '@/routes/snippet/snippet.ts';
|
||||
import { app } from '@/app.ts';
|
||||
|
||||
app
|
||||
.route({
|
||||
path: 'snippet',
|
||||
key: 'list',
|
||||
middleware: ['auth'],
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
// 获取所有的snippet
|
||||
})
|
||||
.addTo(app);
|
||||
@@ -1,54 +0,0 @@
|
||||
import { sequelize } from '@/modules/sequelize.ts';
|
||||
import { DataTypes, Model } from 'sequelize';
|
||||
|
||||
export class Snippet extends Model {
|
||||
declare id: string;
|
||||
declare title: string;
|
||||
declare description: string;
|
||||
declare snippet: string;
|
||||
declare keyword: string;
|
||||
declare user_id: string;
|
||||
declare data: any;
|
||||
}
|
||||
|
||||
Snippet.init(
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.UUID,
|
||||
primaryKey: true,
|
||||
defaultValue: DataTypes.UUIDV4,
|
||||
},
|
||||
title: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: true,
|
||||
},
|
||||
description: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: true,
|
||||
},
|
||||
snippet: {
|
||||
type: DataTypes.TEXT,
|
||||
allowNull: true,
|
||||
},
|
||||
keyword: {
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
user_id: {
|
||||
type: DataTypes.UUID,
|
||||
},
|
||||
data: {
|
||||
type: DataTypes.JSONB,
|
||||
allowNull: true,
|
||||
defaultValue: {},
|
||||
},
|
||||
},
|
||||
{
|
||||
sequelize,
|
||||
tableName: 'snippet',
|
||||
paranoid: true,
|
||||
},
|
||||
);
|
||||
// 当
|
||||
// Snippet.sync({ alter: true, logging: false }).catch((e) => {
|
||||
// console.error('Snippet sync error', e);
|
||||
// });
|
||||
Reference in New Issue
Block a user