Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1a0351aeef | |||
| a5ed4076b7 | |||
| 0112c92505 | |||
| 2351f590b5 | |||
| 2c2acef84e | |||
| a6de121551 | |||
| 31d9ee4390 |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ztimson/ai-utils",
|
||||
"version": "0.1.10",
|
||||
"version": "0.1.18",
|
||||
"description": "AI Utility library",
|
||||
"author": "Zak Timson",
|
||||
"license": "MIT",
|
||||
|
||||
49
src/ai.ts
49
src/ai.ts
@@ -1,25 +1,21 @@
|
||||
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;
|
||||
/** Model: `ggml-base.en.bin` */
|
||||
model: string;
|
||||
/** Path to models */
|
||||
path: string;
|
||||
/** Path to storage location for temporary files */
|
||||
temp?: string;
|
||||
}
|
||||
}
|
||||
|
||||
export type WhisperModel = 'tiny' | 'base' | 'small' | 'medium' | 'large';
|
||||
|
||||
export class Ai {
|
||||
private downloads: {[key: string]: Promise<string>} = {};
|
||||
private whisperModel!: string;
|
||||
@@ -30,7 +26,7 @@ export class Ai {
|
||||
constructor(public readonly options: AiOptions) {
|
||||
this.llm = new LLM(this, options);
|
||||
if(this.options.whisper?.binary) {
|
||||
this.whisperModel = Path.join(<string>this.options.whisper?.path, this.options.whisper?.model + this.options.whisper?.model.endsWith('.bin') ? '' : '.bin');
|
||||
this.whisperModel = this.options.whisper?.model.endsWith('.bin') ? this.options.whisper?.model : this.options.whisper?.model + '.bin';
|
||||
this.downloadAsrModel();
|
||||
}
|
||||
}
|
||||
@@ -41,14 +37,23 @@ 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');
|
||||
const m = await this.downloadAsrModel(model);
|
||||
const name = Math.random().toString(36).substring(2, 10) + '-' + path.split('/').pop() + '.txt';
|
||||
const output = Path.join(this.options.whisper.temp || '/tmp', name);
|
||||
await $`rm -f ${output} && ${this.options.whisper.binary} -nt -np -m ${m} -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};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -57,20 +62,20 @@ export class Ai {
|
||||
* @param {string} model Whisper model that will be downloaded
|
||||
* @return {Promise<string>} Absolute path to model file, resolves once downloaded
|
||||
*/
|
||||
async downloadAsrModel(model?: string): Promise<string> {
|
||||
async downloadAsrModel(model: string = this.whisperModel): Promise<string> {
|
||||
if(!this.options.whisper?.binary) throw new Error('Whisper not configured');
|
||||
const m = model ? (model.endsWith('.bin') ? model : model + '.bin') : this.whisperModel.split('/').pop()!;
|
||||
const p = Path.join(this.options.whisper.path, m);
|
||||
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[m]) return this.downloads[m];
|
||||
this.downloads[m] = fetch(`https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${m}`)
|
||||
if(!!this.downloads[model]) return this.downloads[model];
|
||||
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[m];
|
||||
delete this.downloads[model];
|
||||
return p;
|
||||
});
|
||||
return this.downloads[m];
|
||||
return this.downloads[model];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -19,7 +19,7 @@ export class Anthropic extends LLMProvider {
|
||||
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});
|
||||
history.splice(i, 0, {role: 'tool', id: c.id, name: c.name, args: c.input, timestamp: Date.now()});
|
||||
});
|
||||
} else if(history[orgI].role == 'user') {
|
||||
history[orgI].content.filter((c: any) => c.type =='tool_result').forEach((c: any) => {
|
||||
@@ -29,6 +29,7 @@ export class Anthropic extends LLMProvider {
|
||||
}
|
||||
history[orgI].content = history[orgI].content.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\n\n');
|
||||
}
|
||||
if(!history[orgI].timestamp) history[orgI].timestamp = Date.now();
|
||||
}
|
||||
return history.filter(h => !!h.content);
|
||||
}
|
||||
@@ -38,8 +39,8 @@ export class Anthropic extends LLMProvider {
|
||||
if(history[i].role == 'tool') {
|
||||
const h: any = history[i];
|
||||
history.splice(i, 1,
|
||||
{role: 'assistant', content: [{type: 'tool_use', id: h.id, name: h.name, input: h.args}]},
|
||||
{role: 'user', content: [{type: 'tool_result', tool_use_id: h.id, is_error: !!h.error, content: h.error || h.content}]}
|
||||
{role: 'assistant', content: [{type: 'tool_use', id: h.id, name: h.name, input: h.args}], timestamp: h.timestamp},
|
||||
{role: 'user', content: [{type: 'tool_result', tool_use_id: h.id, is_error: !!h.error, content: h.error || h.content}], timestamp: Date.now()}
|
||||
)
|
||||
i++;
|
||||
}
|
||||
@@ -50,7 +51,7 @@ export class Anthropic extends LLMProvider {
|
||||
ask(message: string, options: LLMRequest = {}): AbortablePromise<LLMMessage[]> {
|
||||
const controller = new AbortController();
|
||||
const response = new Promise<any>(async (res, rej) => {
|
||||
let history = this.fromStandard([...options.history || [], {role: 'user', content: message}]);
|
||||
let history = this.fromStandard([...options.history || [], {role: 'user', content: message, timestamp: Date.now()}]);
|
||||
if(options.compress) history = await this.ai.llm.compress(<any>history, options.compress.max, options.compress.min, options);
|
||||
const requestParams: any = {
|
||||
model: options.model || this.model,
|
||||
@@ -71,13 +72,12 @@ export class Anthropic extends LLMProvider {
|
||||
stream: !!options.stream,
|
||||
};
|
||||
|
||||
// Run tool changes
|
||||
let resp: any;
|
||||
const loopMessages: any[] = [];
|
||||
do {
|
||||
resp = await this.client.messages.create(requestParams);
|
||||
|
||||
// Streaming mode
|
||||
if(options.stream) {
|
||||
if(loopMessages.length) options.stream({text: '\n\n'});
|
||||
resp.content = [];
|
||||
for await (const chunk of resp) {
|
||||
if(controller.signal.aborted) break;
|
||||
@@ -104,10 +104,10 @@ export class Anthropic extends LLMProvider {
|
||||
}
|
||||
}
|
||||
|
||||
// Run tools
|
||||
loopMessages.push({role: 'assistant', content: resp.content, timestamp: Date.now()});
|
||||
const toolCalls = resp.content.filter((c: any) => c.type === 'tool_use');
|
||||
if(toolCalls.length && !controller.signal.aborted) {
|
||||
history.push({role: 'assistant', content: resp.content});
|
||||
history.push({role: 'assistant', content: resp.content, timestamp: Date.now()});
|
||||
const results = await Promise.all(toolCalls.map(async (toolCall: any) => {
|
||||
const tool = options.tools?.find(findByProp('name', toolCall.name));
|
||||
if(!tool) return {tool_use_id: toolCall.id, is_error: true, content: 'Tool not found'};
|
||||
@@ -118,16 +118,20 @@ export class Anthropic extends LLMProvider {
|
||||
return {type: 'tool_result', tool_use_id: toolCall.id, is_error: true, content: err?.message || err?.toString() || 'Unknown'};
|
||||
}
|
||||
}));
|
||||
history.push({role: 'user', content: results});
|
||||
const userMsg = {role: 'user', content: results, timestamp: Date.now()};
|
||||
history.push(userMsg);
|
||||
loopMessages.push(userMsg);
|
||||
requestParams.messages = history;
|
||||
}
|
||||
} while (!controller.signal.aborted && resp.content.some((c: any) => c.type === 'tool_use'));
|
||||
|
||||
const combinedContent = loopMessages.filter(m => m.role === 'assistant')
|
||||
.map(m => m.content.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\n\n'))
|
||||
.filter(c => c).join('\n\n');
|
||||
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')
|
||||
}]));
|
||||
res(this.toStandard([...history, {role: 'assistant', content: combinedContent, timestamp: Date.now()}]));
|
||||
});
|
||||
|
||||
return Object.assign(response, {abort: () => controller.abort()});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ export type LLMMessage = {
|
||||
role: 'assistant' | 'system' | 'user';
|
||||
/** Message content */
|
||||
content: string | any;
|
||||
/** Timestamp */
|
||||
timestamp: number;
|
||||
} | {
|
||||
/** Tool call */
|
||||
role: 'tool';
|
||||
@@ -24,6 +26,8 @@ export type LLMMessage = {
|
||||
content: undefined | string;
|
||||
/** Tool error */
|
||||
error: undefined | string;
|
||||
/** Timestamp */
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export type LLMOptions = {
|
||||
@@ -125,7 +129,7 @@ export class LLM {
|
||||
const recent = keep == 0 ? [] : history.slice(-keep),
|
||||
process = (keep == 0 ? history : history.slice(0, -keep)).filter(h => h.role === 'assistant' || h.role === 'user');
|
||||
const summary = await this.summarize(process.map(m => `${m.role}: ${m.content}`).join('\n\n'), 250, options);
|
||||
return [{role: 'assistant', content: `Conversation Summary: ${summary}`}, ...recent];
|
||||
return [{role: 'assistant', content: `Conversation Summary: ${summary}`, timestamp: Date.now()}, ...recent];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -22,8 +22,9 @@ export class Ollama extends LLMProvider {
|
||||
}
|
||||
} else if(history[i].role == 'tool') {
|
||||
const error = history[i].content.startsWith('{"error":');
|
||||
history[i] = {role: 'tool', name: history[i].tool_name, args: history[i].args, [error ? 'error' : 'content']: history[i].content};
|
||||
history[i] = {role: 'tool', name: history[i].tool_name, args: history[i].args, [error ? 'error' : 'content']: history[i].content, timestamp: history[i].timestamp};
|
||||
}
|
||||
if(!history[i]?.timestamp) history[i].timestamp = Date.now();
|
||||
}
|
||||
return history;
|
||||
}
|
||||
@@ -31,7 +32,7 @@ export class Ollama extends LLMProvider {
|
||||
private fromStandard(history: LLMMessage[]): any[] {
|
||||
return history.map((h: any) => {
|
||||
if(h.role != 'tool') return h;
|
||||
return {role: 'tool', tool_name: h.name, content: h.error || h.content}
|
||||
return {role: 'tool', tool_name: h.name, content: h.error || h.content, timestamp: h.timestamp}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -39,7 +40,7 @@ export class Ollama extends LLMProvider {
|
||||
const controller = new AbortController();
|
||||
const response = new Promise<any>(async (res, rej) => {
|
||||
let system = options.system || this.ai.options.system;
|
||||
let history = this.fromStandard([...options.history || [], {role: 'user', content: message}]);
|
||||
let history = this.fromStandard([...options.history || [], {role: 'user', content: message, timestamp: Date.now()}]);
|
||||
if(history[0].roll == 'system') {
|
||||
if(!system) system = history.shift();
|
||||
else history.shift();
|
||||
@@ -70,11 +71,12 @@ export class Ollama extends LLMProvider {
|
||||
}))
|
||||
}
|
||||
|
||||
// Run tool chains
|
||||
let resp: any;
|
||||
const loopMessages: any[] = [];
|
||||
do {
|
||||
resp = await this.client.chat(requestParams);
|
||||
if(options.stream) {
|
||||
if(loopMessages.length) options.stream({text: '\n\n'});
|
||||
resp.message = {role: 'assistant', content: '', tool_calls: []};
|
||||
for await (const chunk of resp) {
|
||||
if(controller.signal.aborted) break;
|
||||
@@ -87,27 +89,33 @@ export class Ollama extends LLMProvider {
|
||||
}
|
||||
}
|
||||
|
||||
// Run tools
|
||||
loopMessages.push({role: 'assistant', content: resp.message?.content, timestamp: Date.now()});
|
||||
|
||||
if(resp.message?.tool_calls?.length && !controller.signal.aborted) {
|
||||
history.push(resp.message);
|
||||
history.push({...resp.message, timestamp: Date.now()});
|
||||
const results = await Promise.all(resp.message.tool_calls.map(async (toolCall: any) => {
|
||||
const tool = (options.tools || this.ai.options.tools)?.find(findByProp('name', toolCall.function.name));
|
||||
if(!tool) return {role: 'tool', tool_name: toolCall.function.name, content: '{"error": "Tool not found"}'};
|
||||
if(!tool) return {role: 'tool', tool_name: toolCall.function.name, content: '{"error": "Tool not found"}', timestamp: Date.now()};
|
||||
const args = typeof toolCall.function.arguments === 'string' ? JSONAttemptParse(toolCall.function.arguments, {}) : toolCall.function.arguments;
|
||||
try {
|
||||
const result = await tool.fn(args, this.ai);
|
||||
return {role: 'tool', tool_name: toolCall.function.name, args, content: JSONSanitize(result)};
|
||||
return {role: 'tool', tool_name: toolCall.function.name, args, content: JSONSanitize(result), timestamp: Date.now()};
|
||||
} catch (err: any) {
|
||||
return {role: 'tool', tool_name: toolCall.function.name, args, content: JSONSanitize({error: err?.message || err?.toString() || 'Unknown'})};
|
||||
return {role: 'tool', tool_name: toolCall.function.name, args, content: JSONSanitize({error: err?.message || err?.toString() || 'Unknown'}), timestamp: Date.now()};
|
||||
}
|
||||
}));
|
||||
history.push(...results);
|
||||
loopMessages.push(...results);
|
||||
requestParams.messages = history;
|
||||
}
|
||||
} while (!controller.signal.aborted && resp.message?.tool_calls?.length);
|
||||
|
||||
const combinedContent = loopMessages.filter(m => m.role === 'assistant')
|
||||
.map(m => m.content).filter(c => c).join('\n\n');
|
||||
if(options.stream) options.stream({done: true});
|
||||
res(this.toStandard([...history, {role: 'assistant', content: resp.message?.content}]));
|
||||
res(this.toStandard([...history, {role: 'assistant', content: combinedContent, timestamp: Date.now()}]));
|
||||
});
|
||||
|
||||
return Object.assign(response, {abort: () => controller.abort()});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,8 @@ export class OpenAi extends LLMProvider {
|
||||
role: 'tool',
|
||||
id: tc.id,
|
||||
name: tc.function.name,
|
||||
args: JSONAttemptParse(tc.function.arguments, {})
|
||||
args: JSONAttemptParse(tc.function.arguments, {}),
|
||||
timestamp: h.timestamp
|
||||
}));
|
||||
history.splice(i, 1, ...tools);
|
||||
i += tools.length - 1;
|
||||
@@ -33,7 +34,7 @@ export class OpenAi extends LLMProvider {
|
||||
history.splice(i, 1);
|
||||
i--;
|
||||
}
|
||||
|
||||
if(!history[i]?.timestamp) history[i].timestamp = Date.now();
|
||||
}
|
||||
return history;
|
||||
}
|
||||
@@ -47,10 +48,12 @@ export class OpenAi extends LLMProvider {
|
||||
tool_calls: [{ id: h.id, type: 'function', function: { name: h.name, arguments: JSON.stringify(h.args) } }],
|
||||
refusal: null,
|
||||
annotations: [],
|
||||
timestamp: h.timestamp
|
||||
}, {
|
||||
role: 'tool',
|
||||
tool_call_id: h.id,
|
||||
content: h.error || h.content
|
||||
content: h.error || h.content,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
} else {
|
||||
result.push(h);
|
||||
@@ -62,7 +65,7 @@ export class OpenAi extends LLMProvider {
|
||||
ask(message: string, options: LLMRequest = {}): AbortablePromise<LLMMessage[]> {
|
||||
const controller = new AbortController();
|
||||
const response = new Promise<any>(async (res, rej) => {
|
||||
let history = this.fromStandard([...options.history || [], {role: 'user', content: message}]);
|
||||
let history = this.fromStandard([...options.history || [], {role: 'user', content: message, timestamp: Date.now()}]);
|
||||
if(options.compress) history = await this.ai.llm.compress(<any>history, options.compress.max, options.compress.min, options);
|
||||
|
||||
const requestParams: any = {
|
||||
@@ -85,44 +88,51 @@ export class OpenAi extends LLMProvider {
|
||||
}))
|
||||
};
|
||||
|
||||
// Tool call and streaming logic similar to other providers
|
||||
let resp: any;
|
||||
const loopMessages: any[] = [];
|
||||
do {
|
||||
resp = await this.client.chat.completions.create(requestParams);
|
||||
|
||||
// Implement streaming and tool call handling
|
||||
if(options.stream) {
|
||||
resp.choices = [];
|
||||
if(loopMessages.length) options.stream({text: '\n\n'});
|
||||
resp.choices = [{message: {content: '', tool_calls: []}}];
|
||||
for await (const chunk of resp) {
|
||||
if(controller.signal.aborted) break;
|
||||
if(chunk.choices[0].delta.content) {
|
||||
resp.choices[0].message.content += chunk.choices[0].delta.content;
|
||||
options.stream({text: chunk.choices[0].delta.content});
|
||||
}
|
||||
if(chunk.choices[0].delta.tool_calls) {
|
||||
resp.choices[0].message.tool_calls = chunk.choices[0].delta.tool_calls;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Run tools
|
||||
loopMessages.push({role: 'assistant', content: resp.choices[0].message.content || '', timestamp: Date.now()});
|
||||
|
||||
const toolCalls = resp.choices[0].message.tool_calls || [];
|
||||
if(toolCalls.length && !controller.signal.aborted) {
|
||||
history.push(resp.choices[0].message);
|
||||
history.push({...resp.choices[0].message, timestamp: Date.now()});
|
||||
const results = await Promise.all(toolCalls.map(async (toolCall: any) => {
|
||||
const tool = options.tools?.find(findByProp('name', toolCall.function.name));
|
||||
if(!tool) return {role: 'tool', tool_call_id: toolCall.id, content: '{"error": "Tool not found"}'};
|
||||
if(!tool) return {role: 'tool', tool_call_id: toolCall.id, content: '{"error": "Tool not found"}', timestamp: Date.now()};
|
||||
try {
|
||||
const args = JSONAttemptParse(toolCall.function.arguments, {});
|
||||
const result = await tool.fn(args, this.ai);
|
||||
return {role: 'tool', tool_call_id: toolCall.id, content: JSONSanitize(result)};
|
||||
return {role: 'tool', tool_call_id: toolCall.id, content: JSONSanitize(result), timestamp: Date.now()};
|
||||
} catch (err: any) {
|
||||
return {role: 'tool', tool_call_id: toolCall.id, content: JSONSanitize({error: err?.message || err?.toString() || 'Unknown'})};
|
||||
return {role: 'tool', tool_call_id: toolCall.id, content: JSONSanitize({error: err?.message || err?.toString() || 'Unknown'}), timestamp: Date.now()};
|
||||
}
|
||||
}));
|
||||
history.push(...results);
|
||||
loopMessages.push(...results);
|
||||
requestParams.messages = history;
|
||||
}
|
||||
} while (!controller.signal.aborted && resp.choices?.[0]?.message?.tool_calls?.length);
|
||||
|
||||
const combinedContent = loopMessages.filter(m => m.role === 'assistant')
|
||||
.map(m => m.content).filter(c => c).join('\n\n');
|
||||
if(options.stream) options.stream({done: true});
|
||||
res(this.toStandard([...history, {role: 'assistant', content: resp.choices[0].message.content || ''}]));
|
||||
res(this.toStandard([...history, {role: 'assistant', content: combinedContent, timestamp: Date.now()}]));
|
||||
});
|
||||
|
||||
return Object.assign(response, {abort: () => controller.abort()});
|
||||
|
||||
Reference in New Issue
Block a user