2025-02-04 17:15:39 +03:00
|
|
|
import { DataStreamWriter, tool } from 'ai';
|
2025-01-23 01:19:48 +05:30
|
|
|
import { Session } from 'next-auth';
|
|
|
|
|
import { z } from 'zod';
|
|
|
|
|
import { getDocumentById, saveDocument } from '@/lib/db/queries';
|
2025-02-13 08:25:57 -08:00
|
|
|
import { documentHandlersByArtifactKind } from '@/lib/artifacts/server';
|
2025-01-23 01:19:48 +05:30
|
|
|
|
|
|
|
|
interface UpdateDocumentProps {
|
|
|
|
|
session: Session;
|
|
|
|
|
dataStream: DataStreamWriter;
|
|
|
|
|
}
|
|
|
|
|
|
2025-02-03 20:33:15 +05:30
|
|
|
export const updateDocument = ({ session, dataStream }: UpdateDocumentProps) =>
|
2025-01-23 01:19:48 +05:30
|
|
|
tool({
|
|
|
|
|
description: 'Update a document with the given description.',
|
|
|
|
|
parameters: z.object({
|
|
|
|
|
id: z.string().describe('The ID of the document to update'),
|
|
|
|
|
description: z
|
|
|
|
|
.string()
|
|
|
|
|
.describe('The description of changes that need to be made'),
|
|
|
|
|
}),
|
|
|
|
|
execute: async ({ id, description }) => {
|
|
|
|
|
const document = await getDocumentById({ id });
|
|
|
|
|
|
|
|
|
|
if (!document) {
|
|
|
|
|
return {
|
|
|
|
|
error: 'Document not found',
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
dataStream.writeData({
|
|
|
|
|
type: 'clear',
|
|
|
|
|
content: document.title,
|
|
|
|
|
});
|
|
|
|
|
|
2025-02-13 08:25:57 -08:00
|
|
|
const documentHandler = documentHandlersByArtifactKind.find(
|
|
|
|
|
(documentHandlerByArtifactKind) =>
|
|
|
|
|
documentHandlerByArtifactKind.kind === document.kind,
|
2025-02-04 17:15:39 +03:00
|
|
|
);
|
2025-01-23 01:19:48 +05:30
|
|
|
|
2025-02-04 17:15:39 +03:00
|
|
|
if (!documentHandler) {
|
|
|
|
|
throw new Error(`No document handler found for kind: ${document.kind}`);
|
2025-01-23 01:19:48 +05:30
|
|
|
}
|
|
|
|
|
|
2025-02-04 17:15:39 +03:00
|
|
|
await documentHandler.onUpdateDocument({
|
|
|
|
|
document,
|
|
|
|
|
description,
|
|
|
|
|
dataStream,
|
|
|
|
|
session,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
dataStream.writeData({ type: 'finish', content: '' });
|
2025-01-23 01:19:48 +05:30
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
id,
|
|
|
|
|
title: document.title,
|
|
|
|
|
kind: document.kind,
|
|
|
|
|
content: 'The document has been updated successfully.',
|
|
|
|
|
};
|
|
|
|
|
},
|
|
|
|
|
});
|