Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6dce0e8954 | |||
| 98dd0bb323 | |||
| ca5a2334bb | |||
| 3cd7b12f5f | |||
| bb6933f0d5 |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ztimson/ai-utils",
|
||||
"version": "0.2.0",
|
||||
"version": "0.2.4",
|
||||
"description": "AI Utility library",
|
||||
"author": "Zak Timson",
|
||||
"license": "MIT",
|
||||
|
||||
10
src/ai.ts
10
src/ai.ts
@@ -1,3 +1,4 @@
|
||||
import * as os from 'node:os';
|
||||
import {LLM, LLMOptions} from './llm';
|
||||
import { Audio } from './audio.ts';
|
||||
import {Vision} from './vision.ts';
|
||||
@@ -8,15 +9,12 @@ export type AiOptions = LLMOptions & {
|
||||
binary: string;
|
||||
/** Model: `ggml-base.en.bin` */
|
||||
model: string;
|
||||
/** Path to models */
|
||||
path: string;
|
||||
}
|
||||
/** Path to models */
|
||||
path?: string;
|
||||
}
|
||||
|
||||
export class Ai {
|
||||
private downloads: {[key: string]: Promise<string>} = {};
|
||||
private whisperModel!: string;
|
||||
|
||||
/** Audio processing AI */
|
||||
audio!: Audio;
|
||||
/** Language processing AI */
|
||||
@@ -25,6 +23,8 @@ export class Ai {
|
||||
vision!: Vision;
|
||||
|
||||
constructor(public readonly options: AiOptions) {
|
||||
if(!options.path) options.path = os.tmpdir();
|
||||
process.env.TRANSFORMERS_CACHE = options.path;
|
||||
this.audio = new Audio(this);
|
||||
this.language = new LLM(this);
|
||||
this.vision = new Vision(this);
|
||||
|
||||
@@ -54,12 +54,14 @@ export class Anthropic extends LLMProvider {
|
||||
let history = this.fromStandard([...options.history || [], {role: 'user', content: message, timestamp: Date.now()}]);
|
||||
const original = deepCopy(history);
|
||||
if(options.compress) history = await this.ai.language.compressHistory(<any>history, options.compress.max, options.compress.min, options);
|
||||
|
||||
const tools = options.tools || this.ai.options.tools || [];
|
||||
const requestParams: any = {
|
||||
model: options.model || this.model,
|
||||
max_tokens: options.max_tokens || this.ai.options.max_tokens || 4096,
|
||||
system: options.system || this.ai.options.system || '',
|
||||
temperature: options.temperature || this.ai.options.temperature || 0.7,
|
||||
tools: (options.tools || this.ai.options.tools || []).map(t => ({
|
||||
tools: tools.map(t => ({
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
input_schema: {
|
||||
@@ -76,7 +78,10 @@ export class Anthropic extends LLMProvider {
|
||||
let resp: any, isFirstMessage = true;
|
||||
const assistantMessages: string[] = [];
|
||||
do {
|
||||
resp = await this.client.messages.create(requestParams);
|
||||
resp = await this.client.messages.create(requestParams).catch(err => {
|
||||
err.message += `\n\nMessages:\n${JSON.stringify(history, null, 2)}`;
|
||||
throw err;
|
||||
});
|
||||
|
||||
// Streaming mode
|
||||
if(options.stream) {
|
||||
@@ -114,7 +119,7 @@ export class Anthropic extends LLMProvider {
|
||||
history.push({role: 'assistant', content: resp.content});
|
||||
original.push({role: 'assistant', content: resp.content});
|
||||
const results = await Promise.all(toolCalls.map(async (toolCall: any) => {
|
||||
const tool = options.tools?.find(findByProp('name', toolCall.name));
|
||||
const tool = tools.find(findByProp('name', toolCall.name));
|
||||
if(!tool) return {tool_use_id: toolCall.id, is_error: true, content: 'Tool not found'};
|
||||
try {
|
||||
const result = await tool.fn(toolCall.input, this.ai);
|
||||
|
||||
@@ -48,7 +48,7 @@ export class Audio {
|
||||
async downloadAsrModel(model: string = this.whisperModel): Promise<string> {
|
||||
if(!this.ai.options.whisper?.binary) throw new Error('Whisper not configured');
|
||||
if(!model.endsWith('.bin')) model += '.bin';
|
||||
const p = Path.join(this.ai.options.whisper.path, model);
|
||||
const p = Path.join(<string>this.ai.options.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/${model}`)
|
||||
|
||||
26
src/llm.ts
26
src/llm.ts
@@ -136,6 +136,18 @@ export class LLM {
|
||||
return [{role: 'assistant', content: `Conversation Summary: ${summary}`, timestamp: Date.now()}, ...recent];
|
||||
}
|
||||
|
||||
cosineSimilarity(v1: number[], v2: number[]): number {
|
||||
if (v1.length !== v2.length) throw new Error('Vectors must be same length');
|
||||
let dotProduct = 0, normA = 0, normB = 0;
|
||||
for (let i = 0; i < v1.length; i++) {
|
||||
dotProduct += v1[i] * v2[i];
|
||||
normA += v1[i] * v1[i];
|
||||
normB += v2[i] * v2[i];
|
||||
}
|
||||
const denominator = Math.sqrt(normA) * Math.sqrt(normB);
|
||||
return denominator === 0 ? 0 : dotProduct / denominator;
|
||||
}
|
||||
|
||||
embedding(target: object | string, maxTokens = 500, overlapTokens = 50) {
|
||||
const objString = (obj: any, path = ''): string[] => {
|
||||
if(obj === null || obj === undefined) return [];
|
||||
@@ -205,24 +217,12 @@ export class LLM {
|
||||
*/
|
||||
fuzzyMatch(target: string, ...searchTerms: string[]) {
|
||||
if(searchTerms.length < 2) throw new Error('Requires at least 2 strings to compare');
|
||||
|
||||
const vector = (text: string, dimensions: number = 10): number[] => {
|
||||
return text.toLowerCase().split('').map((char, index) =>
|
||||
(char.charCodeAt(0) * (index + 1)) % dimensions / dimensions).slice(0, dimensions);
|
||||
}
|
||||
|
||||
const cosineSimilarity = (v1: number[], v2: number[]): number => {
|
||||
if (v1.length !== v2.length) throw new Error('Vectors must be same length');
|
||||
const tensor1 = tf.tensor1d(v1), tensor2 = tf.tensor1d(v2)
|
||||
const dotProduct = tf.dot(tensor1, tensor2)
|
||||
const magnitude1 = tf.norm(tensor1)
|
||||
const magnitude2 = tf.norm(tensor2)
|
||||
if(magnitude1.dataSync()[0] === 0 || magnitude2.dataSync()[0] === 0) return 0
|
||||
return dotProduct.dataSync()[0] / (magnitude1.dataSync()[0] * magnitude2.dataSync()[0])
|
||||
}
|
||||
|
||||
const v = vector(target);
|
||||
const similarities = searchTerms.map(t => vector(t)).map(refVector => cosineSimilarity(v, refVector))
|
||||
const similarities = searchTerms.map(t => vector(t)).map(refVector => this.cosineSimilarity(v, refVector))
|
||||
return {avg: similarities.reduce((acc, s) => acc + s, 0) / similarities.length, max: Math.max(...similarities), similarities}
|
||||
}
|
||||
|
||||
|
||||
@@ -49,6 +49,7 @@ export class Ollama extends LLMProvider {
|
||||
if(options.compress) history = await this.ai.language.compressHistory(<any>history, options.compress.max, options.compress.min);
|
||||
if(options.system) history.unshift({role: 'system', content: system})
|
||||
|
||||
const tools = options.tools || this.ai.options.tools || [];
|
||||
const requestParams: any = {
|
||||
model: options.model || this.model,
|
||||
messages: history,
|
||||
@@ -58,7 +59,7 @@ export class Ollama extends LLMProvider {
|
||||
temperature: options.temperature || this.ai.options.temperature || 0.7,
|
||||
num_predict: options.max_tokens || this.ai.options.max_tokens || 4096,
|
||||
},
|
||||
tools: (options.tools || this.ai.options.tools || []).map(t => ({
|
||||
tools: tools.map(t => ({
|
||||
type: 'function',
|
||||
function: {
|
||||
name: t.name,
|
||||
@@ -74,7 +75,11 @@ export class Ollama extends LLMProvider {
|
||||
|
||||
let resp: any, isFirstMessage = true;
|
||||
do {
|
||||
resp = await this.client.chat(requestParams);
|
||||
resp = await this.client.chat(requestParams).catch(err => {
|
||||
err.message += `\n\nMessages:\n${JSON.stringify(history, null, 2)}`;
|
||||
throw err;
|
||||
});
|
||||
|
||||
if(options.stream) {
|
||||
if(!isFirstMessage) options.stream({text: '\n\n'});
|
||||
else isFirstMessage = false;
|
||||
@@ -93,7 +98,7 @@ export class Ollama extends LLMProvider {
|
||||
if(resp.message?.tool_calls?.length && !controller.signal.aborted) {
|
||||
history.push(resp.message);
|
||||
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));
|
||||
const tool = tools.find(findByProp('name', toolCall.function.name));
|
||||
if(!tool) return {role: 'tool', tool_name: toolCall.function.name, content: '{"error": "Tool not found"}'};
|
||||
const args = typeof toolCall.function.arguments === 'string' ? JSONAttemptParse(toolCall.function.arguments, {}) : toolCall.function.arguments;
|
||||
try {
|
||||
|
||||
@@ -67,13 +67,14 @@ export class OpenAi extends LLMProvider {
|
||||
let history = this.fromStandard([...options.history || [], {role: 'user', content: message, timestamp: Date.now()}]);
|
||||
if(options.compress) history = await this.ai.language.compressHistory(<any>history, options.compress.max, options.compress.min, options);
|
||||
|
||||
const tools = options.tools || this.ai.options.tools || [];
|
||||
const requestParams: any = {
|
||||
model: options.model || this.model,
|
||||
messages: history,
|
||||
stream: !!options.stream,
|
||||
max_tokens: options.max_tokens || this.ai.options.max_tokens || 4096,
|
||||
temperature: options.temperature || this.ai.options.temperature || 0.7,
|
||||
tools: (options.tools || this.ai.options.tools || []).map(t => ({
|
||||
tools: tools.map(t => ({
|
||||
type: 'function',
|
||||
function: {
|
||||
name: t.name,
|
||||
@@ -89,7 +90,11 @@ export class OpenAi extends LLMProvider {
|
||||
|
||||
let resp: any, isFirstMessage = true;
|
||||
do {
|
||||
resp = await this.client.chat.completions.create(requestParams);
|
||||
resp = await this.client.chat.completions.create(requestParams).catch(err => {
|
||||
err.message += `\n\nMessages:\n${JSON.stringify(history, null, 2)}`;
|
||||
throw err;
|
||||
});
|
||||
|
||||
if(options.stream) {
|
||||
if(!isFirstMessage) options.stream({text: '\n\n'});
|
||||
else isFirstMessage = false;
|
||||
@@ -110,7 +115,7 @@ export class OpenAi extends LLMProvider {
|
||||
if(toolCalls.length && !controller.signal.aborted) {
|
||||
history.push(resp.choices[0].message);
|
||||
const results = await Promise.all(toolCalls.map(async (toolCall: any) => {
|
||||
const tool = options.tools?.find(findByProp('name', toolCall.function.name));
|
||||
const tool = tools?.find(findByProp('name', toolCall.function.name));
|
||||
if(!tool) return {role: 'tool', tool_call_id: toolCall.id, content: '{"error": "Tool not found"}'};
|
||||
try {
|
||||
const args = JSONAttemptParse(toolCall.function.arguments, {});
|
||||
|
||||
@@ -15,7 +15,7 @@ export class Vision {
|
||||
return {
|
||||
abort: () => { worker?.terminate(); },
|
||||
response: new Promise(async res => {
|
||||
worker = await createWorker('eng');
|
||||
worker = await createWorker('eng', 1, {cachePath: this.ai.options.path});
|
||||
const {data} = await worker.recognize(path);
|
||||
await worker.terminate();
|
||||
res(data.text.trim() || null);
|
||||
|
||||
Reference in New Issue
Block a user