@@ -23,7 +23,7 @@ import { useAlert } from 'cozy-ui/transpiled/react/providers/Alert'
2323
2424import { SUMMARY_SYSTEM_PROMPT , getSummaryUserPrompt } from './prompts'
2525import styles from './styles.styl'
26- import { roughTokensEstimation } from '../../helpers'
26+ import { roughTokensEstimation , isTextFile } from '../../helpers'
2727import { useViewer } from '../../providers/ViewerProvider'
2828
2929const AIAssistantPanel = ( { className } ) => {
@@ -49,25 +49,36 @@ const AIAssistantPanel = ({ className }) => {
4949 }
5050 }
5151
52+ const extractFileContent = async ( client , fileBlob , file ) => {
53+ if ( isTextFile ( file . mime ) ) {
54+ return await fileBlob . text ( )
55+ }
56+
57+ const rawTextContent = await extractText ( client , fileBlob , {
58+ name : file . name ,
59+ mime : file . mime
60+ } )
61+ return rawTextContent ? JSON . stringify ( rawTextContent ) : ''
62+ }
63+
64+ const validateContentSize = textContent => {
65+ const summaryConfig = flag ( 'drive.summary' )
66+ if (
67+ summaryConfig ?. maxTokens &&
68+ roughTokensEstimation ( textContent ) > summaryConfig . maxTokens
69+ ) {
70+ const error = new Error ( 'DOCUMENT_TOO_LARGE' )
71+ error . code = 'DOCUMENT_TOO_LARGE'
72+ throw error
73+ }
74+ }
75+
5276 const summarizeFile = async ( { client, file, stream = false , model } ) => {
5377 try {
5478 const fileBlob = await fetchBlobFileById ( client , file ?. _id )
79+ const textContent = await extractFileContent ( client , fileBlob , file )
5580
56- const rawTextContent = await extractText ( client , fileBlob , {
57- name : file . name ,
58- mime : file . mime
59- } )
60- const textContent = rawTextContent ? JSON . stringify ( rawTextContent ) : ''
61-
62- const summaryConfig = flag ( 'drive.summary' )
63- if (
64- summaryConfig ?. maxTokens &&
65- roughTokensEstimation ( textContent ) > summaryConfig . maxTokens
66- ) {
67- const error = new Error ( 'DOCUMENT_TOO_LARGE' )
68- error . code = 'DOCUMENT_TOO_LARGE'
69- throw error
70- }
81+ validateContentSize ( textContent )
7182
7283 const messages = [
7384 { role : 'system' , content : SUMMARY_SYSTEM_PROMPT } ,
0 commit comments