2025-01-23 01:19:48 +05:30
import { generateUUID } from '@/lib/utils' ;
2025-02-04 17:15:39 +03:00
import { DataStreamWriter , tool } from 'ai' ;
2025-01-23 01:19:48 +05:30
import { z } from 'zod' ;
import { Session } from 'next-auth' ;
2025-02-13 08:25:57 -08:00
import {
artifactKinds ,
documentHandlersByArtifactKind ,
} from '@/lib/artifacts/server' ;
2025-01-23 01:19:48 +05:30
interface CreateDocumentProps {
session : Session ;
dataStream : DataStreamWriter ;
}
2025-02-03 20:33:15 +05:30
export const createDocument = ( { session , dataStream } : CreateDocumentProps ) = >
2025-01-23 01:19:48 +05:30
tool ( {
description :
2025-02-03 13:33:48 +05:30
'Create a document for a writing or content creation activities. This tool will call other functions that will generate the contents of the document based on the title and kind.' ,
2025-01-23 01:19:48 +05:30
parameters : z.object ( {
title : z.string ( ) ,
2025-02-13 08:25:57 -08:00
kind : z.enum ( artifactKinds ) ,
2025-01-23 01:19:48 +05:30
} ) ,
execute : async ( { title , kind } ) = > {
const id = generateUUID ( ) ;
2025-02-04 17:15:39 +03:00
dataStream . writeData ( {
type : 'kind' ,
content : kind ,
} ) ;
2025-01-23 01:19:48 +05:30
dataStream . writeData ( {
type : 'id' ,
content : id ,
} ) ;
dataStream . writeData ( {
type : 'title' ,
content : title ,
} ) ;
dataStream . writeData ( {
type : 'clear' ,
content : '' ,
} ) ;
2025-02-13 08:25:57 -08:00
const documentHandler = documentHandlersByArtifactKind . find (
( documentHandlerByArtifactKind ) = >
documentHandlerByArtifactKind . kind === 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: ${ kind } ` ) ;
2025-01-23 01:19:48 +05:30
}
2025-02-04 17:15:39 +03:00
await documentHandler . onCreateDocument ( {
id ,
title ,
dataStream ,
session ,
} ) ;
dataStream . writeData ( { type : 'finish' , content : '' } ) ;
2025-01-23 01:19:48 +05:30
return {
id ,
title ,
kind ,
content : 'A document was created and is now visible to the user.' ,
} ;
} ,
} ) ;