2025-01-23 01:19:48 +05:30
import { generateUUID } from '@/lib/utils' ;
2025-07-03 02:26:34 -07:00
import { tool , type UIMessageStreamWriter } from 'ai' ;
2025-01-23 01:19:48 +05:30
import { z } from 'zod' ;
2025-07-03 02:26:34 -07:00
import type { Session } from 'next-auth' ;
2025-02-13 08:25:57 -08:00
import {
artifactKinds ,
documentHandlersByArtifactKind ,
} from '@/lib/artifacts/server' ;
2025-07-03 02:26:34 -07:00
import type { ChatMessage } from '@/lib/types' ;
2025-01-23 01:19:48 +05:30
interface CreateDocumentProps {
session : Session ;
2025-07-03 02:26:34 -07:00
dataStream : UIMessageStreamWriter < ChatMessage > ;
2025-01-23 01:19:48 +05:30
}
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-07-03 02:26:34 -07:00
inputSchema : z.object ( {
2025-01-23 01:19:48 +05:30
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
2025-07-03 02:26:34 -07:00
dataStream . write ( {
type : 'data-kind' ,
data : kind ,
transient : true ,
2025-02-04 17:15:39 +03:00
} ) ;
2025-01-23 01:19:48 +05:30
2025-07-03 02:26:34 -07:00
dataStream . write ( {
type : 'data-id' ,
data : id ,
transient : true ,
2025-01-23 01:19:48 +05:30
} ) ;
2025-07-03 02:26:34 -07:00
dataStream . write ( {
type : 'data-title' ,
data : title ,
transient : true ,
2025-01-23 01:19:48 +05:30
} ) ;
2025-07-03 02:26:34 -07:00
dataStream . write ( {
type : 'data-clear' ,
data : null ,
transient : true ,
2025-01-23 01:19:48 +05:30
} ) ;
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 ,
} ) ;
2025-07-03 02:26:34 -07:00
dataStream . write ( { type : 'data-finish' , data : null , transient : true } ) ;
2025-01-23 01:19:48 +05:30
return {
id ,
title ,
kind ,
content : 'A document was created and is now visible to the user.' ,
} ;
} ,
} ) ;