import{streamText as e}from"@intlayer/ai";import{readFileSync as t}from"node:fs";import{dirname as n,join as r}from"node:path";import{fileURLToPath as i}from"node:url";import{getMarkdownMetadata as a}from"@intlayer/core/markdown";import{getBlogs as o,getDocs as s,getFrequentQuestions as c}from"@intlayer/docs";import{OpenAI as l}from"openai";const u=n(i(import.meta.url)),d=e=>{try{return JSON.parse(t(r(u,`./embeddings/${e.replace(`.md`,`.json`)}`),`utf-8`))}catch{return{}}},f=[],p=4.15;800*p,200*p;const m=process.env.SKIP_DOC_EMBEDDINGS_INDEX===`true`,h=e=>{let t=[],n=0;for(;n<e.length;){let r=Math.min(n+3320.0000000000005,e.length);if(r<e.length){let t=e.lastIndexOf(` `,r);t>n&&(r=t)}t.push(e.substring(n,r));let i=r-830.0000000000001;n=i<=n?r:i}return t},g=async e=>(await new l({apiKey:process.env.OPENAI_API_KEY}).embeddings.create({model:`text-embedding-3-large`,input:e})).data[0].embedding,_=(e,t)=>e.reduce((e,n,r)=>e+n*t[r],0)/(Math.sqrt(e.reduce((e,t)=>e+t*t,0))*Math.sqrt(t.reduce((e,t)=>e+t*t,0))),v=async()=>{let e=await c(),t=await s(),n=await o(),r={...t,...n,...e};for await(let e of Object.keys(r)){let t=a(r[e]),n=h(r[e]),i=d(e),o=Object.keys(i),s=n.length,c=o.length,l=!1;s!==c&&(console.info(`File "${e}" chunk count changed: ${c} -> ${s}. Regenerating embeddings.`),l=!m);let u={};for await(let r of Object.keys(n)){let a=Number(r)+1,o=n.length,s=n[r],c=`chunk_${a}`,d=l?void 0:i[c];u={...u,[c]:d},f.push({fileKey:e,chunkNumber:a,embedding:d,content:s,docUrl:t.url,docName:t.title}),console.info(`- Loaded: ${e}/${c}/${o}`)}}};v();const y=async(e,t=20,n=.42)=>{let r=await g(e),i=f.filter(e=>e.embedding).map(e=>({...e,similarity:_(r,e.embedding)})).filter(e=>e.similarity>n).sort((e,t)=>t.similarity-e.similarity).slice(0,t),a=new Set(i.map(e=>e.fileKey));return f.sort((e,t)=>a.has(e.fileKey)?-1:1).filter(e=>i.some(t=>t.fileKey===e.fileKey&&t.chunkNumber===e.chunkNumber))},b={role:`system`,content:t(r(u,`./PROMPT.md`),`utf-8`)},x=async(t,n,r)=>{let i=await y(t.filter(e=>e.role===`user`).map(e=>`- ${e.content}`).join(`
`)),a=[{role:`system`,content:b.content.replace(`{{relevantFilesReferences}}`,i.length===0?`Not relevant file found related to the question.`:i.map((e,t)=>[`-----`,`---`,`chunkId: ${t}`,`docChunk: "${e.chunkNumber}/${e.fileKey.length}"`,`docName: "${e.docName}"`,`docUrl: "${e.docUrl}"`,`---`,e.content,`-----`].join(`
`)).join(`

`))},...t.slice(-8)];if(!n)throw Error(`Failed to initialize AI configuration`);let o=``,s=e({...n,messages:a});for await(let e of s.textStream)o+=e,r?.onMessage?.(e);let c=[...new Set(i.map(e=>e.fileKey))];return{response:o??`Error: No result found`,relatedFiles:c}};export{x as askDocQuestion,b as initPrompt,v as loadMarkdownFiles,y as searchChunkReference};
//# sourceMappingURL=askDocQuestion.mjs.map