11 Commits

Author SHA1 Message Date
a5ed4076b7 Handle anthropic multiple responses better.
All checks were successful
Publish Library / Build NPM Project (push) Successful in 34s
Publish Library / Tag Version (push) Successful in 8s
2025-12-16 12:22:14 -05:00
0112c92505 Removed log statements
All checks were successful
Publish Library / Build NPM Project (push) Successful in 20s
Publish Library / Tag Version (push) Successful in 5s
2025-12-14 21:16:39 -05:00
2351f590b5 Removed ASR file intermediary
All checks were successful
Publish Library / Build NPM Project (push) Successful in 37s
Publish Library / Tag Version (push) Successful in 8s
2025-12-14 09:27:07 -05:00
2c2acef84e ASR logging
All checks were successful
Publish Library / Build NPM Project (push) Successful in 37s
Publish Library / Tag Version (push) Successful in 8s
2025-12-14 08:49:02 -05:00
a6de121551 Fixed ASR command
All checks were successful
Publish Library / Build NPM Project (push) Successful in 26s
Publish Library / Tag Version (push) Successful in 7s
2025-12-13 23:19:30 -05:00
31d9ee4390 ASR Debugging
All checks were successful
Publish Library / Build NPM Project (push) Successful in 43s
Publish Library / Tag Version (push) Successful in 17s
2025-12-13 22:59:23 -05:00
d69bea3b38 Fixed ASR whisper models
All checks were successful
Publish Library / Build NPM Project (push) Successful in 30s
Publish Library / Tag Version (push) Successful in 7s
2025-12-13 22:47:35 -05:00
af4b09173c ASR debugging
All checks were successful
Publish Library / Build NPM Project (push) Successful in 30s
Publish Library / Tag Version (push) Successful in 7s
2025-12-13 22:31:54 -05:00
904cc10639 bump
All checks were successful
Publish Library / Build NPM Project (push) Successful in 51s
Publish Library / Tag Version (push) Successful in 7s
2025-12-13 22:05:03 -05:00
07f9593b6a ASR debugging
All checks were successful
Publish Library / Build NPM Project (push) Successful in 29s
Publish Library / Tag Version (push) Successful in 7s
2025-12-13 22:02:13 -05:00
af42506174 ASR fixes
All checks were successful
Publish Library / Build NPM Project (push) Successful in 29s
Publish Library / Tag Version (push) Successful in 7s
2025-12-13 20:48:36 -05:00
3 changed files with 59 additions and 39 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "@ztimson/ai-utils",
"version": "0.1.6",
"version": "0.1.16",
"description": "AI Utility library",
"author": "Zak Timson",
"license": "MIT",

View File

