Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 27506d20af | |||
| 8c64129200 | |||
| 013aa942c0 |
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ztimson/ai-utils",
|
"name": "@ztimson/ai-utils",
|
||||||
"version": "0.5.3",
|
"version": "0.5.6",
|
||||||
"description": "AI Utility library",
|
"description": "AI Utility library",
|
||||||
"author": "Zak Timson",
|
"author": "Zak Timson",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
|||||||
@@ -13,25 +13,25 @@ export class Anthropic extends LLMProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private toStandard(history: any[]): LLMMessage[] {
|
private toStandard(history: any[]): LLMMessage[] {
|
||||||
for(let i = 0; i < history.length; i++) {
|
const timestamp = Date.now();
|
||||||
const orgI = i;
|
const messages: LLMMessage[] = [];
|
||||||
if(typeof history[orgI].content != 'string') {
|
for(let h of history) {
|
||||||
if(history[orgI].role == 'assistant') {
|
if(typeof h.content == 'string') {
|
||||||
history[orgI].content.filter((c: any) => c.type =='tool_use').forEach((c: any) => {
|
messages.push(<any>{timestamp, ...h});
|
||||||
history.splice(i + 1, 0, {role: 'tool', id: c.id, name: c.name, args: c.input, timestamp: Date.now()});
|
} else {
|
||||||
});
|
const textContent = h.content?.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\n\n');
|
||||||
} else if(history[orgI].role == 'user') {
|
if(textContent) messages.push({timestamp, role: h.role, content: textContent});
|
||||||
history[orgI].content.filter((c: any) => c.type =='tool_result').forEach((c: any) => {
|
h.content.forEach((c: any) => {
|
||||||
const h = history.find((h: any) => h.id == c.tool_use_id);
|
if(c.type == 'tool_use') {
|
||||||
h[c.is_error ? 'error' : 'content'] = c.content;
|
messages.push({timestamp, role: 'tool', id: c.id, name: c.name, args: c.input, content: undefined});
|
||||||
|
} else if(c.type == 'tool_result') {
|
||||||
|
const m: any = messages.findLast(m => (<any>m).id == c.tool_use_id);
|
||||||
|
if(m) m[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');
|
|
||||||
if(!history[orgI].content) history.splice(orgI, 1);
|
|
||||||
}
|
}
|
||||||
if(!history[orgI].timestamp) history[orgI].timestamp = Date.now();
|
return messages;
|
||||||
}
|
|
||||||
return history.filter(h => !!h.content);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fromStandard(history: LLMMessage[]): any[] {
|
private fromStandard(history: LLMMessage[]): any[] {
|
||||||
@@ -50,8 +50,8 @@ export class Anthropic extends LLMProvider {
|
|||||||
|
|
||||||
ask(message: string, options: LLMRequest = {}): AbortablePromise<string> {
|
ask(message: string, options: LLMRequest = {}): AbortablePromise<string> {
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
return Object.assign(new Promise<any>(async (res, rej) => {
|
return Object.assign(new Promise<any>(async (res) => {
|
||||||
const history = this.fromStandard([...options.history || [], {role: 'user', content: message, timestamp: Date.now()}]);
|
let history = this.fromStandard([...options.history || [], {role: 'user', content: message, timestamp: Date.now()}]);
|
||||||
const tools = options.tools || this.ai.options.llm?.tools || [];
|
const tools = options.tools || this.ai.options.llm?.tools || [];
|
||||||
const requestParams: any = {
|
const requestParams: any = {
|
||||||
model: options.model || this.model,
|
model: options.model || this.model,
|
||||||
@@ -73,7 +73,6 @@ export class Anthropic extends LLMProvider {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let resp: any, isFirstMessage = true;
|
let resp: any, isFirstMessage = true;
|
||||||
const assistantMessages: string[] = [];
|
|
||||||
do {
|
do {
|
||||||
resp = await this.client.messages.create(requestParams).catch(err => {
|
resp = await this.client.messages.create(requestParams).catch(err => {
|
||||||
err.message += `\n\nMessages:\n${JSON.stringify(history, null, 2)}`;
|
err.message += `\n\nMessages:\n${JSON.stringify(history, null, 2)}`;
|
||||||
@@ -119,7 +118,6 @@ export class Anthropic extends LLMProvider {
|
|||||||
if(options.stream) options.stream({tool: toolCall.name});
|
if(options.stream) options.stream({tool: toolCall.name});
|
||||||
if(!tool) return {tool_use_id: toolCall.id, is_error: true, content: 'Tool not found'};
|
if(!tool) return {tool_use_id: toolCall.id, is_error: true, content: 'Tool not found'};
|
||||||
try {
|
try {
|
||||||
console.log(typeof tool.fn);
|
|
||||||
const result = await tool.fn(toolCall.input, options?.stream, this.ai);
|
const result = await tool.fn(toolCall.input, options?.stream, this.ai);
|
||||||
return {type: 'tool_result', tool_use_id: toolCall.id, content: JSONSanitize(result)};
|
return {type: 'tool_result', tool_use_id: toolCall.id, content: JSONSanitize(result)};
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
@@ -131,7 +129,7 @@ export class Anthropic extends LLMProvider {
|
|||||||
}
|
}
|
||||||
} while (!controller.signal.aborted && resp.content.some((c: any) => c.type === 'tool_use'));
|
} while (!controller.signal.aborted && resp.content.some((c: any) => c.type === 'tool_use'));
|
||||||
history.push({role: 'assistant', content: resp.content.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\n\n')});
|
history.push({role: 'assistant', content: resp.content.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\n\n')});
|
||||||
this.toStandard(history);
|
history = this.toStandard(history);
|
||||||
|
|
||||||
if(options.stream) options.stream({done: true});
|
if(options.stream) options.stream({done: true});
|
||||||
if(options.history) options.history.splice(0, options.history.length, ...history);
|
if(options.history) options.history.splice(0, options.history.length, ...history);
|
||||||
|
|||||||
@@ -3,8 +3,11 @@ import { parentPort } from 'worker_threads';
|
|||||||
|
|
||||||
let embedder: any;
|
let embedder: any;
|
||||||
|
|
||||||
parentPort?.on('message', async ({ id, text, model }) => {
|
parentPort?.on('message', async ({ id, text, model, path }) => {
|
||||||
if(!embedder) embedder = await pipeline('feature-extraction', 'Xenova/' + model, {quantized: true});
|
if(!embedder) embedder = await pipeline('feature-extraction', 'Xenova/' + model, {
|
||||||
|
quantized: true,
|
||||||
|
cache_dir: path,
|
||||||
|
});
|
||||||
const output = await embedder(text, { pooling: 'mean', normalize: true });
|
const output = await embedder(text, { pooling: 'mean', normalize: true });
|
||||||
const embedding = Array.from(output.data);
|
const embedding = Array.from(output.data);
|
||||||
parentPort?.postMessage({ id, embedding });
|
parentPort?.postMessage({ id, embedding });
|
||||||
|
|||||||
@@ -271,7 +271,12 @@ class LLM {
|
|||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const id = this.embedId++;
|
const id = this.embedId++;
|
||||||
this.embedQueue.set(id, { resolve, reject });
|
this.embedQueue.set(id, { resolve, reject });
|
||||||
this.embedWorker?.postMessage({ id, text, model: this.ai.options?.embedder || 'bge-small-en-v1.5' });
|
this.embedWorker?.postMessage({
|
||||||
|
id,
|
||||||
|
text,
|
||||||
|
model: this.ai.options?.embedder || 'bge-small-en-v1.5',
|
||||||
|
path: this.ai.options.path
|
||||||
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
const chunks = this.chunk(target, maxTokens, overlapTokens);
|
const chunks = this.chunk(target, maxTokens, overlapTokens);
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ export class OpenAi extends LLMProvider {
|
|||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
return Object.assign(new Promise<any>(async (res, rej) => {
|
return Object.assign(new Promise<any>(async (res, rej) => {
|
||||||
if(options.system && options.history?.[0]?.role != 'system') options.history?.splice(0, 0, {role: 'system', content: options.system, timestamp: Date.now()});
|
if(options.system && options.history?.[0]?.role != 'system') options.history?.splice(0, 0, {role: 'system', content: options.system, timestamp: Date.now()});
|
||||||
const history = this.fromStandard([...options.history || [], {role: 'user', content: message, timestamp: Date.now()}]);
|
let history = this.fromStandard([...options.history || [], {role: 'user', content: message, timestamp: Date.now()}]);
|
||||||
const tools = options.tools || this.ai.options.llm?.tools || [];
|
const tools = options.tools || this.ai.options.llm?.tools || [];
|
||||||
const requestParams: any = {
|
const requestParams: any = {
|
||||||
model: options.model || this.model,
|
model: options.model || this.model,
|
||||||
@@ -133,7 +133,7 @@ export class OpenAi extends LLMProvider {
|
|||||||
}
|
}
|
||||||
} while (!controller.signal.aborted && resp.choices?.[0]?.message?.tool_calls?.length);
|
} while (!controller.signal.aborted && resp.choices?.[0]?.message?.tool_calls?.length);
|
||||||
history.push({role: 'assistant', content: resp.choices[0].message.content || ''});
|
history.push({role: 'assistant', content: resp.choices[0].message.content || ''});
|
||||||
this.toStandard(history);
|
history = this.toStandard(history);
|
||||||
|
|
||||||
if(options.stream) options.stream({done: true});
|
if(options.stream) options.stream({done: true});
|
||||||
if(options.history) options.history.splice(0, options.history.length, ...history);
|
if(options.history) options.history.splice(0, options.history.length, ...history);
|
||||||
|
|||||||
Reference in New Issue
Block a user