File size: 7,699 Bytes
867b17d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
// This is a helper for an older version of ai, v4.3.13
// import { config } from 'dotenv';
// import postgres from 'postgres';
// import {
// chat,
// message,
// type MessageDeprecated,
// messageDeprecated,
// vote,
// voteDeprecated,
// } from '../schema';
// import { drizzle } from 'drizzle-orm/postgres-js';
// import { inArray } from 'drizzle-orm';
// import { appendResponseMessages, type UIMessage } from 'ai';
// config({
// path: '.env.local',
// });
// if (!process.env.POSTGRES_URL) {
// throw new Error('POSTGRES_URL environment variable is not set');
// }
// const client = postgres(process.env.POSTGRES_URL);
// const db = drizzle(client);
// const BATCH_SIZE = 100; // Process 100 chats at a time
// const INSERT_BATCH_SIZE = 1000; // Insert 1000 messages at a time
// type NewMessageInsert = {
// id: string;
// chatId: string;
// parts: any[];
// role: string;
// attachments: any[];
// createdAt: Date;
// };
// type NewVoteInsert = {
// messageId: string;
// chatId: string;
// isUpvoted: boolean;
// };
// interface MessageDeprecatedContentPart {
// type: string;
// content: unknown;
// }
// function getMessageRank(message: MessageDeprecated): number {
// if (
// message.role === 'assistant' &&
// (message.content as MessageDeprecatedContentPart[]).some(
// (contentPart) => contentPart.type === 'tool-call',
// )
// ) {
// return 0;
// }
// if (
// message.role === 'tool' &&
// (message.content as MessageDeprecatedContentPart[]).some(
// (contentPart) => contentPart.type === 'tool-result',
// )
// ) {
// return 1;
// }
// if (message.role === 'assistant') {
// return 2;
// }
// return 3;
// }
// function dedupeParts<T extends { type: string; [k: string]: any }>(
// parts: T[],
// ): T[] {
// const seen = new Set<string>();
// return parts.filter((p) => {
// const key = `${p.type}|${JSON.stringify(p.content ?? p)}`;
// if (seen.has(key)) return false;
// seen.add(key);
// return true;
// });
// }
// function sanitizeParts<T extends { type: string; [k: string]: any }>(
// parts: T[],
// ): T[] {
// return parts.filter(
// (part) => !(part.type === 'reasoning' && part.reasoning === 'undefined'),
// );
// }
// async function migrateMessages() {
// const chats = await db.select().from(chat);
// let processedCount = 0;
// for (let i = 0; i < chats.length; i += BATCH_SIZE) {
// const chatBatch = chats.slice(i, i + BATCH_SIZE);
// const chatIds = chatBatch.map((chat) => chat.id);
// const allMessages = await db
// .select()
// .from(messageDeprecated)
// .where(inArray(messageDeprecated.chatId, chatIds));
// const allVotes = await db
// .select()
// .from(voteDeprecated)
// .where(inArray(voteDeprecated.chatId, chatIds));
// const newMessagesToInsert: NewMessageInsert[] = [];
// const newVotesToInsert: NewVoteInsert[] = [];
// for (const chat of chatBatch) {
// processedCount++;
// console.info(`Processed ${processedCount}/${chats.length} chats`);
// const messages = allMessages
// .filter((message) => message.chatId === chat.id)
// .sort((a, b) => {
// const differenceInTime =
// new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
// if (differenceInTime !== 0) return differenceInTime;
// return getMessageRank(a) - getMessageRank(b);
// });
// const votes = allVotes.filter((v) => v.chatId === chat.id);
// const messageSection: Array<UIMessage> = [];
// const messageSections: Array<Array<UIMessage>> = [];
// for (const message of messages) {
// const { role } = message;
// if (role === 'user' && messageSection.length > 0) {
// messageSections.push([...messageSection]);
// messageSection.length = 0;
// }
// // @ts-expect-error message.content has different type
// messageSection.push(message);
// }
// if (messageSection.length > 0) {
// messageSections.push([...messageSection]);
// }
// for (const section of messageSections) {
// const [userMessage, ...assistantMessages] = section;
// const [firstAssistantMessage] = assistantMessages;
// try {
// const uiSection = appendResponseMessages({
// messages: [userMessage],
// // @ts-expect-error: message.content has different type
// responseMessages: assistantMessages,
// _internal: {
// currentDate: () => firstAssistantMessage.createdAt ?? new Date(),
// },
// });
// const projectedUISection = uiSection
// .map((message) => {
// if (message.role === 'user') {
// return {
// id: message.id,
// chatId: chat.id,
// parts: [{ type: 'text', text: message.content }],
// role: message.role,
// createdAt: message.createdAt,
// attachments: [],
// } as NewMessageInsert;
// } else if (message.role === 'assistant') {
// const cleanParts = sanitizeParts(
// dedupeParts(message.parts || []),
// );
// return {
// id: message.id,
// chatId: chat.id,
// parts: cleanParts,
// role: message.role,
// createdAt: message.createdAt,
// attachments: [],
// } as NewMessageInsert;
// }
// return null;
// })
// .filter((msg): msg is NewMessageInsert => msg !== null);
// for (const msg of projectedUISection) {
// newMessagesToInsert.push(msg);
// if (msg.role === 'assistant') {
// const voteByMessage = votes.find((v) => v.messageId === msg.id);
// if (voteByMessage) {
// newVotesToInsert.push({
// messageId: msg.id,
// chatId: msg.chatId,
// isUpvoted: voteByMessage.isUpvoted,
// });
// }
// }
// }
// } catch (error) {
// console.error(`Error processing chat ${chat.id}: ${error}`);
// }
// }
// }
// for (let j = 0; j < newMessagesToInsert.length; j += INSERT_BATCH_SIZE) {
// const messageBatch = newMessagesToInsert.slice(j, j + INSERT_BATCH_SIZE);
// if (messageBatch.length > 0) {
// const validMessageBatch = messageBatch.map((msg) => ({
// id: msg.id,
// chatId: msg.chatId,
// parts: msg.parts,
// role: msg.role,
// attachments: msg.attachments,
// createdAt: msg.createdAt,
// }));
// await db.insert(message).values(validMessageBatch);
// }
// }
// for (let j = 0; j < newVotesToInsert.length; j += INSERT_BATCH_SIZE) {
// const voteBatch = newVotesToInsert.slice(j, j + INSERT_BATCH_SIZE);
// if (voteBatch.length > 0) {
// await db.insert(vote).values(voteBatch);
// }
// }
// }
// console.info(`Migration completed: ${processedCount} chats processed`);
// }
// migrateMessages()
// .then(() => {
// console.info('Script completed successfully');
// process.exit(0);
// })
// .catch((error) => {
// console.error('Script failed:', error);
// process.exit(1);
// });
|