Added official file support
This commit is contained in:
155
src/llm.ts
155
src/llm.ts
@@ -5,11 +5,16 @@ import {OpenAi} from './open-ai.ts';
|
||||
import {LLMProvider} from './provider.ts';
|
||||
import {AiTool, AiToolArg} from './tools.ts';
|
||||
import {fileURLToPath} from 'url';
|
||||
import {dirname, join} from 'path';
|
||||
import {spawn} from 'node:child_process';
|
||||
import {Memory, MemoryCache, MemoryManager, MemoryOptions, stripHeader} from './memory.ts';
|
||||
import {mkdtempSync} from 'node:fs';
|
||||
import fs from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {dirname, join, basename, extname} from 'path';
|
||||
import { PDFParse } from 'pdf-parse';
|
||||
|
||||
const MAX_AGENT_DEPTH = 5;
|
||||
const PDF_OCR_PAGE_THRESHOLD = 12; // above this many pages, OCR scanned pages instead of feeding images to the model
|
||||
|
||||
export type AnthropicConfig = {proto: 'anthropic', token: string | string[]};
|
||||
export type OpenAiConfig = {proto: 'openai', host?: string, token: string | string[]};
|
||||
@@ -27,6 +32,19 @@ export type Agent = {
|
||||
agents?: string[] | null;
|
||||
}
|
||||
|
||||
export type LLMFile = {
|
||||
/** Path to file on disk */
|
||||
path?: string;
|
||||
/** File content: raw text, base64-encoded binary, or a Buffer */
|
||||
content?: string | Buffer;
|
||||
/** Original filename, used to infer type from extension */
|
||||
name?: string;
|
||||
/** Mime type override, inferred from extension if omitted */
|
||||
mime?: string;
|
||||
/** @internal set once extraction has run, skips re-processing next turn */
|
||||
extracted?: boolean;
|
||||
};
|
||||
|
||||
export type LLMMessage = {
|
||||
/** Message originator */
|
||||
role: 'assistant' | 'system' | 'user';
|
||||
@@ -88,6 +106,8 @@ export type LLMRequest = {
|
||||
mcp?: McpServer[];
|
||||
/** Subagents exposed as delegatable/wrapped tools */
|
||||
agents?: Agent[];
|
||||
/** Attach files to request */
|
||||
files?: LLMFile[];
|
||||
/** @internal recursion guard for nested agent delegation */
|
||||
_agentDepth?: number;
|
||||
}
|
||||
@@ -111,6 +131,11 @@ export type Skill = {
|
||||
}
|
||||
|
||||
class LLM {
|
||||
private static AUDIO_EXT = ['wav','mp3','m4a','flac','ogg','aac','wma'];
|
||||
private static IMAGE_EXT = ['png','jpg','jpeg','bmp','gif','tiff','webp'];
|
||||
private static TEXT_EXT = ['txt','md','csv','json','xml','html','js','ts','py','yaml','yml','log'];
|
||||
private static PDF_EXT = ['pdf'];
|
||||
|
||||
private memoryManager!: MemoryManager;
|
||||
|
||||
defaultModel!: string;
|
||||
@@ -126,6 +151,120 @@ class LLM {
|
||||
this.memoryManager = new MemoryManager(this);
|
||||
}
|
||||
|
||||
private async loadBuffer(file: LLMFile, asText: boolean): Promise<Buffer> {
|
||||
if(file.path) return fs.readFile(file.path);
|
||||
if(Buffer.isBuffer(file.content)) return file.content;
|
||||
if(typeof file.content === 'string') return Buffer.from(file.content, asText ? 'utf-8' : 'base64');
|
||||
throw new Error('No path or content provided');
|
||||
}
|
||||
|
||||
private async writeTemp(name: string, buffer: Buffer): Promise<string> {
|
||||
const path = join(mkdtempSync(join(tmpdir(), 'ai-file-')), name);
|
||||
await fs.writeFile(path, buffer);
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract text from a PDF. Pages with no text layer (scanned/image-only) are handled as either:
|
||||
* - Rendered to images and returned alongside the text so the (vision-capable) model can read them directly
|
||||
* - OCR'd via Tesseract when the doc is too large to reasonably pass as images
|
||||
*/
|
||||
private async resolvePdf(buffer: Buffer): Promise<{text: string, images: {mime: string, data: string}[]}> {
|
||||
const parser = new PDFParse({data: buffer});
|
||||
try {
|
||||
const {text, pages} = await parser.getText();
|
||||
const scanned = (pages || []).filter(p => !p.text?.trim());
|
||||
if(!scanned.length) return {text: text.trim() || '[Empty PDF]', images: []};
|
||||
const total = pages.length;
|
||||
const pageNums = scanned.map(p => p.num);
|
||||
const {pages: shots} = await parser.getScreenshot({partial: pageNums});
|
||||
if(total <= PDF_OCR_PAGE_THRESHOLD) {
|
||||
return {
|
||||
text: text.trim(),
|
||||
images: shots.map(s => ({mime: 'image/png', data: Buffer.from(s.data).toString('base64')}))
|
||||
};
|
||||
}
|
||||
const ocrText = await Promise.all(shots.map(async (s, i) => {
|
||||
const path = await this.writeTemp(`page-${pageNums[i]}.png`, Buffer.from(s.data));
|
||||
try {
|
||||
return await this.ai.vision.ocr(path) || '';
|
||||
} finally {
|
||||
fs.rm(dirname(path), {recursive: true, force: true}).catch(() => {});
|
||||
}
|
||||
}));
|
||||
return {text: [text.trim(), ...ocrText].filter(Boolean).join('\n\n'), images: []};
|
||||
} finally {
|
||||
await parser.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveFile(file: LLMFile): Promise<{text?: string, images?: {mime: string, data: string}[]}> {
|
||||
const name = file.name || (file.path ? basename(file.path) : 'file');
|
||||
|
||||
// Already resolved on a previous turn, reuse cached text
|
||||
if(file.extracted) return {text: `<file name="${name}">\n${file.content}\n</file>`};
|
||||
|
||||
const ext = extname(name).slice(1).toLowerCase();
|
||||
const mime = file.mime || '';
|
||||
const isAudio = mime.startsWith('audio/') || LLM.AUDIO_EXT.includes(ext);
|
||||
const isImage = mime.startsWith('image/') || LLM.IMAGE_EXT.includes(ext);
|
||||
const isPdf = mime === 'application/pdf' || LLM.PDF_EXT.includes(ext);
|
||||
const isText = mime.startsWith('text/') || LLM.TEXT_EXT.includes(ext);
|
||||
|
||||
let tmpDir: string | null = null;
|
||||
try {
|
||||
if(isImage) {
|
||||
const data = (await this.loadBuffer(file, false)).toString('base64');
|
||||
return {images: [{mime: mime || `image/${ext === 'jpg' ? 'jpeg' : ext}`, data}]};
|
||||
}
|
||||
|
||||
if(isPdf) {
|
||||
const {text, images} = await this.resolvePdf(await this.loadBuffer(file, false));
|
||||
// Only cache/skip re-processing when we didn't need to hand off images (OCR'd or fully text-based)
|
||||
if(!images.length) {
|
||||
file.content = text;
|
||||
file.extracted = true;
|
||||
delete file.path;
|
||||
}
|
||||
return {text: `<file name="${name}">\n${text || '[Scanned PDF - see attached page images]'}\n</file>`, images};
|
||||
}
|
||||
|
||||
let text: string;
|
||||
if(isAudio) {
|
||||
let path = file.path;
|
||||
if(!path) {
|
||||
const buffer = await this.loadBuffer(file, false);
|
||||
path = await this.writeTemp(name, buffer);
|
||||
tmpDir = dirname(path);
|
||||
}
|
||||
text = await this.ai.audio.asr(path) || '';
|
||||
} else if(isText) {
|
||||
text = (await this.loadBuffer(file, true)).toString('utf-8');
|
||||
} else {
|
||||
text = `Unsupported file type: ${ext || mime}`;
|
||||
}
|
||||
|
||||
// Cache result, skip re-extraction on future turns of the same conversation
|
||||
file.content = text;
|
||||
file.extracted = true;
|
||||
delete file.path;
|
||||
|
||||
return {text: `<file name="${name}">\n${text}\n</file>`};
|
||||
} catch(err: any) {
|
||||
return {text: `<file name="${name}">Failed to process: ${err.message}</file>`};
|
||||
} finally {
|
||||
if(tmpDir) fs.rm(tmpDir, {recursive: true, force: true}).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveFiles(files: LLMFile[]): Promise<{text: string, images: {mime: string, data: string}[]}> {
|
||||
const resolved = await Promise.all(files.map(f => this.resolveFile(f)));
|
||||
return {
|
||||
text: resolved.filter(r => r.text).map(r => r.text).join('\n\n'),
|
||||
images: resolved.flatMap(r => r.images || [])
|
||||
};
|
||||
}
|
||||
|
||||
private setupAgent(agents: Agent[] = [], allAgents: Agent[], history: LLMMessage[], aborts: (() => void)[], depth = 0, delegateState: {resp: string | null}): AiTool[] {
|
||||
return agents.map(a => {
|
||||
const toolName = `${a.delegate ? '' : 'sub'}agent_${snakeCase(a.name)}`;
|
||||
@@ -343,6 +482,18 @@ Linked: ${makeUnique([...r.links, ...r.backlinks]).join(', ')}
|
||||
|
||||
if(aborted) throw Object.assign(new Error('Aborted'), {name: 'AbortError'});
|
||||
|
||||
// Files
|
||||
const files = options.files || [];
|
||||
const lastMsg = history[history.length - 1];
|
||||
const originalContent = lastMsg?.content;
|
||||
if(files.length && lastMsg?.role === 'user') {
|
||||
const {text, images} = await this.resolveFiles(files);
|
||||
const merged = text ? `${originalContent}\n\n${text}` : originalContent;
|
||||
lastMsg.content = images.length
|
||||
? [...images.map(i => ({type: 'image', mime: i.mime, data: i.data})), {type: 'text', text: merged}]
|
||||
: merged;
|
||||
}
|
||||
|
||||
const toolTimings = new Map<string, {duration: number, tps: number}>();
|
||||
tools = this.wrapToolTiming(tools, toolTimings);
|
||||
|
||||
@@ -352,6 +503,8 @@ Linked: ${makeUnique([...r.links, ...r.backlinks]).join(', ')}
|
||||
request = this.models[m].ask('', {...options, tools, system: prompts.filter(Boolean).join('\n\n')});
|
||||
let resp = await request;
|
||||
|
||||
if(files.length && lastMsg?.role === 'user') lastMsg.content = originalContent;
|
||||
|
||||
// Capture meta (duration / tps)
|
||||
for(const h of history) {
|
||||
if(h.role === 'tool' && toolTimings.has(h.id)) Object.assign(h, toolTimings.get(h.id));
|
||||
|
||||
Reference in New Issue
Block a user