@@ -1,25 +1,23 @@
import {$} from '@ztimson/node-utils';
import {createWorker} from 'tesseract.js';
import {LLM, LLMOptions} from './llm';
import fs from 'node:fs/promises';
import Path from 'node:path';
import * as tf from '@tensorflow/tfjs';
import {spawn} from 'node:child_process';
export type AiOptions = LLMOptions & {
whisper?: {
/** Whisper binary location */
binary: string;
/** Model */
model: WhisperModel;
/** Working directory for models and temporary files */
/** Model: `ggml-base.en.bin` */
model: string;
/** Path to models */
path: string;
}
}
export type WhisperModel = 'tiny' | 'base' | 'small' | 'medium' | 'large';
export class Ai {
private downloads: {[key: string]: Promise<void>} = {};
private downloads: {[key: string]: Promise<string>} = {};
private whisperModel!: string;
/** Large Language Models */
@@ -27,7 +25,10 @@ export class Ai {
constructor(public readonly options: AiOptions) {
this.llm = new LLM(this, options);
if(this.options.whisper?.binary) this.downloadAsrModel(this.options.whisper.model);
if(this.options.whisper?.binary) {
this.whisperModel = this.options.whisper?.model.endsWith('.bin') ? this.options.whisper?.model : this.options.whisper?.model + '.bin';
this.downloadAsrModel();
}
}
/**
@@ -36,32 +37,43 @@ export class Ai {
* @param model Whisper model
* @returns {Promise<any>} Extracted text
*/
async asr(path: string, model?: WhisperModel): Promise<string | null> {
asr(path: string, model: string = this.whisperModel): {abort: () => void, response: Promise<string | null>} {
if(!this.options.whisper?.binary) throw new Error('Whisper not configured');
if(!model) model = this.options.whisper.model;
await this.downloadAsrModel(<string>model);
const name = Math.random().toString(36).substring(2, 10) + '-' + path.split('/').pop();
const output = Path.join(this.options.whisper.path || '/tmp', name);
await $`rm -f /tmp/${name}.txt && ${this.options.whisper.binary} -nt -np -m ${this.whisperModel} -f ${path} -otxt -of ${output}`;
return fs.readFile(output, 'utf-8').then(text => text?.trim() || null)
.finally(() => fs.rm(output, {force: true}).catch(() => {}));
let abort: any = () => {};
const response = new Promise<string | null>((resolve, reject) => {
this.downloadAsrModel(model).then(m => {
let output = '';
const proc = spawn(<string>this.options.whisper?.binary, ['-nt', '-np', '-m', m, '-f', path], {stdio: ['ignore', 'pipe', 'ignore']});
abort = () => proc.kill('SIGTERM');
proc.on('error', (err: Error) => reject(err));
proc.stdout.on('data', (data: Buffer) => output += data.toString());
proc.on('close', (code: number) => {
if(code === 0) resolve(output.trim() || null);
else reject(new Error(`Exit code ${code}`));
});
});
});
return {response, abort};
}
/**
* Downloads the specified Whisper model if it is not already present locally.
*
* @param {string} model Whisper model that will be downloaded
* @return {Promise<void>} A promise that resolves once the model is downloaded and saved locally.
* @return {Promise<string>} Absolute path to model file, resolves once downloaded
*/
async downloadAsrModel(model: string): Promise<void> {
async downloadAsrModel(model: string = this.whisperModel): Promise<string> {
if(!this.options.whisper?.binary) throw new Error('Whisper not configured');
this.whisperModel = Path.join(<string>this.options.whisper?.path, this.options.whisper?.model + '.bin');
if(await fs.stat(this.whisperModel).then(() => true).catch(() => false)) return;
if(!model.endsWith('.bin')) model += '.bin';
const p = Path.join(this.options.whisper.path, model);
if(await fs.stat(p).then(() => true).catch(() => false)) return p;
if(!!this.downloads[model]) return this.downloads[model];
this.downloads[model] = fetch(`https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${this.options.whisper?.model}.bin`)
.then(resp => resp.arrayBuffer()).then(arr => Buffer.from(arr)).then(async buffer => {
await fs.writeFile(this.whisperModel, buffer);
this.downloads[model] = fetch(`https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${model}`)
.then(resp => resp.arrayBuffer())
.then(arr => Buffer.from(arr)).then(async buffer => {
await fs.writeFile(p, buffer);
delete this.downloads[model];
return p;
});
return this.downloads[model];
}

View File

@@ -13,24 +13,29 @@ export class Anthropic extends LLMProvider {
}
private toStandard(history: any[]): LLMMessage[] {
const merged: any[] = [];
for(let i = 0; i < history.length; i++) {
const orgI = i;
if(typeof history[orgI].content != 'string') {
if(history[orgI].role == 'assistant') {
history[orgI].content.filter((c: any) => c.type =='tool_use').forEach((c: any) => {
i++;
history.splice(i, 0, {role: 'tool', id: c.id, name: c.name, args: c.input});
const msg = history[i];
if(typeof msg.content != 'string') {
if(msg.role == 'assistant') {
msg.content.filter((c: any) => c.type == 'tool_use').forEach((c: any) => {
merged.push({role: 'tool', id: c.id, name: c.name, args: c.input});
});
} else if(history[orgI].role == 'user') {
history[orgI].content.filter((c: any) => c.type =='tool_result').forEach((c: any) => {
const h = history.find((h: any) => h.id == c.tool_use_id);
h[c.is_error ? 'error' : 'content'] = c.content;
} else if(msg.role == 'user') {
msg.content.filter((c: any) => c.type == 'tool_result').forEach((c: any) => {
const h = merged.find((h: any) => h.id == c.tool_use_id);
if(h) h[c.is_error ? 'error' : 'content'] = c.content;
});
}
history[orgI].content = history[orgI].content.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\n\n');
msg.content = msg.content.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\n\n');
}
if(msg.content) {
const last = merged.at(-1);
if(last && last.role == 'assistant' && msg.role == 'assistant') last.content += '\n\n' + msg.content;
else merged.push({role: msg.role, content: msg.content});
}
}
return history.filter(h => !!h.content);
return merged;
}
private fromStandard(history: LLMMessage[]): any[] {
@@ -71,13 +76,15 @@ export class Anthropic extends LLMProvider {
stream: !!options.stream,
};
// Run tool changes
let resp: any;
let isFirstMessage = true;
do {
resp = await this.client.messages.create(requestParams);
// Streaming mode
if(options.stream) {
if(!isFirstMessage) options.stream({text: '\n\n'});
isFirstMessage = false;
resp.content = [];
for await (const chunk of resp) {
if(controller.signal.aborted) break;
@@ -104,7 +111,6 @@ export class Anthropic extends LLMProvider {
}
}
// Run tools
const toolCalls = resp.content.filter((c: any) => c.type === 'tool_use');
if(toolCalls.length && !controller.signal.aborted) {
history.push({role: 'assistant', content: resp.content});
@@ -122,12 +128,14 @@ export class Anthropic extends LLMProvider {
requestParams.messages = history;
}
} while (!controller.signal.aborted && resp.content.some((c: any) => c.type === 'tool_use'));
if(options.stream) options.stream({done: true});
res(this.toStandard([...history, {
role: 'assistant',
content: resp.content.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\n\n')
}]));
});
return Object.assign(response, {abort: () => controller.abort()});
}
}