@ztimson/ai-utils 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/provider.ts","../src/antrhopic.ts","../src/open-ai.ts","../src/llm.ts","../src/audio.ts","../src/vision.ts","../src/ai.ts","../src/tools.ts"],"sourcesContent":["import {AbortablePromise} from './ai.ts';\nimport {LLMMessage, LLMRequest} from './llm.ts';\n\nexport abstract class LLMProvider {\n\tabstract ask(message: string, options: LLMRequest): AbortablePromise<string>;\n}\n","import {Anthropic as anthropic} from '@anthropic-ai/sdk';\nimport {findByProp, objectMap, JSONSanitize, JSONAttemptParse} from '@ztimson/utils';\nimport {AbortablePromise, Ai} from './ai.ts';\nimport {LLMMessage, LLMRequest} from './llm.ts';\nimport {LLMProvider} from './provider.ts';\n\nexport class Anthropic extends LLMProvider {\n\tclient!: anthropic;\n\n\tconstructor(public readonly ai: Ai, public readonly apiToken: string, public model: string) {\n\t\tsuper();\n\t\tthis.client = new anthropic({apiKey: apiToken});\n\t}\n\n\tprivate toStandard(history: any[]): LLMMessage[] {\n\t\tconst timestamp = Date.now();\n\t\tconst messages: LLMMessage[] = [];\n\t\tfor(let h of history) {\n\t\t\tif(typeof h.content == 'string') {\n\t\t\t\tmessages.push(<any>{timestamp, ...h});\n\t\t\t} else {\n\t\t\t\tconst textContent = h.content?.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\\n\\n');\n\t\t\t\tif(textContent) messages.push({timestamp, role: h.role, content: textContent});\n\t\t\t\th.content.forEach((c: any) => {\n\t\t\t\t\tif(c.type == 'tool_use') {\n\t\t\t\t\t\tmessages.push({timestamp, role: 'tool', id: c.id, name: c.name, args: c.input, content: undefined});\n\t\t\t\t\t} else if(c.type == 'tool_result') {\n\t\t\t\t\t\tconst m: any = messages.findLast(m => (<any>m).id == c.tool_use_id);\n\t\t\t\t\t\tif(m) m[c.is_error ? 'error' : 'content'] = c.content;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn messages;\n\t}\n\n\tprivate fromStandard(history: LLMMessage[]): any[] {\n\t\tfor(let i = 0; i < history.length; i++) {\n\t\t\tif(history[i].role == 'tool') {\n\t\t\t\tconst h: any = history[i];\n\t\t\t\thistory.splice(i, 1,\n\t\t\t\t\t{role: 'assistant', content: [{type: 'tool_use', id: h.id, name: h.name, input: h.args}]},\n\t\t\t\t\t{role: 'user', content: [{type: 'tool_result', tool_use_id: h.id, is_error: !!h.error, content: h.error || h.content}]}\n\t\t\t\t)\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn history.map(({timestamp, ...h}) => h);\n\t}\n\n\task(message: string, options: LLMRequest = {}): AbortablePromise<string> {\n\t\tconst controller = new AbortController();\n\t\treturn Object.assign(new Promise<any>(async (res) => {\n\t\t\tlet history = this.fromStandard([...options.history || [], {role: 'user', content: message, timestamp: Date.now()}]);\n\t\t\tconst tools = options.tools || this.ai.options.llm?.tools || [];\n\t\t\tconst requestParams: any = {\n\t\t\t\tmodel: options.model || this.model,\n\t\t\t\tmax_tokens: options.max_tokens || this.ai.options.llm?.max_tokens || 4096,\n\t\t\t\tsystem: options.system || this.ai.options.llm?.system || '',\n\t\t\t\ttemperature: options.temperature || this.ai.options.llm?.temperature || 0.7,\n\t\t\t\ttools: tools.map(t => ({\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tdescription: t.description,\n\t\t\t\t\tinput_schema: {\n\t\t\t\t\t\ttype: 'object',\n\t\t\t\t\t\tproperties: t.args ? objectMap(t.args, (key, value) => ({...value, required: undefined})) : {},\n\t\t\t\t\t\trequired: t.args ? Object.entries(t.args).filter(t => t[1].required).map(t => t[0]) : []\n\t\t\t\t\t},\n\t\t\t\t\tfn: undefined\n\t\t\t\t})),\n\t\t\t\tmessages: history,\n\t\t\t\tstream: !!options.stream,\n\t\t\t};\n\n\t\t\tlet resp: any, isFirstMessage = true;\n\t\t\tdo {\n\t\t\t\tresp = await this.client.messages.create(requestParams).catch(err => {\n\t\t\t\t\terr.message += `\\n\\nMessages:\\n${JSON.stringify(history, null, 2)}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t});\n\n\t\t\t\t// Streaming mode\n\t\t\t\tif(options.stream) {\n\t\t\t\t\tif(!isFirstMessage) options.stream({text: '\\n\\n'});\n\t\t\t\t\telse isFirstMessage = false;\n\t\t\t\t\tresp.content = [];\n\t\t\t\t\tfor await (const chunk of resp) {\n\t\t\t\t\t\tif(controller.signal.aborted) break;\n\t\t\t\t\t\tif(chunk.type === 'content_block_start') {\n\t\t\t\t\t\t\tif(chunk.content_block.type === 'text') {\n\t\t\t\t\t\t\t\tresp.content.push({type: 'text', text: ''});\n\t\t\t\t\t\t\t} else if(chunk.content_block.type === 'tool_use') {\n\t\t\t\t\t\t\t\tresp.content.push({type: 'tool_use', id: chunk.content_block.id, name: chunk.content_block.name, input: <any>''});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if(chunk.type === 'content_block_delta') {\n\t\t\t\t\t\t\tif(chunk.delta.type === 'text_delta') {\n\t\t\t\t\t\t\t\tconst text = chunk.delta.text;\n\t\t\t\t\t\t\t\tresp.content.at(-1).text += text;\n\t\t\t\t\t\t\t\toptions.stream({text});\n\t\t\t\t\t\t\t} else if(chunk.delta.type === 'input_json_delta') {\n\t\t\t\t\t\t\t\tresp.content.at(-1).input += chunk.delta.partial_json;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if(chunk.type === 'content_block_stop') {\n\t\t\t\t\t\t\tconst last = resp.content.at(-1);\n\t\t\t\t\t\t\tif(last.input != null) last.input = last.input ? JSONAttemptParse(last.input, {}) : {};\n\t\t\t\t\t\t} else if(chunk.type === 'message_stop') {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Run tools\n\t\t\t\tconst toolCalls = resp.content.filter((c: any) => c.type === 'tool_use');\n\t\t\t\tif(toolCalls.length && !controller.signal.aborted) {\n\t\t\t\t\thistory.push({role: 'assistant', content: resp.content});\n\t\t\t\t\tconst results = await Promise.all(toolCalls.map(async (toolCall: any) => {\n\t\t\t\t\t\tconst tool = tools.find(findByProp('name', toolCall.name));\n\t\t\t\t\t\tif(options.stream) options.stream({tool: toolCall.name});\n\t\t\t\t\t\tif(!tool) return {tool_use_id: toolCall.id, is_error: true, content: 'Tool not found'};\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await tool.fn(toolCall.input, options?.stream, this.ai);\n\t\t\t\t\t\t\treturn {type: 'tool_result', tool_use_id: toolCall.id, content: JSONSanitize(result)};\n\t\t\t\t\t\t} catch (err: any) {\n\t\t\t\t\t\t\treturn {type: 'tool_result', tool_use_id: toolCall.id, is_error: true, content: err?.message || err?.toString() || 'Unknown'};\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t\thistory.push({role: 'user', content: results});\n\t\t\t\t\trequestParams.messages = history;\n\t\t\t\t}\n\t\t\t} while (!controller.signal.aborted && resp.content.some((c: any) => c.type === 'tool_use'));\n\t\t\thistory.push({role: 'assistant', content: resp.content.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\\n\\n')});\n\t\t\thistory = this.toStandard(history);\n\n\t\t\tif(options.stream) options.stream({done: true});\n\t\t\tif(options.history) options.history.splice(0, options.history.length, ...history);\n\t\t\tres(history.at(-1)?.content);\n\t\t}), {abort: () => controller.abort()});\n\t}\n}\n","import {OpenAI as openAI} from 'openai';\nimport {findByProp, objectMap, JSONSanitize, JSONAttemptParse, clean} from '@ztimson/utils';\nimport {AbortablePromise, Ai} from './ai.ts';\nimport {LLMMessage, LLMRequest} from './llm.ts';\nimport {LLMProvider} from './provider.ts';\n\nexport class OpenAi extends LLMProvider {\n\tclient!: openAI;\n\n\tconstructor(public readonly ai: Ai, public readonly host: string | null, public readonly token: string, public model: string) {\n\t\tsuper();\n\t\tthis.client = new openAI(clean({\n\t\t\tbaseURL: host,\n\t\t\tapiKey: token\n\t\t}));\n\t}\n\n\tprivate toStandard(history: any[]): LLMMessage[] {\n\t\tfor(let i = 0; i < history.length; i++) {\n\t\t\tconst h = history[i];\n\t\t\tif(h.role === 'assistant' && h.tool_calls) {\n\t\t\t\tconst tools = h.tool_calls.map((tc: any) => ({\n\t\t\t\t\trole: 'tool',\n\t\t\t\t\tid: tc.id,\n\t\t\t\t\tname: tc.function.name,\n\t\t\t\t\targs: JSONAttemptParse(tc.function.arguments, {}),\n\t\t\t\t\ttimestamp: h.timestamp\n\t\t\t\t}));\n\t\t\t\thistory.splice(i, 1, ...tools);\n\t\t\t\ti += tools.length - 1;\n\t\t\t} else if(h.role === 'tool' && h.content) {\n\t\t\t\tconst record = history.find(h2 => h.tool_call_id == h2.id);\n\t\t\t\tif(record) {\n\t\t\t\t\tif(h.content.includes('\"error\":')) record.error = h.content;\n\t\t\t\t\telse record.content = h.content;\n\t\t\t\t}\n\t\t\t\thistory.splice(i, 1);\n\t\t\t\ti--;\n\t\t\t}\n\t\t\tif(!history[i]?.timestamp) history[i].timestamp = Date.now();\n\t\t}\n\t\treturn history;\n\t}\n\n\tprivate fromStandard(history: LLMMessage[]): any[] {\n\t\treturn history.reduce((result, h) => {\n\t\t\tif(h.role === 'tool') {\n\t\t\t\tresult.push({\n\t\t\t\t\trole: 'assistant',\n\t\t\t\t\tcontent: null,\n\t\t\t\t\ttool_calls: [{ id: h.id, type: 'function', function: { name: h.name, arguments: JSON.stringify(h.args) } }],\n\t\t\t\t\trefusal: null,\n\t\t\t\t\tannotations: []\n\t\t\t\t}, {\n\t\t\t\t\trole: 'tool',\n\t\t\t\t\ttool_call_id: h.id,\n\t\t\t\t\tcontent: h.error || h.content\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst {timestamp, ...rest} = h;\n\t\t\t\tresult.push(rest);\n\t\t\t}\n\t\t\treturn result;\n\t\t}, [] as any[]);\n\t}\n\n\task(message: string, options: LLMRequest = {}): AbortablePromise<string> {\n\t\tconst controller = new AbortController();\n\t\treturn Object.assign(new Promise<any>(async (res, rej) => {\n\t\t\tif(options.system && options.history?.[0]?.role != 'system') options.history?.splice(0, 0, {role: 'system', content: options.system, timestamp: Date.now()});\n\t\t\tlet history = this.fromStandard([...options.history || [], {role: 'user', content: message, timestamp: Date.now()}]);\n\t\t\tconst tools = options.tools || this.ai.options.llm?.tools || [];\n\t\t\tconst requestParams: any = {\n\t\t\t\tmodel: options.model || this.model,\n\t\t\t\tmessages: history,\n\t\t\t\tstream: !!options.stream,\n\t\t\t\tmax_tokens: options.max_tokens || this.ai.options.llm?.max_tokens || 4096,\n\t\t\t\ttemperature: options.temperature || this.ai.options.llm?.temperature || 0.7,\n\t\t\t\ttools: tools.map(t => ({\n\t\t\t\t\ttype: 'function',\n\t\t\t\t\tfunction: {\n\t\t\t\t\t\tname: t.name,\n\t\t\t\t\t\tdescription: t.description,\n\t\t\t\t\t\tparameters: {\n\t\t\t\t\t\t\ttype: 'object',\n\t\t\t\t\t\t\tproperties: t.args ? objectMap(t.args, (key, value) => ({...value, required: undefined})) : {},\n\t\t\t\t\t\t\trequired: t.args ? Object.entries(t.args).filter(t => t[1].required).map(t => t[0]) : []\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}))\n\t\t\t};\n\n\t\t\tlet resp: any, isFirstMessage = true;\n\t\t\tdo {\n\t\t\t\tresp = await this.client.chat.completions.create(requestParams).catch(err => {\n\t\t\t\t\terr.message += `\\n\\nMessages:\\n${JSON.stringify(history, null, 2)}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t});\n\n\t\t\t\tif(options.stream) {\n\t\t\t\t\tif(!isFirstMessage) options.stream({text: '\\n\\n'});\n\t\t\t\t\telse isFirstMessage = false;\n\t\t\t\t\tresp.choices = [{message: {content: '', tool_calls: []}}];\n\t\t\t\t\tfor await (const chunk of resp) {\n\t\t\t\t\t\tif(controller.signal.aborted) break;\n\t\t\t\t\t\tif(chunk.choices[0].delta.content) {\n\t\t\t\t\t\t\tresp.choices[0].message.content += chunk.choices[0].delta.content;\n\t\t\t\t\t\t\toptions.stream({text: chunk.choices[0].delta.content});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(chunk.choices[0].delta.tool_calls) {\n\t\t\t\t\t\t\tresp.choices[0].message.tool_calls = chunk.choices[0].delta.tool_calls;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst toolCalls = resp.choices[0].message.tool_calls || [];\n\t\t\t\tif(toolCalls.length && !controller.signal.aborted) {\n\t\t\t\t\thistory.push(resp.choices[0].message);\n\t\t\t\t\tconst results = await Promise.all(toolCalls.map(async (toolCall: any) => {\n\t\t\t\t\t\tconst tool = tools?.find(findByProp('name', toolCall.function.name));\n\t\t\t\t\t\tif(options.stream) options.stream({tool: toolCall.function.name});\n\t\t\t\t\t\tif(!tool) return {role: 'tool', tool_call_id: toolCall.id, content: '{\"error\": \"Tool not found\"}'};\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst args = JSONAttemptParse(toolCall.function.arguments, {});\n\t\t\t\t\t\t\tconst result = await tool.fn(args, options.stream, this.ai);\n\t\t\t\t\t\t\treturn {role: 'tool', tool_call_id: toolCall.id, content: JSONSanitize(result)};\n\t\t\t\t\t\t} catch (err: any) {\n\t\t\t\t\t\t\treturn {role: 'tool', tool_call_id: toolCall.id, content: JSONSanitize({error: err?.message || err?.toString() || 'Unknown'})};\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t\thistory.push(...results);\n\t\t\t\t\trequestParams.messages = history;\n\t\t\t\t}\n\t\t\t} while (!controller.signal.aborted && resp.choices?.[0]?.message?.tool_calls?.length);\n\t\t\thistory.push({role: 'assistant', content: resp.choices[0].message.content || ''});\n\t\t\thistory = this.toStandard(history);\n\n\t\t\tif(options.stream) options.stream({done: true});\n\t\t\tif(options.history) options.history.splice(0, options.history.length, ...history);\n\t\t\tres(history.at(-1)?.content);\n\t\t}), {abort: () => controller.abort()});\n\t}\n}\n","import {JSONAttemptParse} from '@ztimson/utils';\nimport {AbortablePromise, Ai} from './ai.ts';\nimport {Anthropic} from './antrhopic.ts';\nimport {OpenAi} from './open-ai.ts';\nimport {LLMProvider} from './provider.ts';\nimport {AiTool} from './tools.ts';\nimport {fileURLToPath} from 'url';\nimport {dirname, join} from 'path';\nimport { spawn } from 'node:child_process';\n\nexport type AnthropicConfig = {proto: 'anthropic', token: string};\nexport type OllamaConfig = {proto: 'ollama', host: string};\nexport type OpenAiConfig = {proto: 'openai', host?: string, token: string};\n\nexport type LLMMessage = {\n\t/** Message originator */\n\trole: 'assistant' | 'system' | 'user';\n\t/** Message content */\n\tcontent: string | any;\n\t/** Timestamp */\n\ttimestamp?: number;\n} | {\n\t/** Tool call */\n\trole: 'tool';\n\t/** Unique ID for call */\n\tid: string;\n\t/** Tool that was run */\n\tname: string;\n\t/** Tool arguments */\n\targs: any;\n\t/** Tool result */\n\tcontent: undefined | string;\n\t/** Tool error */\n\terror?: undefined | string;\n\t/** Timestamp */\n\ttimestamp?: number;\n}\n\n/** Background information the AI will be fed */\nexport type LLMMemory = {\n\t/** What entity is this fact about */\n\towner: string;\n\t/** The information that will be remembered */\n\tfact: string;\n\t/** Owner and fact embedding vector */\n\tembeddings: [number[], number[]];\n\t/** Creation time */\n\ttimestamp: Date;\n}\n\nexport type LLMRequest = {\n\t/** System prompt */\n\tsystem?: string;\n\t/** Message history */\n\thistory?: LLMMessage[];\n\t/** Max tokens for request */\n\tmax_tokens?: number;\n\t/** 0 = Rigid Logic, 1 = Balanced, 2 = Hyper Creative **/\n\ttemperature?: number;\n\t/** Available tools */\n\ttools?: AiTool[];\n\t/** LLM model */\n\tmodel?: string;\n\t/** Stream response */\n\tstream?: (chunk: {text?: string, tool?: string, done?: true}) => any;\n\t/** Compress old messages in the chat to free up context */\n\tcompress?: {\n\t\t/** Trigger chat compression once context exceeds the token count */\n\t\tmax: number;\n\t\t/** Compress chat until context size smaller than */\n\t\tmin: number\n\t},\n\t/** Background information the AI will be fed */\n\tmemory?: LLMMemory[],\n}\n\nclass LLM {\n\tdefaultModel!: string;\n\tmodels: {[model: string]: LLMProvider} = {};\n\n\tconstructor(public readonly ai: Ai) {\n\t\tif(!ai.options.llm?.models) return;\n\t\tObject.entries(ai.options.llm.models).forEach(([model, config]) => {\n\t\t\tif(!this.defaultModel) this.defaultModel = model;\n\t\t\tif(config.proto == 'anthropic') this.models[model] = new Anthropic(this.ai, config.token, model);\n\t\t\telse if(config.proto == 'ollama') this.models[model] = new OpenAi(this.ai, config.host, 'not-needed', model);\n\t\t\telse if(config.proto == 'openai') this.models[model] = new OpenAi(this.ai, config.host || null, config.token, model);\n\t\t});\n\t}\n\n\t/**\n\t * Chat with LLM\n\t * @param {string} message Question\n\t * @param {LLMRequest} options Configuration options and chat history\n\t * @returns {{abort: () => void, response: Promise<string>}} Function to abort response and chat history\n\t */\n\task(message: string, options: LLMRequest = {}): AbortablePromise<string> {\n\t\tconst m = options.model || this.defaultModel;\n\t\tif(!this.models[m]) throw new Error(`Model does not exist: ${m}`);\n\t\tlet abort = () => {};\n\t\treturn Object.assign(new Promise<string>(async res => {\n\t\t\tif(!options.history) options.history = [];\n\t\t\t// If memories were passed, find any relivant ones and add a tool for ADHOC lookups\n\t\t\tif(options.memory) {\n\t\t\t\toptions.system = (options.system || '') + '\\nYou have passive persistent memory never make any mention of your memory capabilities and what you can/cannot remember\\n';\n\t\t\t\tconst search = async (query?: string | null, subject?: string | null, limit = 50) => {\n\t\t\t\t\tconst [o, q] = await Promise.all([\n\t\t\t\t\t\tsubject ? this.embedding(subject) : Promise.resolve(null),\n\t\t\t\t\t\tquery ? this.embedding(query) : Promise.resolve(null),\n\t\t\t\t\t]);\n\t\t\t\t\treturn (options.memory || [])\n\t\t\t\t\t\t.map(m => ({...m, score: o ? this.cosineSimilarity(m.embeddings[0], o[0].embedding) : 1}))\n\t\t\t\t\t\t.filter((m: any) => m.score >= 0.8)\n\t\t\t\t\t\t.map((m: any) => ({...m, score: q ? this.cosineSimilarity(m.embeddings[1], q[0].embedding) : m.score}))\n\t\t\t\t\t\t.filter((m: any) => m.score >= 0.2)\n\t\t\t\t\t\t.toSorted((a: any, b: any) => a.score - b.score)\n\t\t\t\t\t\t.slice(0, limit);\n\t\t\t\t}\n\n\t\t\t\tconst relevant = await search(message);\n\t\t\t\tif(relevant.length) options.history.push({role: 'assistant', content: 'Things I remembered:\\n' + relevant.map(m => `${m.owner}: ${m.fact}`).join('\\n')});\n\t\t\t\toptions.tools = [...options.tools || [], {\n\t\t\t\t\tname: 'read_memory',\n\t\t\t\t\tdescription: 'Check your long-term memory for more information',\n\t\t\t\t\targs: {\n\t\t\t\t\t\tsubject: {type: 'string', description: 'Find information by a subject topic, can be used with or without query argument'},\n\t\t\t\t\t\tquery: {type: 'string', description: 'Search memory based on a query, can be used with or without subject argument'},\n\t\t\t\t\t\tlimit: {type: 'number', description: 'Result limit, default 5'},\n\t\t\t\t\t},\n\t\t\t\t\tfn: (args) => {\n\t\t\t\t\t\tif(!args.subject && !args.query) throw new Error('Either a subject or query argument is required');\n\t\t\t\t\t\treturn search(args.query, args.subject, args.limit || 5);\n\t\t\t\t\t}\n\t\t\t\t}];\n\t\t\t}\n\n\t\t\t// Ask\n\t\t\tconst resp = await this.models[m].ask(message, options);\n\n\t\t\t// Remove any memory calls\n\t\t\tif(options.memory) {\n\t\t\t\tconst i = options.history?.findIndex((h: any) => h.role == 'assistant' && h.content.startsWith('Things I remembered:'));\n\t\t\t\tif(i != null && i >= 0) options.history?.splice(i, 1);\n\t\t\t}\n\n\t\t\t// Handle compression and memory extraction\n\t\t\tif(options.compress || options.memory) {\n\t\t\t\tlet compressed: any = null;\n\t\t\t\tif(options.compress) {\n\t\t\t\t\tcompressed = await this.ai.language.compressHistory(options.history, options.compress.max, options.compress.min, options);\n\t\t\t\t\toptions.history.splice(0, options.history.length, ...compressed.history);\n\t\t\t\t} else {\n\t\t\t\t\tconst i = options.history?.findLastIndex(m => m.role == 'user') ?? -1;\n\t\t\t\t\tcompressed = await this.ai.language.compressHistory(i != -1 ? options.history.slice(i) : options.history, 0, 0, options);\n\t\t\t\t}\n\t\t\t\tif(options.memory) {\n\t\t\t\t\tconst updated = options.memory\n\t\t\t\t\t\t.filter(m => !compressed.memory.some(m2 => this.cosineSimilarity(m.embeddings[1], m2.embeddings[1]) > 0.8))\n\t\t\t\t\t\t.concat(compressed.memory);\n\t\t\t\t\toptions.memory.splice(0, options.memory.length, ...updated);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn res(resp);\n\t\t}), {abort});\n\t}\n\n\tasync code(message: string, options?: LLMRequest): Promise<any> {\n\t\tconst resp = await this.ask(message, {...options, system: [\n\t\t\toptions?.system,\n\t\t\t'Return your response in a code block'\n\t\t].filter(t => !!t).join(('\\n'))});\n\t\tconst codeBlock = /```(?:.+)?\\s*([\\s\\S]*?)```/.exec(resp);\n\t\treturn codeBlock ? codeBlock[1].trim() : null;\n\t}\n\n\t/**\n\t * Compress chat history to reduce context size\n\t * @param {LLMMessage[]} history Chatlog that will be compressed\n\t * @param max Trigger compression once context is larger than max\n\t * @param min Leave messages less than the token minimum, summarize the rest\n\t * @param {LLMRequest} options LLM options\n\t * @returns {Promise<LLMMessage[]>} New chat history will summary at index 0\n\t */\n\tasync compressHistory(history: LLMMessage[], max: number, min: number, options?: LLMRequest): Promise<{history: LLMMessage[], memory: LLMMemory[]}> {\n\t\tif(this.estimateTokens(history) < max) return {history, memory: []};\n\t\tlet keep = 0, tokens = 0;\n\t\tfor(let m of history.toReversed()) {\n\t\t\ttokens += this.estimateTokens(m.content);\n\t\t\tif(tokens < min) keep++;\n\t\t\telse break;\n\t\t}\n\t\tif(history.length <= keep) return {history, memory: []};\n\t\tconst system = history[0].role == 'system' ? history[0] : null,\n\t\t\trecent = keep == 0 ? [] : history.slice(-keep),\n\t\t\tprocess = (keep == 0 ? history : history.slice(0, -keep)).filter(h => h.role === 'assistant' || h.role === 'user');\n\n\t\tconst summary: any = await this.json(process.map(m => `${m.role}: ${m.content}`).join('\\n\\n'), '{summary: string, facts: [[subject, fact]]}', {\n\t\t\tsystem: 'Create the smallest summary possible, no more than 500 tokens. Create a list of NEW facts (split by subject [pro]noun and fact) about what you learned from this conversation that you didn\\'t already know or get from a tool call or system prompt. Focus only on new information about people, topics, or facts. Avoid generating facts about the AI.',\n\t\t\tmodel: options?.model,\n\t\t\ttemperature: options?.temperature || 0.3\n\t\t});\n\t\tconst timestamp = new Date();\n\t\tconst memory = await Promise.all((summary?.facts || [])?.map(async ([owner, fact]: [string, string]) => {\n\t\t\tconst e = await Promise.all([this.embedding(owner), this.embedding(`${owner}: ${fact}`)]);\n\t\t\treturn {owner, fact, embeddings: [e[0][0].embedding, e[1][0].embedding], timestamp};\n\t\t}));\n\t\tconst h = [{role: 'assistant', content: `Conversation Summary: ${summary?.summary}`, timestamp: Date.now()}, ...recent];\n\t\tif(system) h.splice(0, 0, system);\n\t\treturn {history: <any>h, memory};\n\t}\n\n\t/**\n\t * Compare the difference between embeddings (calculates the angle between two vectors)\n\t * @param {number[]} v1 First embedding / vector comparison\n\t * @param {number[]} v2 Second embedding / vector for comparison\n\t * @returns {number} Similarity values 0-1: 0 = unique, 1 = identical\n\t */\n\tcosineSimilarity(v1: number[], v2: number[]): number {\n\t\tif (v1.length !== v2.length) throw new Error('Vectors must be same length');\n\t\tlet dotProduct = 0, normA = 0, normB = 0;\n\t\tfor (let i = 0; i < v1.length; i++) {\n\t\t\tdotProduct += v1[i] * v2[i];\n\t\t\tnormA += v1[i] * v1[i];\n\t\t\tnormB += v2[i] * v2[i];\n\t\t}\n\t\tconst denominator = Math.sqrt(normA) * Math.sqrt(normB);\n\t\treturn denominator === 0 ? 0 : dotProduct / denominator;\n\t}\n\n\t/**\n\t * Chunk text into parts for AI digestion\n\t * @param {object | string} target Item that will be chunked (objects get converted)\n\t * @param {number} maxTokens Chunking size. More = better context, less = more specific (Search by paragraphs or lines)\n\t * @param {number} overlapTokens Includes previous X tokens to provide continuity to AI (In addition to max tokens)\n\t * @returns {string[]} Chunked strings\n\t */\n\tchunk(target: object | string, maxTokens = 500, overlapTokens = 50): string[] {\n\t\tconst objString = (obj: any, path = ''): string[] => {\n\t\t\tif(!obj) return [];\n\t\t\treturn Object.entries(obj).flatMap(([key, value]) => {\n\t\t\t\tconst p = path ? `${path}${isNaN(+key) ? `.${key}` : `[${key}]`}` : key;\n\t\t\t\tif(typeof value === 'object' && !Array.isArray(value)) return objString(value, p);\n\t\t\t\treturn `${p}: ${Array.isArray(value) ? value.join(', ') : value}`;\n\t\t\t});\n\t\t};\n\t\tconst lines = typeof target === 'object' ? objString(target) : target.split('\\n');\n\t\tconst tokens = lines.flatMap(l => [...l.split(/\\s+/).filter(Boolean), '\\n']);\n\t\tconst chunks: string[] = [];\n\t\tfor(let i = 0; i < tokens.length;) {\n\t\t\tlet text = '', j = i;\n\t\t\twhile(j < tokens.length) {\n\t\t\t\tconst next = text + (text ? ' ' : '') + tokens[j];\n\t\t\t\tif(this.estimateTokens(next.replace(/\\s*\\n\\s*/g, '\\n')) > maxTokens && text) break;\n\t\t\t\ttext = next;\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tconst clean = text.replace(/\\s*\\n\\s*/g, '\\n').trim();\n\t\t\tif(clean) chunks.push(clean);\n\t\t\ti = Math.max(j - overlapTokens, j === i ? i + 1 : j);\n\t\t}\n\t\treturn chunks;\n\t}\n\n\t/**\n\t * Create a vector representation of a string\n\t * @param {object | string} target Item that will be embedded (objects get converted)\n\t * @param {maxTokens?: number, overlapTokens?: number} opts Options for embedding such as chunk sizes\n\t * @returns {Promise<Awaited<{index: number, embedding: number[], text: string, tokens: number}>[]>} Chunked embeddings\n\t */\n\tembedding(target: object | string, opts: {maxTokens?: number, overlapTokens?: number} = {}): AbortablePromise<any[]> {\n\t\tlet {maxTokens = 500, overlapTokens = 50} = opts;\n\t\tlet aborted = false;\n\t\tconst abort = () => { aborted = true; };\n\n\t\tconst embed = (text: string): Promise<number[]> => {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif(aborted) return reject(new Error('Aborted'));\n\n\t\t\t\tconst args: string[] = [\n\t\t\t\t\tjoin(dirname(fileURLToPath(import.meta.url)), 'embedder.js'),\n\t\t\t\t\t<string>this.ai.options.path,\n\t\t\t\t\tthis.ai.options?.embedder || 'bge-small-en-v1.5'\n\t\t\t\t];\n\t\t\t\tconst proc = spawn('node', args, {stdio: ['pipe', 'pipe', 'ignore']});\n\t\t\t\tproc.stdin.write(text);\n\t\t\t\tproc.stdin.end();\n\n\t\t\t\tlet output = '';\n\t\t\t\tproc.stdout.on('data', (data: Buffer) => output += data.toString());\n\t\t\t\tproc.on('close', (code: number) => {\n\t\t\t\t\tif(aborted) return reject(new Error('Aborted'));\n\t\t\t\t\tif(code === 0) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = JSON.parse(output);\n\t\t\t\t\t\t\tresolve(result.embedding);\n\t\t\t\t\t\t} catch(err) {\n\t\t\t\t\t\t\treject(new Error('Failed to parse embedding output'));\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(new Error(`Embedder process exited with code ${code}`));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tproc.on('error', reject);\n\t\t\t});\n\t\t};\n\n\t\tconst p = (async () => {\n\t\t\tconst chunks = this.chunk(target, maxTokens, overlapTokens), results: any[] = [];\n\t\t\tfor(let i = 0; i < chunks.length; i++) {\n\t\t\t\tif(aborted) break;\n\t\t\t\tconst text = chunks[i];\n\t\t\t\tconst embedding = await embed(text);\n\t\t\t\tresults.push({index: i, embedding, text, tokens: this.estimateTokens(text)});\n\t\t\t}\n\t\t\treturn results;\n\t\t})();\n\t\treturn Object.assign(p, { abort });\n\t}\n\n\t/**\n\t * Estimate variable as tokens\n\t * @param history Object to size\n\t * @returns {number} Rough token count\n\t */\n\testimateTokens(history: any): number {\n\t\tconst text = JSON.stringify(history);\n\t\treturn Math.ceil((text.length / 4) * 1.2);\n\t}\n\n\t/**\n\t * Compare the difference between two strings using tensor math\n\t * @param target Text that will be checked\n\t * @param {string} searchTerms Multiple search terms to check against target\n\t * @returns {{avg: number, max: number, similarities: number[]}} Similarity values 0-1: 0 = unique, 1 = identical\n\t */\n\tfuzzyMatch(target: string, ...searchTerms: string[]) {\n\t\tif(searchTerms.length < 2) throw new Error('Requires at least 2 strings to compare');\n\t\tconst vector = (text: string, dimensions: number = 10): number[] => {\n\t\t\treturn text.toLowerCase().split('').map((char, index) =>\n\t\t\t\t(char.charCodeAt(0) * (index + 1)) % dimensions / dimensions).slice(0, dimensions);\n\t\t}\n\t\tconst v = vector(target);\n\t\tconst similarities = searchTerms.map(t => vector(t)).map(refVector => this.cosineSimilarity(v, refVector))\n\t\treturn {avg: similarities.reduce((acc, s) => acc + s, 0) / similarities.length, max: Math.max(...similarities), similarities}\n\t}\n\n\t/**\n\t * Ask a question with JSON response\n\t * @param {string} text Text to process\n\t * @param {string} schema JSON schema the AI should match\n\t * @param {LLMRequest} options Configuration options and chat history\n\t * @returns {Promise<{} | {} | RegExpExecArray | null>}\n\t */\n\tasync json(text: string, schema: string, options?: LLMRequest): Promise<any> {\n\t\tconst code = await this.code(text, {...options, system: [\n\t\t\toptions?.system,\n\t\t\t`Only respond using JSON matching this schema:\\n\\`\\`\\`json\\n${schema}\\n\\`\\`\\``\n\t\t].filter(t => !!t).join('\\n')});\n\t\treturn code ? JSONAttemptParse(code, {}) : null;\n\t}\n\n\t/**\n\t * Create a summary of some text\n\t * @param {string} text Text to summarize\n\t * @param {number} tokens Max number of tokens\n\t * @param options LLM request options\n\t * @returns {Promise<string>} Summary\n\t */\n\tsummarize(text: string, tokens: number, options?: LLMRequest): Promise<string | null> {\n\t\treturn this.ask(text, {system: `Generate a brief summary <= ${tokens} tokens. Output nothing else`, temperature: 0.3, ...options});\n\t}\n}\n\nexport default LLM;\n","import {execSync, spawn} from 'node:child_process';\nimport {mkdtempSync} from 'node:fs';\nimport fs from 'node:fs/promises';\nimport {tmpdir} from 'node:os';\nimport * as path from 'node:path';\nimport Path, {join} from 'node:path';\nimport {AbortablePromise, Ai} from './ai.ts';\n\nexport class Audio {\n\tprivate downloads: {[key: string]: Promise<string>} = {};\n\tprivate pyannote!: string;\n\tprivate whisperModel!: string;\n\n\tconstructor(private ai: Ai) {\n\t\tif(ai.options.whisper) {\n\t\t\tthis.whisperModel = ai.options.asr || 'ggml-base.en.bin';\n\t\t\tthis.downloadAsrModel();\n\t\t}\n\n\t\tthis.pyannote = `\nimport sys\nimport json\nimport os\nfrom pyannote.audio import Pipeline\n\nos.environ['TORCH_HOME'] = r\"${ai.options.path}\"\npipeline = Pipeline.from_pretrained(\"pyannote/speaker-diarization-3.1\", token=\"${ai.options.hfToken}\")\noutput = pipeline(sys.argv[1])\n\nsegments = []\nfor turn, speaker in output.speaker_diarization:\n segments.append({\"start\": turn.start, \"end\": turn.end, \"speaker\": speaker})\n\nprint(json.dumps(segments))\n`;\n\t}\n\n\tprivate async addPunctuation(timestampData: any, llm?: boolean, cadence = 150): Promise<string> {\n\t\tconst countSyllables = (word: string): number => {\n\t\t\tword = word.toLowerCase().replace(/[^a-z]/g, '');\n\t\t\tif(word.length <= 3) return 1;\n\t\t\tconst matches = word.match(/[aeiouy]+/g);\n\t\t\tlet count = matches ? matches.length : 1;\n\t\t\tif(word.endsWith('e')) count--;\n\t\t\treturn Math.max(1, count);\n\t\t};\n\n\t\tlet result = '';\n\t\ttimestampData.transcription.filter((word, i) => {\n\t\t\tlet skip = false;\n\t\t\tconst prevWord = timestampData.transcription[i - 1];\n\t\t\tconst nextWord = timestampData.transcription[i + 1];\n\t\t\tif(!word.text && nextWord) {\n\t\t\t\tnextWord.offsets.from = word.offsets.from;\n\t\t\t\tnextWord.timestamps.from = word.offsets.from;\n\t\t\t} else if(word.text && word.text[0] != ' ' && prevWord) {\n\t\t\t\tprevWord.offsets.to = word.offsets.to;\n\t\t\t\tprevWord.timestamps.to = word.timestamps.to;\n\t\t\t\tprevWord.text += word.text;\n\t\t\t\tskip = true;\n\t\t\t}\n\t\t\treturn !!word.text && !skip;\n\t\t}).forEach((word: any) => {\n\t\t\tconst capital = /^[A-Z]/.test(word.text.trim());\n\t\t\tconst length = word.offsets.to - word.offsets.from;\n\t\t\tconst syllables = countSyllables(word.text.trim());\n\t\t\tconst expected = syllables * cadence;\n\t\t\tif(capital && length > expected * 2 && word.text[0] == ' ') result += '.';\n\t\t\tresult += word.text;\n\t\t});\n\t\tif(!llm) return result.trim();\n\t\treturn this.ai.language.ask(result, {\n\t\t\tsystem: 'Remove any misplaced punctuation from the following ASR transcript using the replace tool. Avoid modifying words unless there is an obvious typo',\n\t\t\ttemperature: 0.1,\n\t\t\ttools: [{\n\t\t\t\tname: 'replace',\n\t\t\t\tdescription: 'Use find and replace to fix errors',\n\t\t\t\targs: {\n\t\t\t\t\tfind: {type: 'string', description: 'Text to find', required: true},\n\t\t\t\t\treplace: {type: 'string', description: 'Text to replace', required: true}\n\t\t\t\t},\n\t\t\t\tfn: (args) => result = result.replace(args.find, args.replace)\n\t\t\t}]\n\t\t}).then(() => result);\n\t}\n\n\tprivate async diarizeTranscript(timestampData: any, speakers: any[], llm: boolean): Promise<string> {\n\t\tconst speakerMap = new Map();\n\t\tlet speakerCount = 0;\n\t\tspeakers.forEach((seg: any) => {\n\t\t\tif(!speakerMap.has(seg.speaker)) speakerMap.set(seg.speaker, ++speakerCount);\n\t\t});\n\n\t\tconst punctuatedText = await this.addPunctuation(timestampData, llm);\n\t\tconst sentences = punctuatedText.match(/[^.!?]+[.!?]+/g) || [punctuatedText];\n\t\tconst words = timestampData.transcription.filter((w: any) => w.text.trim());\n\n\t\t// Assign speaker to each sentence\n\t\tconst sentencesWithSpeakers = sentences.map(sentence => {\n\t\t\tsentence = sentence.trim();\n\t\t\tif(!sentence) return null;\n\n\t\t\tconst sentenceWords = sentence.toLowerCase().replace(/[^\\w\\s]/g, '').split(/\\s+/);\n\t\t\tconst speakerWordCount = new Map<number, number>();\n\n\t\t\tsentenceWords.forEach(sw => {\n\t\t\t\tconst word = words.find((w: any) => sw === w.text.trim().toLowerCase().replace(/[^\\w]/g, ''));\n\t\t\t\tif(!word) return;\n\n\t\t\t\tconst wordTime = word.offsets.from / 1000;\n\t\t\t\tconst speaker = speakers.find((seg: any) => wordTime >= seg.start && wordTime <= seg.end);\n\t\t\t\tif(speaker) {\n\t\t\t\t\tconst spkNum = speakerMap.get(speaker.speaker);\n\t\t\t\t\tspeakerWordCount.set(spkNum, (speakerWordCount.get(spkNum) || 0) + 1);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tlet bestSpeaker = 1;\n\t\t\tlet maxWords = 0;\n\t\t\tspeakerWordCount.forEach((count, speaker) => {\n\t\t\t\tif(count > maxWords) {\n\t\t\t\t\tmaxWords = count;\n\t\t\t\t\tbestSpeaker = speaker;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn {speaker: bestSpeaker, text: sentence};\n\t\t}).filter(s => s !== null);\n\n\t\t// Merge adjacent sentences from same speaker\n\t\tconst merged: Array<{speaker: number, text: string}> = [];\n\t\tsentencesWithSpeakers.forEach(item => {\n\t\t\tconst last = merged[merged.length - 1];\n\t\t\tif(last && last.speaker === item.speaker) {\n\t\t\t\tlast.text += ' ' + item.text;\n\t\t\t} else {\n\t\t\t\tmerged.push({...item});\n\t\t\t}\n\t\t});\n\n\t\tlet transcript = merged.map(item => `[Speaker ${item.speaker}]: ${item.text}`).join('\\n').trim();\n\t\tif(!llm) return transcript;\n\t\tlet chunks = this.ai.language.chunk(transcript, 500, 0);\n\t\tif(chunks.length > 4) chunks = [...chunks.slice(0, 3), <string>chunks.at(-1)];\n\t\tconst names = await this.ai.language.json(chunks.join('\\n'), '{1: \"Detected Name\", 2: \"Second Name\"}', {\n\t\t\tsystem: 'Use the following transcript to identify speakers. Only identify speakers you are positive about, dont mention speakers you are unsure about in your response',\n\t\t\ttemperature: 0.1,\n\t\t});\n\t\tObject.entries(names).forEach(([speaker, name]) => transcript = transcript.replaceAll(`[Speaker ${speaker}]`, `[${name}]`));\n\t\treturn transcript;\n\t}\n\n\tprivate runAsr(file: string, opts: {model?: string, diarization?: boolean} = {}): AbortablePromise<any> {\n\t\tlet proc: any;\n\t\tconst p = new Promise<any>((resolve, reject) => {\n\t\t\tthis.downloadAsrModel(opts.model).then(m => {\n\t\t\t\tif(opts.diarization) {\n\t\t\t\t\tlet output = path.join(path.dirname(file), 'transcript');\n\t\t\t\t\tproc = spawn(<string>this.ai.options.whisper,\n\t\t\t\t\t\t['-m', m, '-f', file, '-np', '-ml', '1', '-oj', '-of', output],\n\t\t\t\t\t\t{stdio: ['ignore', 'ignore', 'pipe']}\n\t\t\t\t\t);\n\t\t\t\t\tproc.on('error', (err: Error) => reject(err));\n\t\t\t\t\tproc.on('close', async (code: number) => {\n\t\t\t\t\t\tif(code === 0) {\n\t\t\t\t\t\t\toutput = await fs.readFile(output + '.json', 'utf-8');\n\t\t\t\t\t\t\tfs.rm(output + '.json').catch(() => { });\n\t\t\t\t\t\t\ttry { resolve(JSON.parse(output)); }\n\t\t\t\t\t\t\tcatch(e) { reject(new Error('Failed to parse whisper JSON')); }\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treject(new Error(`Exit code ${code}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tlet output = '';\n\t\t\t\t\tproc = spawn(<string>this.ai.options.whisper, ['-m', m, '-f', file, '-np', '-nt']);\n\t\t\t\t\tproc.on('error', (err: Error) => reject(err));\n\t\t\t\t\tproc.stdout.on('data', (data: Buffer) => output += data.toString());\n\t\t\t\t\tproc.on('close', async (code: number) => {\n\t\t\t\t\t\tif(code === 0) {\n\t\t\t\t\t\t\tresolve(output.trim() || null);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treject(new Error(`Exit code ${code}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\treturn <any>Object.assign(p, {abort: () => proc?.kill('SIGTERM')});\n\t}\n\n\tprivate runDiarization(file: string): AbortablePromise<any> {\n\t\tlet aborted = false, abort = () => { aborted = true; };\n\t\tconst checkPython = (cmd: string) => {\n\t\t\treturn new Promise<boolean>((resolve) => {\n\t\t\t\tconst proc = spawn(cmd, ['-W', 'ignore', '-c', 'import pyannote.audio']);\n\t\t\t\tproc.on('close', (code: number) => resolve(code === 0));\n\t\t\t\tproc.on('error', () => resolve(false));\n\t\t\t});\n\t\t};\n\t\tconst p = Promise.all<any>([\n\t\t\tcheckPython('python'),\n\t\t\tcheckPython('python3'),\n\t\t]).then(<any>(async ([p, p3]: [boolean, boolean]) => {\n\t\t\tif(aborted) return;\n\t\t\tif(!p && !p3) throw new Error('Pyannote is not installed: pip install pyannote.audio');\n\t\t\tconst binary = p3 ? 'python3' : 'python';\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif(aborted) return;\n\t\t\t\tlet output = '';\n\t\t\t\tconst proc = spawn(binary, ['-W', 'ignore', '-c', this.pyannote, file]);\n\t\t\t\tproc.stdout.on('data', (data: Buffer) => output += data.toString());\n\t\t\t\tproc.stderr.on('data', (data: Buffer) => console.error(data.toString()));\n\t\t\t\tproc.on('close', (code: number) => {\n\t\t\t\t\tif(code === 0) {\n\t\t\t\t\t\ttry { resolve(JSON.parse(output)); }\n\t\t\t\t\t\tcatch (err) { reject(new Error('Failed to parse diarization output')); }\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(new Error(`Python process exited with code ${code}`));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tproc.on('error', reject);\n\t\t\t\tabort = () => proc.kill('SIGTERM');\n\t\t\t});\n\t\t}));\n\t\treturn <any>Object.assign(p, {abort});\n\t}\n\n\tasr(file: string, options: { model?: string; diarization?: boolean | 'llm' } = {}): AbortablePromise<string | null> {\n\t\tif(!this.ai.options.whisper) throw new Error('Whisper not configured');\n\n\t\tconst tmp = join(mkdtempSync(join(tmpdir(), 'audio-')), 'converted.wav');\n\t\texecSync(`ffmpeg -i \"${file}\" -ar 16000 -ac 1 -f wav \"${tmp}\"`, { stdio: 'ignore' });\n\t\tconst clean = () => fs.rm(Path.dirname(tmp), {recursive: true, force: true}).catch(() => {});\n\n\t\tif(!options.diarization) return this.runAsr(tmp, {model: options.model});\n\t\tconst timestamps = this.runAsr(tmp, {model: options.model, diarization: true});\n\t\tconst diarization = this.runDiarization(tmp);\n\t\tlet aborted = false, abort = () => {\n\t\t\taborted = true;\n\t\t\ttimestamps.abort();\n\t\t\tdiarization.abort();\n\t\t\tclean();\n\t\t};\n\n\t\tconst response = Promise.allSettled([timestamps, diarization]).then(async ([ts, d]) => {\n\t\t\tif(ts.status == 'rejected') throw new Error('Whisper.cpp timestamps:\\n' + ts.reason);\n\t\t\tif(d.status == 'rejected') throw new Error('Pyannote:\\n' + d.reason);\n\t\t\tif(aborted || !options.diarization) return ts.value;\n\t\t\treturn this.diarizeTranscript(ts.value, d.value, options.diarization == 'llm');\n\t\t}).finally(() => clean());\n\t\treturn <any>Object.assign(response, {abort});\n\t}\n\n\tasync downloadAsrModel(model: string = this.whisperModel): Promise<string> {\n\t\tif(!this.ai.options.whisper) throw new Error('Whisper not configured');\n\t\tif(!model.endsWith('.bin')) model += '.bin';\n\t\tconst p = Path.join(<string>this.ai.options.path, model);\n\t\tif(await fs.stat(p).then(() => true).catch(() => false)) return p;\n\t\tif(!!this.downloads[model]) return this.downloads[model];\n\t\tthis.downloads[model] = fetch(`https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${model}`)\n\t\t\t.then(resp => resp.arrayBuffer())\n\t\t\t.then(arr => Buffer.from(arr)).then(async buffer => {\n\t\t\t\tawait fs.writeFile(p, buffer);\n\t\t\t\tdelete this.downloads[model];\n\t\t\t\treturn p;\n\t\t\t});\n\t\treturn this.downloads[model];\n\t}\n}\n","import {createWorker} from 'tesseract.js';\nimport {AbortablePromise, Ai} from './ai.ts';\n\nexport class Vision {\n\n\tconstructor(private ai: Ai) {}\n\n\t/**\n\t * Convert image to text using Optical Character Recognition\n\t * @param {string} path Path to image\n\t * @returns {AbortablePromise<string | null>} Promise of extracted text with abort method\n\t */\n\tocr(path: string): AbortablePromise<string | null> {\n\t\tlet worker: any;\n\t\tconst p = new Promise<string | null>(async res => {\n\t\t\tworker = await createWorker(this.ai.options.ocr || 'eng', 2, {cachePath: this.ai.options.path});\n\t\t\tconst {data} = await worker.recognize(path);\n\t\t\tawait worker.terminate();\n\t\t\tres(data.text.trim() || null);\n\t\t});\n\t\treturn Object.assign(p, {abort: () => worker?.terminate()});\n\t}\n}\n","import * as os from 'node:os';\nimport LLM, {AnthropicConfig, OllamaConfig, OpenAiConfig, LLMRequest} from './llm';\nimport { Audio } from './audio.ts';\nimport {Vision} from './vision.ts';\n\nexport type AbortablePromise<T> = Promise<T> & {\n\tabort: () => any\n};\n\nexport type AiOptions = {\n\t/** Token to pull models from hugging face */\n\thfToken?: string;\n\t/** Path to models */\n\tpath?: string;\n\t/** Whisper ASR model: ggml-tiny.en.bin, ggml-base.en.bin */\n\tasr?: string;\n\t/** Embedding model: all-MiniLM-L6-v2, bge-small-en-v1.5, bge-large-en-v1.5 */\n\tembedder?: string;\n\t/** Large language models, first is default */\n\tllm?: Omit<LLMRequest, 'model'> & {\n\t\tmodels: {[model: string]: AnthropicConfig | OllamaConfig | OpenAiConfig};\n\t}\n\t/** OCR model: eng, eng_best, eng_fast */\n\tocr?: string;\n\t/** Whisper binary */\n\twhisper?: string;\n}\n\nexport class Ai {\n\t/** Audio processing AI */\n\taudio!: Audio;\n\t/** Language processing AI */\n\tlanguage!: LLM;\n\t/** Vision processing AI */\n\tvision!: Vision;\n\n\tconstructor(public readonly options: AiOptions) {\n\t\tif(!options.path) options.path = os.tmpdir();\n\t\tprocess.env.TRANSFORMERS_CACHE = options.path;\n\t\tthis.audio = new Audio(this);\n\t\tthis.language = new LLM(this);\n\t\tthis.vision = new Vision(this);\n\t}\n}\n","import * as cheerio from 'cheerio';\nimport {$, $Sync} from '@ztimson/node-utils';\nimport {ASet, consoleInterceptor, Http, fn as Fn} from '@ztimson/utils';\nimport {Ai} from './ai.ts';\nimport {LLMRequest} from './llm.ts';\n\nexport type AiToolArg = {[key: string]: {\n\t/** Argument type */\n\ttype: 'array' | 'boolean' | 'number' | 'object' | 'string',\n\t/** Argument description */\n\tdescription: string,\n\t/** Required argument */\n\trequired?: boolean;\n\t/** Default value */\n\tdefault?: any,\n\t/** Options */\n\tenum?: string[],\n\t/** Minimum value or length */\n\tmin?: number,\n\t/** Maximum value or length */\n\tmax?: number,\n\t/** Match pattern */\n\tpattern?: string,\n\t/** Child arguments */\n\titems?: {[key: string]: AiToolArg}\n}}\n\nexport type AiTool = {\n\t/** Tool ID / Name - Must be snail_case */\n\tname: string,\n\t/** Tool description / prompt */\n\tdescription: string,\n\t/** Tool arguments */\n\targs?: AiToolArg,\n\t/** Callback function */\n\tfn: (args: any, stream: LLMRequest['stream'], ai: Ai) => any | Promise<any>,\n};\n\nexport const CliTool: AiTool = {\n\tname: 'cli',\n\tdescription: 'Use the command line interface, returns any output',\n\targs: {command: {type: 'string', description: 'Command to run', required: true}},\n\tfn: (args: {command: string}) => $`${args.command}`\n}\n\nexport const DateTimeTool: AiTool = {\n\tname: 'get_datetime',\n\tdescription: 'Get current UTC date / time',\n\targs: {},\n\tfn: async () => new Date().toUTCString()\n}\n\nexport const ExecTool: AiTool = {\n\tname: 'exec',\n\tdescription: 'Run code/scripts',\n\targs: {\n\t\tlanguage: {type: 'string', description: 'Execution language', enum: ['cli', 'node', 'python'], required: true},\n\t\tcode: {type: 'string', description: 'Code to execute', required: true}\n\t},\n\tfn: async (args, stream, ai) => {\n\t\ttry {\n\t\t\tswitch(args.type) {\n\t\t\t\tcase 'bash':\n\t\t\t\t\treturn await CliTool.fn({command: args.code}, stream, ai);\n\t\t\t\tcase 'node':\n\t\t\t\t\treturn await JSTool.fn({code: args.code}, stream, ai);\n\t\t\t\tcase 'python': {\n\t\t\t\t\treturn await PythonTool.fn({code: args.code}, stream, ai);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch(err: any) {\n\t\t\treturn {error: err?.message || err.toString()};\n\t\t}\n\t}\n}\n\nexport const FetchTool: AiTool = {\n\tname: 'fetch',\n\tdescription: 'Make HTTP request to URL',\n\targs: {\n\t\turl: {type: 'string', description: 'URL to fetch', required: true},\n\t\tmethod: {type: 'string', description: 'HTTP method to use', enum: ['GET', 'POST', 'PUT', 'DELETE'], default: 'GET'},\n\t\theaders: {type: 'object', description: 'HTTP headers to send', default: {}},\n\t\tbody: {type: 'object', description: 'HTTP body to send'},\n\t},\n\tfn: (args: {\n\t\turl: string;\n\t\tmethod: 'GET' | 'POST' | 'PUT' | 'DELETE';\n\t\theaders: {[key: string]: string};\n\t\tbody: any;\n\t}) => new Http({url: args.url, headers: args.headers}).request({method: args.method || 'GET', body: args.body})\n}\n\nexport const JSTool: AiTool = {\n\tname: 'exec_javascript',\n\tdescription: 'Execute commonjs javascript',\n\targs: {\n\t\tcode: {type: 'string', description: 'CommonJS javascript', required: true}\n\t},\n\tfn: async (args: {code: string}) => {\n\t\tconst console = consoleInterceptor(null);\n\t\tconst resp = await Fn<any>({console}, args.code, true).catch((err: any) => console.output.error.push(err));\n\t\treturn {...console.output, return: resp, stdout: undefined, stderr: undefined};\n\t}\n}\n\nexport const PythonTool: AiTool = {\n\tname: 'exec_javascript',\n\tdescription: 'Execute commonjs javascript',\n\targs: {\n\t\tcode: {type: 'string', description: 'CommonJS javascript', required: true}\n\t},\n\tfn: async (args: {code: string}) => ({result: $Sync`python -c \"${args.code}\"`})\n}\n\nexport const ReadWebpageTool: AiTool = {\n\tname: 'read_webpage',\n\tdescription: 'Extract clean, structured content from a webpage. Use after web_search to read specific URLs',\n\targs: {\n\t\turl: {type: 'string', description: 'URL to extract content from', required: true},\n\t\tfocus: {type: 'string', description: 'Optional: What aspect to focus on (e.g., \"pricing\", \"features\", \"contact info\")'}\n\t},\n\tfn: async (args: {url: string; focus?: string}) => {\n\t\tconst html = await fetch(args.url, {headers: {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64)\"}})\n\t\t\t.then(r => r.text()).catch(err => {throw new Error(`Failed to fetch: ${err.message}`)});\n\n\t\tconst $ = cheerio.load(html);\n\t\t$('script, style, nav, footer, header, aside, iframe, noscript, [role=\"navigation\"], [role=\"banner\"], .ad, .ads, .cookie, .popup').remove();\n\t\tconst metadata = {\n\t\t\ttitle: $('meta[property=\"og:title\"]').attr('content') || $('title').text() || '',\n\t\t\tdescription: $('meta[name=\"description\"]').attr('content') || $('meta[property=\"og:description\"]').attr('content') || '',\n\t\t};\n\n\t\tlet content = '';\n\t\tconst contentSelectors = ['article', 'main', '[role=\"main\"]', '.content', '.post', '.entry', 'body'];\n\t\tfor (const selector of contentSelectors) {\n\t\t\tconst el = $(selector).first();\n\t\t\tif (el.length && el.text().trim().length > 200) {\n\t\t\t\tcontent = el.text();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!content) content = $('body').text();\n\t\tcontent = content.replace(/\\s+/g, ' ').trim().slice(0, 8000);\n\n\t\treturn {url: args.url, title: metadata.title.trim(), description: metadata.description.trim(), content, focus: args.focus};\n\t}\n}\n\nexport const WebSearchTool: AiTool = {\n\tname: 'web_search',\n\tdescription: 'Use duckduckgo (anonymous) to find find relevant online resources. Returns a list of URLs that works great with the `read_webpage` tool',\n\targs: {\n\t\tquery: {type: 'string', description: 'Search string', required: true},\n\t\tlength: {type: 'string', description: 'Number of results to return', default: 5},\n\t},\n\tfn: async (args: {\n\t\tquery: string;\n\t\tlength: number;\n\t}) => {\n\t\tconst html = await fetch(`https://html.duckduckgo.com/html/?q=${encodeURIComponent(args.query)}`, {\n\t\t\theaders: {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64)\", \"Accept-Language\": \"en-US,en;q=0.9\"}\n\t\t}).then(resp => resp.text());\n\t\tlet match, regex = /<a .*?href=\"(.+?)\".+?<\\/a>/g;\n\t\tconst results = new ASet<string>();\n\t\twhile((match = regex.exec(html)) !== null) {\n\t\t\tlet url = /uddg=(.+)&amp?/.exec(decodeURIComponent(match[1]))?.[1];\n\t\t\tif(url) url = decodeURIComponent(url);\n\t\t\tif(url) results.add(url);\n\t\t\tif(results.size >= (args.length || 5)) break;\n\t\t}\n\t\treturn results;\n\t}\n}\n"],"names":["LLMProvider","Anthropic","ai","apiToken","model","anthropic","history","timestamp","messages","h","textContent","c","m","i","message","options","controller","res","tools","requestParams","t","objectMap","key","value","resp","isFirstMessage","err","chunk","text","last","JSONAttemptParse","toolCalls","results","toolCall","tool","findByProp","result","JSONSanitize","OpenAi","host","token","openAI","clean","tc","record","h2","rest","rej","args","LLM","config","abort","search","query","subject","limit","o","q","a","b","relevant","compressed","updated","m2","codeBlock","max","min","keep","tokens","system","recent","process","summary","memory","owner","fact","e","v1","v2","dotProduct","normA","normB","denominator","target","maxTokens","overlapTokens","objString","obj","path","p","l","chunks","j","next","opts","aborted","embed","resolve","reject","join","dirname","fileURLToPath","_documentCurrentScript","proc","spawn","output","data","code","embedding","searchTerms","vector","dimensions","char","index","v","similarities","refVector","acc","s","schema","Audio","timestampData","llm","cadence","countSyllables","word","matches","count","skip","prevWord","nextWord","capital","length","expected","speakers","speakerMap","speakerCount","seg","punctuatedText","sentences","words","w","sentencesWithSpeakers","sentence","sentenceWords","speakerWordCount","sw","wordTime","speaker","spkNum","bestSpeaker","maxWords","merged","item","transcript","names","name","file","fs","checkPython","cmd","p3","binary","tmp","mkdtempSync","tmpdir","execSync","Path","timestamps","diarization","response","ts","d","arr","buffer","Vision","worker","createWorker","Ai","os","CliTool","$","DateTimeTool","ExecTool","stream","JSTool","PythonTool","FetchTool","Http","console","consoleInterceptor","Fn","$Sync","ReadWebpageTool","html","r","cheerio","metadata","content","contentSelectors","selector","el","WebSearchTool","match","regex","ASet","url"],"mappings":"qvBAGO,MAAeA,C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,CAAA,CAAC,EAEhF,GAAI,MAAO1J,GAGL,CACL,MAAMkJ,EAAO,MAAM,MAAM,uCAAuC,mBAAmBlJ,EAAK,KAAK,CAAC,GAAI,CACjG,QAAS,CAAC,aAAc,4CAA6C,kBAAmB,gBAAA,CAAgB,CACxG,EAAE,KAAKxB,GAAQA,EAAK,MAAM,EAC3B,IAAImL,EAAOC,EAAQ,8BACnB,MAAM5K,EAAU,IAAI6K,OACpB,MAAOF,EAAQC,EAAM,KAAKV,CAAI,KAAO,MAAM,CAC1C,IAAIY,EAAM,iBAAiB,KAAK,mBAAmBH,EAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAGjE,GAFGG,IAAKA,EAAM,mBAAmBA,CAAG,GACjCA,GAAK9K,EAAQ,IAAI8K,CAAG,EACpB9K,EAAQ,OAASgB,EAAK,QAAU,GAAI,KACxC,CACA,OAAOhB,CACR,CACD"}
1
+ {"version":3,"file":"index.js","sources":["../src/provider.ts","../src/antrhopic.ts","../src/open-ai.ts","../src/llm.ts","../src/audio.ts","../src/vision.ts","../src/ai.ts","../src/tools.ts"],"sourcesContent":["import {AbortablePromise} from './ai.ts';\nimport {LLMMessage, LLMRequest} from './llm.ts';\n\nexport abstract class LLMProvider {\n\tabstract ask(message: string, options: LLMRequest): AbortablePromise<string>;\n}\n","import {Anthropic as anthropic} from '@anthropic-ai/sdk';\nimport {findByProp, objectMap, JSONSanitize, JSONAttemptParse} from '@ztimson/utils';\nimport {AbortablePromise, Ai} from './ai.ts';\nimport {LLMMessage, LLMRequest} from './llm.ts';\nimport {LLMProvider} from './provider.ts';\n\nexport class Anthropic extends LLMProvider {\n\tclient!: anthropic;\n\n\tconstructor(public readonly ai: Ai, public readonly apiToken: string, public model: string) {\n\t\tsuper();\n\t\tthis.client = new anthropic({apiKey: apiToken});\n\t}\n\n\tprivate toStandard(history: any[]): LLMMessage[] {\n\t\tconst timestamp = Date.now();\n\t\tconst messages: LLMMessage[] = [];\n\t\tfor(let h of history) {\n\t\t\tif(typeof h.content == 'string') {\n\t\t\t\tmessages.push(<any>{timestamp, ...h});\n\t\t\t} else {\n\t\t\t\tconst textContent = h.content?.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\\n\\n');\n\t\t\t\tif(textContent) messages.push({timestamp, role: h.role, content: textContent});\n\t\t\t\th.content.forEach((c: any) => {\n\t\t\t\t\tif(c.type == 'tool_use') {\n\t\t\t\t\t\tmessages.push({timestamp, role: 'tool', id: c.id, name: c.name, args: c.input, content: undefined});\n\t\t\t\t\t} else if(c.type == 'tool_result') {\n\t\t\t\t\t\tconst m: any = messages.findLast(m => (<any>m).id == c.tool_use_id);\n\t\t\t\t\t\tif(m) m[c.is_error ? 'error' : 'content'] = c.content;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn messages;\n\t}\n\n\tprivate fromStandard(history: LLMMessage[]): any[] {\n\t\tfor(let i = 0; i < history.length; i++) {\n\t\t\tif(history[i].role == 'tool') {\n\t\t\t\tconst h: any = history[i];\n\t\t\t\thistory.splice(i, 1,\n\t\t\t\t\t{role: 'assistant', content: [{type: 'tool_use', id: h.id, name: h.name, input: h.args}]},\n\t\t\t\t\t{role: 'user', content: [{type: 'tool_result', tool_use_id: h.id, is_error: !!h.error, content: h.error || h.content}]}\n\t\t\t\t)\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn history.map(({timestamp, ...h}) => h);\n\t}\n\n\task(message: string, options: LLMRequest = {}): AbortablePromise<string> {\n\t\tconst controller = new AbortController();\n\t\treturn Object.assign(new Promise<any>(async (res) => {\n\t\t\tlet history = this.fromStandard([...options.history || [], {role: 'user', content: message, timestamp: Date.now()}]);\n\t\t\tconst tools = options.tools || this.ai.options.llm?.tools || [];\n\t\t\tconst requestParams: any = {\n\t\t\t\tmodel: options.model || this.model,\n\t\t\t\tmax_tokens: options.max_tokens || this.ai.options.llm?.max_tokens || 4096,\n\t\t\t\tsystem: options.system || this.ai.options.llm?.system || '',\n\t\t\t\ttemperature: options.temperature || this.ai.options.llm?.temperature || 0.7,\n\t\t\t\ttools: tools.map(t => ({\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tdescription: t.description,\n\t\t\t\t\tinput_schema: {\n\t\t\t\t\t\ttype: 'object',\n\t\t\t\t\t\tproperties: t.args ? objectMap(t.args, (key, value) => ({...value, required: undefined})) : {},\n\t\t\t\t\t\trequired: t.args ? Object.entries(t.args).filter(t => t[1].required).map(t => t[0]) : []\n\t\t\t\t\t},\n\t\t\t\t\tfn: undefined\n\t\t\t\t})),\n\t\t\t\tmessages: history,\n\t\t\t\tstream: !!options.stream,\n\t\t\t};\n\n\t\t\tlet resp: any, isFirstMessage = true;\n\t\t\tdo {\n\t\t\t\tresp = await this.client.messages.create(requestParams).catch(err => {\n\t\t\t\t\terr.message += `\\n\\nMessages:\\n${JSON.stringify(history, null, 2)}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t});\n\n\t\t\t\t// Streaming mode\n\t\t\t\tif(options.stream) {\n\t\t\t\t\tif(!isFirstMessage) options.stream({text: '\\n\\n'});\n\t\t\t\t\telse isFirstMessage = false;\n\t\t\t\t\tresp.content = [];\n\t\t\t\t\tfor await (const chunk of resp) {\n\t\t\t\t\t\tif(controller.signal.aborted) break;\n\t\t\t\t\t\tif(chunk.type === 'content_block_start') {\n\t\t\t\t\t\t\tif(chunk.content_block.type === 'text') {\n\t\t\t\t\t\t\t\tresp.content.push({type: 'text', text: ''});\n\t\t\t\t\t\t\t} else if(chunk.content_block.type === 'tool_use') {\n\t\t\t\t\t\t\t\tresp.content.push({type: 'tool_use', id: chunk.content_block.id, name: chunk.content_block.name, input: <any>''});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if(chunk.type === 'content_block_delta') {\n\t\t\t\t\t\t\tif(chunk.delta.type === 'text_delta') {\n\t\t\t\t\t\t\t\tconst text = chunk.delta.text;\n\t\t\t\t\t\t\t\tresp.content.at(-1).text += text;\n\t\t\t\t\t\t\t\toptions.stream({text});\n\t\t\t\t\t\t\t} else if(chunk.delta.type === 'input_json_delta') {\n\t\t\t\t\t\t\t\tresp.content.at(-1).input += chunk.delta.partial_json;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if(chunk.type === 'content_block_stop') {\n\t\t\t\t\t\t\tconst last = resp.content.at(-1);\n\t\t\t\t\t\t\tif(last.input != null) last.input = last.input ? JSONAttemptParse(last.input, {}) : {};\n\t\t\t\t\t\t} else if(chunk.type === 'message_stop') {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Run tools\n\t\t\t\tconst toolCalls = resp.content.filter((c: any) => c.type === 'tool_use');\n\t\t\t\tif(toolCalls.length && !controller.signal.aborted) {\n\t\t\t\t\thistory.push({role: 'assistant', content: resp.content});\n\t\t\t\t\tconst results = await Promise.all(toolCalls.map(async (toolCall: any) => {\n\t\t\t\t\t\tconst tool = tools.find(findByProp('name', toolCall.name));\n\t\t\t\t\t\tif(options.stream) options.stream({tool: toolCall.name});\n\t\t\t\t\t\tif(!tool) return {tool_use_id: toolCall.id, is_error: true, content: 'Tool not found'};\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await tool.fn(toolCall.input, options?.stream, this.ai);\n\t\t\t\t\t\t\treturn {type: 'tool_result', tool_use_id: toolCall.id, content: JSONSanitize(result)};\n\t\t\t\t\t\t} catch (err: any) {\n\t\t\t\t\t\t\treturn {type: 'tool_result', tool_use_id: toolCall.id, is_error: true, content: err?.message || err?.toString() || 'Unknown'};\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t\thistory.push({role: 'user', content: results});\n\t\t\t\t\trequestParams.messages = history;\n\t\t\t\t}\n\t\t\t} while (!controller.signal.aborted && resp.content.some((c: any) => c.type === 'tool_use'));\n\t\t\thistory.push({role: 'assistant', content: resp.content.filter((c: any) => c.type == 'text').map((c: any) => c.text).join('\\n\\n')});\n\t\t\thistory = this.toStandard(history);\n\n\t\t\tif(options.stream) options.stream({done: true});\n\t\t\tif(options.history) options.history.splice(0, options.history.length, ...history);\n\t\t\tres(history.at(-1)?.content);\n\t\t}), {abort: () => controller.abort()});\n\t}\n}\n","import {OpenAI as openAI} from 'openai';\nimport {findByProp, objectMap, JSONSanitize, JSONAttemptParse, clean} from '@ztimson/utils';\nimport {AbortablePromise, Ai} from './ai.ts';\nimport {LLMMessage, LLMRequest} from './llm.ts';\nimport {LLMProvider} from './provider.ts';\n\nexport class OpenAi extends LLMProvider {\n\tclient!: openAI;\n\n\tconstructor(public readonly ai: Ai, public readonly host: string | null, public readonly token: string, public model: string) {\n\t\tsuper();\n\t\tthis.client = new openAI(clean({\n\t\t\tbaseURL: host,\n\t\t\tapiKey: token || host ? 'ignored' : undefined\n\t\t}));\n\t}\n\n\tprivate toStandard(history: any[]): LLMMessage[] {\n\t\tfor(let i = 0; i < history.length; i++) {\n\t\t\tconst h = history[i];\n\t\t\tif(h.role === 'assistant' && h.tool_calls) {\n\t\t\t\tconst tools = h.tool_calls.map((tc: any) => ({\n\t\t\t\t\trole: 'tool',\n\t\t\t\t\tid: tc.id,\n\t\t\t\t\tname: tc.function.name,\n\t\t\t\t\targs: JSONAttemptParse(tc.function.arguments, {}),\n\t\t\t\t\ttimestamp: h.timestamp\n\t\t\t\t}));\n\t\t\t\thistory.splice(i, 1, ...tools);\n\t\t\t\ti += tools.length - 1;\n\t\t\t} else if(h.role === 'tool' && h.content) {\n\t\t\t\tconst record = history.find(h2 => h.tool_call_id == h2.id);\n\t\t\t\tif(record) {\n\t\t\t\t\tif(h.content.includes('\"error\":')) record.error = h.content;\n\t\t\t\t\telse record.content = h.content;\n\t\t\t\t}\n\t\t\t\thistory.splice(i, 1);\n\t\t\t\ti--;\n\t\t\t}\n\t\t\tif(!history[i]?.timestamp) history[i].timestamp = Date.now();\n\t\t}\n\t\treturn history;\n\t}\n\n\tprivate fromStandard(history: LLMMessage[]): any[] {\n\t\treturn history.reduce((result, h) => {\n\t\t\tif(h.role === 'tool') {\n\t\t\t\tresult.push({\n\t\t\t\t\trole: 'assistant',\n\t\t\t\t\tcontent: null,\n\t\t\t\t\ttool_calls: [{ id: h.id, type: 'function', function: { name: h.name, arguments: JSON.stringify(h.args) } }],\n\t\t\t\t\trefusal: null,\n\t\t\t\t\tannotations: []\n\t\t\t\t}, {\n\t\t\t\t\trole: 'tool',\n\t\t\t\t\ttool_call_id: h.id,\n\t\t\t\t\tcontent: h.error || h.content\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst {timestamp, ...rest} = h;\n\t\t\t\tresult.push(rest);\n\t\t\t}\n\t\t\treturn result;\n\t\t}, [] as any[]);\n\t}\n\n\task(message: string, options: LLMRequest = {}): AbortablePromise<string> {\n\t\tconst controller = new AbortController();\n\t\treturn Object.assign(new Promise<any>(async (res, rej) => {\n\t\t\tif(options.system) {\n\t\t\t\tif(options.history?.[0]?.role != 'system') options.history?.splice(0, 0, {role: 'system', content: options.system, timestamp: Date.now()});\n\t\t\t\telse options.history[0].content = options.system;\n\t\t\t}\n\t\t\tlet history = this.fromStandard([...options.history || [], {role: 'user', content: message, timestamp: Date.now()}]);\n\t\t\tconst tools = options.tools || this.ai.options.llm?.tools || [];\n\t\t\tconst requestParams: any = {\n\t\t\t\tmodel: options.model || this.model,\n\t\t\t\tmessages: history,\n\t\t\t\tstream: !!options.stream,\n\t\t\t\tmax_tokens: options.max_tokens || this.ai.options.llm?.max_tokens || 4096,\n\t\t\t\ttemperature: options.temperature || this.ai.options.llm?.temperature || 0.7,\n\t\t\t\ttools: tools.map(t => ({\n\t\t\t\t\ttype: 'function',\n\t\t\t\t\tfunction: {\n\t\t\t\t\t\tname: t.name,\n\t\t\t\t\t\tdescription: t.description,\n\t\t\t\t\t\tparameters: {\n\t\t\t\t\t\t\ttype: 'object',\n\t\t\t\t\t\t\tproperties: t.args ? objectMap(t.args, (key, value) => ({...value, required: undefined})) : {},\n\t\t\t\t\t\t\trequired: t.args ? Object.entries(t.args).filter(t => t[1].required).map(t => t[0]) : []\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}))\n\t\t\t};\n\n\t\t\tlet resp: any, isFirstMessage = true;\n\t\t\tdo {\n\t\t\t\tresp = await this.client.chat.completions.create(requestParams).catch(err => {\n\t\t\t\t\terr.message += `\\n\\nMessages:\\n${JSON.stringify(history, null, 2)}`;\n\t\t\t\t\tthrow err;\n\t\t\t\t});\n\n\t\t\t\tif(options.stream) {\n\t\t\t\t\tif(!isFirstMessage) options.stream({text: '\\n\\n'});\n\t\t\t\t\telse isFirstMessage = false;\n\t\t\t\t\tresp.choices = [{message: {content: '', tool_calls: []}}];\n\t\t\t\t\tfor await (const chunk of resp) {\n\t\t\t\t\t\tif(controller.signal.aborted) break;\n\t\t\t\t\t\tif(chunk.choices[0].delta.content) {\n\t\t\t\t\t\t\tresp.choices[0].message.content += chunk.choices[0].delta.content;\n\t\t\t\t\t\t\toptions.stream({text: chunk.choices[0].delta.content});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(chunk.choices[0].delta.tool_calls) {\n\t\t\t\t\t\t\tresp.choices[0].message.tool_calls = chunk.choices[0].delta.tool_calls;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst toolCalls = resp.choices[0].message.tool_calls || [];\n\t\t\t\tif(toolCalls.length && !controller.signal.aborted) {\n\t\t\t\t\thistory.push(resp.choices[0].message);\n\t\t\t\t\tconst results = await Promise.all(toolCalls.map(async (toolCall: any) => {\n\t\t\t\t\t\tconst tool = tools?.find(findByProp('name', toolCall.function.name));\n\t\t\t\t\t\tif(options.stream) options.stream({tool: toolCall.function.name});\n\t\t\t\t\t\tif(!tool) return {role: 'tool', tool_call_id: toolCall.id, content: '{\"error\": \"Tool not found\"}'};\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst args = JSONAttemptParse(toolCall.function.arguments, {});\n\t\t\t\t\t\t\tconst result = await tool.fn(args, options.stream, this.ai);\n\t\t\t\t\t\t\treturn {role: 'tool', tool_call_id: toolCall.id, content: JSONSanitize(result)};\n\t\t\t\t\t\t} catch (err: any) {\n\t\t\t\t\t\t\treturn {role: 'tool', tool_call_id: toolCall.id, content: JSONSanitize({error: err?.message || err?.toString() || 'Unknown'})};\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t\thistory.push(...results);\n\t\t\t\t\trequestParams.messages = history;\n\t\t\t\t}\n\t\t\t} while (!controller.signal.aborted && resp.choices?.[0]?.message?.tool_calls?.length);\n\t\t\thistory.push({role: 'assistant', content: resp.choices[0].message.content || ''});\n\t\t\thistory = this.toStandard(history);\n\n\t\t\tif(options.stream) options.stream({done: true});\n\t\t\tif(options.history) options.history.splice(0, options.history.length, ...history);\n\t\t\tres(history.at(-1)?.content);\n\t\t}), {abort: () => controller.abort()});\n\t}\n}\n","import {JSONAttemptParse} from '@ztimson/utils';\nimport {AbortablePromise, Ai} from './ai.ts';\nimport {Anthropic} from './antrhopic.ts';\nimport {OpenAi} from './open-ai.ts';\nimport {LLMProvider} from './provider.ts';\nimport {AiTool} from './tools.ts';\nimport {fileURLToPath} from 'url';\nimport {dirname, join} from 'path';\nimport { spawn } from 'node:child_process';\n\nexport type AnthropicConfig = {proto: 'anthropic', token: string};\nexport type OllamaConfig = {proto: 'ollama', host: string};\nexport type OpenAiConfig = {proto: 'openai', host?: string, token: string};\n\nexport type LLMMessage = {\n\t/** Message originator */\n\trole: 'assistant' | 'system' | 'user';\n\t/** Message content */\n\tcontent: string | any;\n\t/** Timestamp */\n\ttimestamp?: number;\n} | {\n\t/** Tool call */\n\trole: 'tool';\n\t/** Unique ID for call */\n\tid: string;\n\t/** Tool that was run */\n\tname: string;\n\t/** Tool arguments */\n\targs: any;\n\t/** Tool result */\n\tcontent: undefined | string;\n\t/** Tool error */\n\terror?: undefined | string;\n\t/** Timestamp */\n\ttimestamp?: number;\n}\n\n/** Background information the AI will be fed */\nexport type LLMMemory = {\n\t/** What entity is this fact about */\n\towner: string;\n\t/** The information that will be remembered */\n\tfact: string;\n\t/** Owner and fact embedding vector */\n\tembeddings: [number[], number[]];\n}\n\nexport type LLMRequest = {\n\t/** System prompt */\n\tsystem?: string;\n\t/** Message history */\n\thistory?: LLMMessage[];\n\t/** Max tokens for request */\n\tmax_tokens?: number;\n\t/** 0 = Rigid Logic, 1 = Balanced, 2 = Hyper Creative **/\n\ttemperature?: number;\n\t/** Available tools */\n\ttools?: AiTool[];\n\t/** LLM model */\n\tmodel?: string;\n\t/** Stream response */\n\tstream?: (chunk: {text?: string, tool?: string, done?: true}) => any;\n\t/** Compress old messages in the chat to free up context */\n\tcompress?: {\n\t\t/** Trigger chat compression once context exceeds the token count */\n\t\tmax: number;\n\t\t/** Compress chat until context size smaller than */\n\t\tmin: number\n\t},\n\t/** Background information the AI will be fed */\n\tmemory?: LLMMemory[],\n}\n\nclass LLM {\n\tdefaultModel!: string;\n\tmodels: {[model: string]: LLMProvider} = {};\n\n\tconstructor(public readonly ai: Ai) {\n\t\tif(!ai.options.llm?.models) return;\n\t\tObject.entries(ai.options.llm.models).forEach(([model, config]) => {\n\t\t\tif(!this.defaultModel) this.defaultModel = model;\n\t\t\tif(config.proto == 'anthropic') this.models[model] = new Anthropic(this.ai, config.token, model);\n\t\t\telse if(config.proto == 'ollama') this.models[model] = new OpenAi(this.ai, config.host, 'not-needed', model);\n\t\t\telse if(config.proto == 'openai') this.models[model] = new OpenAi(this.ai, config.host || null, config.token, model);\n\t\t});\n\t}\n\n\t/**\n\t * Chat with LLM\n\t * @param {string} message Question\n\t * @param {LLMRequest} options Configuration options and chat history\n\t * @returns {{abort: () => void, response: Promise<string>}} Function to abort response and chat history\n\t */\n\task(message: string, options: LLMRequest = {}): AbortablePromise<string> {\n\t\toptions = <any>{\n\t\t\tsystem: '',\n\t\t\ttemperature: 0.8,\n\t\t\t...this.ai.options.llm,\n\t\t\tmodels: undefined,\n\t\t\thistory: [],\n\t\t\t...options,\n\t\t}\n\t\tconst m = options.model || this.defaultModel;\n\t\tif(!this.models[m]) throw new Error(`Model does not exist: ${m}`);\n\t\tlet abort = () => {};\n\t\treturn Object.assign(new Promise<string>(async res => {\n\t\t\tif(!options.history) options.history = [];\n\t\t\t// If memories were passed, find any relevant ones and add a tool for ADHOC lookups\n\t\t\tif(options.memory) {\n\t\t\t\tconst search = async (query?: string | null, subject?: string | null, limit = 10) => {\n\t\t\t\t\tconst [o, q] = await Promise.all([\n\t\t\t\t\t\tsubject ? this.embedding(subject) : Promise.resolve(null),\n\t\t\t\t\t\tquery ? this.embedding(query) : Promise.resolve(null),\n\t\t\t\t\t]);\n\t\t\t\t\treturn (options.memory || []).map(m => {\n\t\t\t\t\t\tconst score = (o ? this.cosineSimilarity(m.embeddings[0], o[0].embedding) : 0)\n\t\t\t\t\t\t\t+ (q ? this.cosineSimilarity(m.embeddings[1], q[0].embedding) : 0);\n\t\t\t\t\t\treturn {...m, score};\n\t\t\t\t\t}).toSorted((a: any, b: any) => a.score - b.score).slice(0, limit);\n\t\t\t\t}\n\n\t\t\t\toptions.system += '\\nYou have RAG memory and will be given the top_k closest memories regarding the users query. Save anything new you have learned worth remembering from the user message using the remember tool and feel free to recall memories manually.\\n';\n\t\t\t\tconst relevant = await search(message);\n\t\t\t\tif(relevant.length) options.history.push({role: 'tool', name: 'recall', id: 'auto_recall_' + Math.random().toString(), args: {}, content: 'Things I remembered:\\n' + relevant.map(m => `${m.owner}: ${m.fact}`).join('\\n')});\n\t\t\t\toptions.tools = [{\n\t\t\t\t\tname: 'recall',\n\t\t\t\t\tdescription: 'Recall the closest memories you have regarding a query using RAG',\n\t\t\t\t\targs: {\n\t\t\t\t\t\tsubject: {type: 'string', description: 'Find information by a subject topic, can be used with or without query argument'},\n\t\t\t\t\t\tquery: {type: 'string', description: 'Search memory based on a query, can be used with or without subject argument'},\n\t\t\t\t\t\ttopK: {type: 'number', description: 'Result limit, default 5'},\n\t\t\t\t\t},\n\t\t\t\t\tfn: (args) => {\n\t\t\t\t\t\tif(!args.subject && !args.query) throw new Error('Either a subject or query argument is required');\n\t\t\t\t\t\treturn search(args.query, args.subject, args.topK);\n\t\t\t\t\t}\n\t\t\t\t}, {\n\t\t\t\t\tname: 'remember',\n\t\t\t\t\tdescription: 'Store important facts user shares for future recall',\n\t\t\t\t\targs: {\n\t\t\t\t\t\towner: {type: 'string', description: 'Subject/person this fact is about'},\n\t\t\t\t\t\tfact: {type: 'string', description: 'The information to remember'}\n\t\t\t\t\t},\n\t\t\t\t\tfn: async (args) => {\n\t\t\t\t\t\tif(!options.memory) return;\n\t\t\t\t\t\tconst e = await Promise.all([\n\t\t\t\t\t\t\tthis.embedding(args.owner),\n\t\t\t\t\t\t\tthis.embedding(`${args.owner}: ${args.fact}`)\n\t\t\t\t\t\t]);\n\t\t\t\t\t\tconst newMem = {owner: args.owner, fact: args.fact, embeddings: <any>[e[0][0].embedding, e[1][0].embedding]};\n\t\t\t\t\t\toptions.memory.splice(0, options.memory.length, ...[\n\t\t\t\t\t\t\t...options.memory.filter(m => {\n\t\t\t\t\t\t\t\treturn this.cosineSimilarity(newMem.embeddings[0], m.embeddings[0]) < 0.9 && this.cosineSimilarity(newMem.embeddings[1], m.embeddings[1]) < 0.8;\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\tnewMem\n\t\t\t\t\t\t]);\n\t\t\t\t\t\treturn 'Remembered!';\n\t\t\t\t\t}\n\t\t\t\t}, ...options.tools || []];\n\t\t\t}\n\n\t\t\t// Ask\n\t\t\tconst resp = await this.models[m].ask(message, options);\n\n\t\t\t// Remove any memory calls from history\n\t\t\tif(options.memory) options.history.splice(0, options.history.length, ...options.history.filter(h => h.role != 'tool' || (h.name != 'recall' && h.name != 'remember')));\n\n\t\t\t// Compress message history\n\t\t\tif(options.compress) {\n\t\t\t\tconst compressed = await this.ai.language.compressHistory(options.history, options.compress.max, options.compress.min, options);\n\t\t\t\toptions.history.splice(0, options.history.length, ...compressed);\n\t\t\t}\n\n\t\t\treturn res(resp);\n\t\t}), {abort});\n\t}\n\n\tasync code(message: string, options?: LLMRequest): Promise<any> {\n\t\tconst resp = await this.ask(message, {...options, system: [\n\t\t\toptions?.system,\n\t\t\t'Return your response in a code block'\n\t\t].filter(t => !!t).join(('\\n'))});\n\t\tconst codeBlock = /```(?:.+)?\\s*([\\s\\S]*?)```/.exec(resp);\n\t\treturn codeBlock ? codeBlock[1].trim() : null;\n\t}\n\n\t/**\n\t * Compress chat history to reduce context size\n\t * @param {LLMMessage[]} history Chatlog that will be compressed\n\t * @param max Trigger compression once context is larger than max\n\t * @param min Leave messages less than the token minimum, summarize the rest\n\t * @param {LLMRequest} options LLM options\n\t * @returns {Promise<LLMMessage[]>} New chat history will summary at index 0\n\t */\n\tasync compressHistory(history: LLMMessage[], max: number, min: number, options?: LLMRequest): Promise<LLMMessage[]> {\n\t\tif(this.estimateTokens(history) < max) return history;\n\t\tlet keep = 0, tokens = 0;\n\t\tfor(let m of history.toReversed()) {\n\t\t\ttokens += this.estimateTokens(m.content);\n\t\t\tif(tokens < min) keep++;\n\t\t\telse break;\n\t\t}\n\t\tif(history.length <= keep) return history;\n\t\tconst system = history[0].role == 'system' ? history[0] : null,\n\t\t\trecent = keep == 0 ? [] : history.slice(-keep),\n\t\t\tprocess = (keep == 0 ? history : history.slice(0, -keep)).filter(h => h.role === 'assistant' || h.role === 'user');\n\n\t\tconst summary: any = await this.summarize(process.map(m => `[${m.role}]: ${m.content}`).join('\\n\\n'), 500, options);\n\t\tconst d = Date.now();\n\t\tconst h = [{role: <any>'tool', name: 'summary', id: `summary_` + d, args: {}, content: `Conversation Summary: ${summary?.summary}`, timestamp: d}, ...recent];\n\t\tif(system) h.splice(0, 0, system);\n\t\treturn h;\n\t}\n\n\t/**\n\t * Compare the difference between embeddings (calculates the angle between two vectors)\n\t * @param {number[]} v1 First embedding / vector comparison\n\t * @param {number[]} v2 Second embedding / vector for comparison\n\t * @returns {number} Similarity values 0-1: 0 = unique, 1 = identical\n\t */\n\tcosineSimilarity(v1: number[], v2: number[]): number {\n\t\tif (v1.length !== v2.length) throw new Error('Vectors must be same length');\n\t\tlet dotProduct = 0, normA = 0, normB = 0;\n\t\tfor (let i = 0; i < v1.length; i++) {\n\t\t\tdotProduct += v1[i] * v2[i];\n\t\t\tnormA += v1[i] * v1[i];\n\t\t\tnormB += v2[i] * v2[i];\n\t\t}\n\t\tconst denominator = Math.sqrt(normA) * Math.sqrt(normB);\n\t\treturn denominator === 0 ? 0 : dotProduct / denominator;\n\t}\n\n\t/**\n\t * Chunk text into parts for AI digestion\n\t * @param {object | string} target Item that will be chunked (objects get converted)\n\t * @param {number} maxTokens Chunking size. More = better context, less = more specific (Search by paragraphs or lines)\n\t * @param {number} overlapTokens Includes previous X tokens to provide continuity to AI (In addition to max tokens)\n\t * @returns {string[]} Chunked strings\n\t */\n\tchunk(target: object | string, maxTokens = 500, overlapTokens = 50): string[] {\n\t\tconst objString = (obj: any, path = ''): string[] => {\n\t\t\tif(!obj) return [];\n\t\t\treturn Object.entries(obj).flatMap(([key, value]) => {\n\t\t\t\tconst p = path ? `${path}${isNaN(+key) ? `.${key}` : `[${key}]`}` : key;\n\t\t\t\tif(typeof value === 'object' && !Array.isArray(value)) return objString(value, p);\n\t\t\t\treturn `${p}: ${Array.isArray(value) ? value.join(', ') : value}`;\n\t\t\t});\n\t\t};\n\t\tconst lines = typeof target === 'object' ? objString(target) : target.toString().split('\\n');\n\t\tconst tokens = lines.flatMap(l => [...l.split(/\\s+/).filter(Boolean), '\\n']);\n\t\tconst chunks: string[] = [];\n\t\tfor(let i = 0; i < tokens.length;) {\n\t\t\tlet text = '', j = i;\n\t\t\twhile(j < tokens.length) {\n\t\t\t\tconst next = text + (text ? ' ' : '') + tokens[j];\n\t\t\t\tif(this.estimateTokens(next.replace(/\\s*\\n\\s*/g, '\\n')) > maxTokens && text) break;\n\t\t\t\ttext = next;\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tconst clean = text.replace(/\\s*\\n\\s*/g, '\\n').trim();\n\t\t\tif(clean) chunks.push(clean);\n\t\t\ti = Math.max(j - overlapTokens, j === i ? i + 1 : j);\n\t\t}\n\t\treturn chunks;\n\t}\n\n\t/**\n\t * Create a vector representation of a string\n\t * @param {object | string} target Item that will be embedded (objects get converted)\n\t * @param {maxTokens?: number, overlapTokens?: number} opts Options for embedding such as chunk sizes\n\t * @returns {Promise<Awaited<{index: number, embedding: number[], text: string, tokens: number}>[]>} Chunked embeddings\n\t */\n\tembedding(target: object | string, opts: {maxTokens?: number, overlapTokens?: number} = {}): AbortablePromise<any[]> {\n\t\tlet {maxTokens = 500, overlapTokens = 50} = opts;\n\t\tlet aborted = false;\n\t\tconst abort = () => { aborted = true; };\n\n\t\tconst embed = (text: string): Promise<number[]> => {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif(aborted) return reject(new Error('Aborted'));\n\n\t\t\t\tconst args: string[] = [\n\t\t\t\t\tjoin(dirname(fileURLToPath(import.meta.url)), 'embedder.js'),\n\t\t\t\t\t<string>this.ai.options.path,\n\t\t\t\t\tthis.ai.options?.embedder || 'bge-small-en-v1.5'\n\t\t\t\t];\n\t\t\t\tconst proc = spawn('node', args, {stdio: ['pipe', 'pipe', 'ignore']});\n\t\t\t\tproc.stdin.write(text);\n\t\t\t\tproc.stdin.end();\n\n\t\t\t\tlet output = '';\n\t\t\t\tproc.stdout.on('data', (data: Buffer) => output += data.toString());\n\t\t\t\tproc.on('close', (code: number) => {\n\t\t\t\t\tif(aborted) return reject(new Error('Aborted'));\n\t\t\t\t\tif(code === 0) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = JSON.parse(output);\n\t\t\t\t\t\t\tresolve(result.embedding);\n\t\t\t\t\t\t} catch(err) {\n\t\t\t\t\t\t\treject(new Error('Failed to parse embedding output'));\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(new Error(`Embedder process exited with code ${code}`));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tproc.on('error', reject);\n\t\t\t});\n\t\t};\n\n\t\tconst p = (async () => {\n\t\t\tconst chunks = this.chunk(target, maxTokens, overlapTokens), results: any[] = [];\n\t\t\tfor(let i = 0; i < chunks.length; i++) {\n\t\t\t\tif(aborted) break;\n\t\t\t\tconst text = chunks[i];\n\t\t\t\tconst embedding = await embed(text);\n\t\t\t\tresults.push({index: i, embedding, text, tokens: this.estimateTokens(text)});\n\t\t\t}\n\t\t\treturn results;\n\t\t})();\n\t\treturn Object.assign(p, { abort });\n\t}\n\n\t/**\n\t * Estimate variable as tokens\n\t * @param history Object to size\n\t * @returns {number} Rough token count\n\t */\n\testimateTokens(history: any): number {\n\t\tconst text = JSON.stringify(history);\n\t\treturn Math.ceil((text.length / 4) * 1.2);\n\t}\n\n\t/**\n\t * Compare the difference between two strings using tensor math\n\t * @param target Text that will be checked\n\t * @param {string} searchTerms Multiple search terms to check against target\n\t * @returns {{avg: number, max: number, similarities: number[]}} Similarity values 0-1: 0 = unique, 1 = identical\n\t */\n\tfuzzyMatch(target: string, ...searchTerms: string[]) {\n\t\tif(searchTerms.length < 2) throw new Error('Requires at least 2 strings to compare');\n\t\tconst vector = (text: string, dimensions: number = 10): number[] => {\n\t\t\treturn text.toLowerCase().split('').map((char, index) =>\n\t\t\t\t(char.charCodeAt(0) * (index + 1)) % dimensions / dimensions).slice(0, dimensions);\n\t\t}\n\t\tconst v = vector(target);\n\t\tconst similarities = searchTerms.map(t => vector(t)).map(refVector => this.cosineSimilarity(v, refVector))\n\t\treturn {avg: similarities.reduce((acc, s) => acc + s, 0) / similarities.length, max: Math.max(...similarities), similarities}\n\t}\n\n\t/**\n\t * Ask a question with JSON response\n\t * @param {string} text Text to process\n\t * @param {string} schema JSON schema the AI should match\n\t * @param {LLMRequest} options Configuration options and chat history\n\t * @returns {Promise<{} | {} | RegExpExecArray | null>}\n\t */\n\tasync json(text: string, schema: string, options?: LLMRequest): Promise<any> {\n\t\tconst code = await this.code(text, {...options, system: [\n\t\t\toptions?.system,\n\t\t\t`Only respond using JSON matching this schema:\\n\\`\\`\\`json\\n${schema}\\n\\`\\`\\``\n\t\t].filter(t => !!t).join('\\n')});\n\t\treturn code ? JSONAttemptParse(code, {}) : null;\n\t}\n\n\t/**\n\t * Create a summary of some text\n\t * @param {string} text Text to summarize\n\t * @param {number} tokens Max number of tokens\n\t * @param options LLM request options\n\t * @returns {Promise<string>} Summary\n\t */\n\tsummarize(text: string, tokens: number = 500, options?: LLMRequest): Promise<string | null> {\n\t\treturn this.ask(text, {system: `Generate the shortest summary possible <= ${tokens} tokens. Output nothing else`, temperature: 0.3, ...options});\n\t}\n}\n\nexport default LLM;\n","import {execSync, spawn} from 'node:child_process';\nimport {mkdtempSync} from 'node:fs';\nimport fs from 'node:fs/promises';\nimport {tmpdir} from 'node:os';\nimport * as path from 'node:path';\nimport Path, {join} from 'node:path';\nimport {AbortablePromise, Ai} from './ai.ts';\n\nexport class Audio {\n\tprivate downloads: {[key: string]: Promise<string>} = {};\n\tprivate pyannote!: string;\n\tprivate whisperModel!: string;\n\n\tconstructor(private ai: Ai) {\n\t\tif(ai.options.whisper) {\n\t\t\tthis.whisperModel = ai.options.asr || 'ggml-base.en.bin';\n\t\t\tthis.downloadAsrModel();\n\t\t}\n\n\t\tthis.pyannote = `\nimport sys\nimport json\nimport os\nfrom pyannote.audio import Pipeline\n\nos.environ['TORCH_HOME'] = r\"${ai.options.path}\"\npipeline = Pipeline.from_pretrained(\"pyannote/speaker-diarization-3.1\", token=\"${ai.options.hfToken}\")\noutput = pipeline(sys.argv[1])\n\nsegments = []\nfor turn, speaker in output.speaker_diarization:\n segments.append({\"start\": turn.start, \"end\": turn.end, \"speaker\": speaker})\n\nprint(json.dumps(segments))\n`;\n\t}\n\n\tprivate async addPunctuation(timestampData: any, llm?: boolean, cadence = 150): Promise<string> {\n\t\tconst countSyllables = (word: string): number => {\n\t\t\tword = word.toLowerCase().replace(/[^a-z]/g, '');\n\t\t\tif(word.length <= 3) return 1;\n\t\t\tconst matches = word.match(/[aeiouy]+/g);\n\t\t\tlet count = matches ? matches.length : 1;\n\t\t\tif(word.endsWith('e')) count--;\n\t\t\treturn Math.max(1, count);\n\t\t};\n\n\t\tlet result = '';\n\t\ttimestampData.transcription.filter((word, i) => {\n\t\t\tlet skip = false;\n\t\t\tconst prevWord = timestampData.transcription[i - 1];\n\t\t\tconst nextWord = timestampData.transcription[i + 1];\n\t\t\tif(!word.text && nextWord) {\n\t\t\t\tnextWord.offsets.from = word.offsets.from;\n\t\t\t\tnextWord.timestamps.from = word.offsets.from;\n\t\t\t} else if(word.text && word.text[0] != ' ' && prevWord) {\n\t\t\t\tprevWord.offsets.to = word.offsets.to;\n\t\t\t\tprevWord.timestamps.to = word.timestamps.to;\n\t\t\t\tprevWord.text += word.text;\n\t\t\t\tskip = true;\n\t\t\t}\n\t\t\treturn !!word.text && !skip;\n\t\t}).forEach((word: any) => {\n\t\t\tconst capital = /^[A-Z]/.test(word.text.trim());\n\t\t\tconst length = word.offsets.to - word.offsets.from;\n\t\t\tconst syllables = countSyllables(word.text.trim());\n\t\t\tconst expected = syllables * cadence;\n\t\t\tif(capital && length > expected * 2 && word.text[0] == ' ') result += '.';\n\t\t\tresult += word.text;\n\t\t});\n\t\tif(!llm) return result.trim();\n\t\treturn this.ai.language.ask(result, {\n\t\t\tsystem: 'Remove any misplaced punctuation from the following ASR transcript using the replace tool. Avoid modifying words unless there is an obvious typo',\n\t\t\ttemperature: 0.1,\n\t\t\ttools: [{\n\t\t\t\tname: 'replace',\n\t\t\t\tdescription: 'Use find and replace to fix errors',\n\t\t\t\targs: {\n\t\t\t\t\tfind: {type: 'string', description: 'Text to find', required: true},\n\t\t\t\t\treplace: {type: 'string', description: 'Text to replace', required: true}\n\t\t\t\t},\n\t\t\t\tfn: (args) => result = result.replace(args.find, args.replace)\n\t\t\t}]\n\t\t}).then(() => result);\n\t}\n\n\tprivate async diarizeTranscript(timestampData: any, speakers: any[], llm: boolean): Promise<string> {\n\t\tconst speakerMap = new Map();\n\t\tlet speakerCount = 0;\n\t\tspeakers.forEach((seg: any) => {\n\t\t\tif(!speakerMap.has(seg.speaker)) speakerMap.set(seg.speaker, ++speakerCount);\n\t\t});\n\n\t\tconst punctuatedText = await this.addPunctuation(timestampData, llm);\n\t\tconst sentences = punctuatedText.match(/[^.!?]+[.!?]+/g) || [punctuatedText];\n\t\tconst words = timestampData.transcription.filter((w: any) => w.text.trim());\n\n\t\t// Assign speaker to each sentence\n\t\tconst sentencesWithSpeakers = sentences.map(sentence => {\n\t\t\tsentence = sentence.trim();\n\t\t\tif(!sentence) return null;\n\n\t\t\tconst sentenceWords = sentence.toLowerCase().replace(/[^\\w\\s]/g, '').split(/\\s+/);\n\t\t\tconst speakerWordCount = new Map<number, number>();\n\n\t\t\tsentenceWords.forEach(sw => {\n\t\t\t\tconst word = words.find((w: any) => sw === w.text.trim().toLowerCase().replace(/[^\\w]/g, ''));\n\t\t\t\tif(!word) return;\n\n\t\t\t\tconst wordTime = word.offsets.from / 1000;\n\t\t\t\tconst speaker = speakers.find((seg: any) => wordTime >= seg.start && wordTime <= seg.end);\n\t\t\t\tif(speaker) {\n\t\t\t\t\tconst spkNum = speakerMap.get(speaker.speaker);\n\t\t\t\t\tspeakerWordCount.set(spkNum, (speakerWordCount.get(spkNum) || 0) + 1);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tlet bestSpeaker = 1;\n\t\t\tlet maxWords = 0;\n\t\t\tspeakerWordCount.forEach((count, speaker) => {\n\t\t\t\tif(count > maxWords) {\n\t\t\t\t\tmaxWords = count;\n\t\t\t\t\tbestSpeaker = speaker;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn {speaker: bestSpeaker, text: sentence};\n\t\t}).filter(s => s !== null);\n\n\t\t// Merge adjacent sentences from same speaker\n\t\tconst merged: Array<{speaker: number, text: string}> = [];\n\t\tsentencesWithSpeakers.forEach(item => {\n\t\t\tconst last = merged[merged.length - 1];\n\t\t\tif(last && last.speaker === item.speaker) {\n\t\t\t\tlast.text += ' ' + item.text;\n\t\t\t} else {\n\t\t\t\tmerged.push({...item});\n\t\t\t}\n\t\t});\n\n\t\tlet transcript = merged.map(item => `[Speaker ${item.speaker}]: ${item.text}`).join('\\n').trim();\n\t\tif(!llm) return transcript;\n\t\tlet chunks = this.ai.language.chunk(transcript, 500, 0);\n\t\tif(chunks.length > 4) chunks = [...chunks.slice(0, 3), <string>chunks.at(-1)];\n\t\tconst names = await this.ai.language.json(chunks.join('\\n'), '{1: \"Detected Name\", 2: \"Second Name\"}', {\n\t\t\tsystem: 'Use the following transcript to identify speakers. Only identify speakers you are positive about, dont mention speakers you are unsure about in your response',\n\t\t\ttemperature: 0.1,\n\t\t});\n\t\tObject.entries(names).forEach(([speaker, name]) => transcript = transcript.replaceAll(`[Speaker ${speaker}]`, `[${name}]`));\n\t\treturn transcript;\n\t}\n\n\tprivate runAsr(file: string, opts: {model?: string, diarization?: boolean} = {}): AbortablePromise<any> {\n\t\tlet proc: any;\n\t\tconst p = new Promise<any>((resolve, reject) => {\n\t\t\tthis.downloadAsrModel(opts.model).then(m => {\n\t\t\t\tif(opts.diarization) {\n\t\t\t\t\tlet output = path.join(path.dirname(file), 'transcript');\n\t\t\t\t\tproc = spawn(<string>this.ai.options.whisper,\n\t\t\t\t\t\t['-m', m, '-f', file, '-np', '-ml', '1', '-oj', '-of', output],\n\t\t\t\t\t\t{stdio: ['ignore', 'ignore', 'pipe']}\n\t\t\t\t\t);\n\t\t\t\t\tproc.on('error', (err: Error) => reject(err));\n\t\t\t\t\tproc.on('close', async (code: number) => {\n\t\t\t\t\t\tif(code === 0) {\n\t\t\t\t\t\t\toutput = await fs.readFile(output + '.json', 'utf-8');\n\t\t\t\t\t\t\tfs.rm(output + '.json').catch(() => { });\n\t\t\t\t\t\t\ttry { resolve(JSON.parse(output)); }\n\t\t\t\t\t\t\tcatch(e) { reject(new Error('Failed to parse whisper JSON')); }\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treject(new Error(`Exit code ${code}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tlet output = '';\n\t\t\t\t\tproc = spawn(<string>this.ai.options.whisper, ['-m', m, '-f', file, '-np', '-nt']);\n\t\t\t\t\tproc.on('error', (err: Error) => reject(err));\n\t\t\t\t\tproc.stdout.on('data', (data: Buffer) => output += data.toString());\n\t\t\t\t\tproc.on('close', async (code: number) => {\n\t\t\t\t\t\tif(code === 0) {\n\t\t\t\t\t\t\tresolve(output.trim() || null);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treject(new Error(`Exit code ${code}`));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\treturn <any>Object.assign(p, {abort: () => proc?.kill('SIGTERM')});\n\t}\n\n\tprivate runDiarization(file: string): AbortablePromise<any> {\n\t\tlet aborted = false, abort = () => { aborted = true; };\n\t\tconst checkPython = (cmd: string) => {\n\t\t\treturn new Promise<boolean>((resolve) => {\n\t\t\t\tconst proc = spawn(cmd, ['-W', 'ignore', '-c', 'import pyannote.audio']);\n\t\t\t\tproc.on('close', (code: number) => resolve(code === 0));\n\t\t\t\tproc.on('error', () => resolve(false));\n\t\t\t});\n\t\t};\n\t\tconst p = Promise.all<any>([\n\t\t\tcheckPython('python'),\n\t\t\tcheckPython('python3'),\n\t\t]).then(<any>(async ([p, p3]: [boolean, boolean]) => {\n\t\t\tif(aborted) return;\n\t\t\tif(!p && !p3) throw new Error('Pyannote is not installed: pip install pyannote.audio');\n\t\t\tconst binary = p3 ? 'python3' : 'python';\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif(aborted) return;\n\t\t\t\tlet output = '';\n\t\t\t\tconst proc = spawn(binary, ['-W', 'ignore', '-c', this.pyannote, file]);\n\t\t\t\tproc.stdout.on('data', (data: Buffer) => output += data.toString());\n\t\t\t\tproc.stderr.on('data', (data: Buffer) => console.error(data.toString()));\n\t\t\t\tproc.on('close', (code: number) => {\n\t\t\t\t\tif(code === 0) {\n\t\t\t\t\t\ttry { resolve(JSON.parse(output)); }\n\t\t\t\t\t\tcatch (err) { reject(new Error('Failed to parse diarization output')); }\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(new Error(`Python process exited with code ${code}`));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tproc.on('error', reject);\n\t\t\t\tabort = () => proc.kill('SIGTERM');\n\t\t\t});\n\t\t}));\n\t\treturn <any>Object.assign(p, {abort});\n\t}\n\n\tasr(file: string, options: { model?: string; diarization?: boolean | 'llm' } = {}): AbortablePromise<string | null> {\n\t\tif(!this.ai.options.whisper) throw new Error('Whisper not configured');\n\n\t\tconst tmp = join(mkdtempSync(join(tmpdir(), 'audio-')), 'converted.wav');\n\t\texecSync(`ffmpeg -i \"${file}\" -ar 16000 -ac 1 -f wav \"${tmp}\"`, { stdio: 'ignore' });\n\t\tconst clean = () => fs.rm(Path.dirname(tmp), {recursive: true, force: true}).catch(() => {});\n\n\t\tif(!options.diarization) return this.runAsr(tmp, {model: options.model});\n\t\tconst timestamps = this.runAsr(tmp, {model: options.model, diarization: true});\n\t\tconst diarization = this.runDiarization(tmp);\n\t\tlet aborted = false, abort = () => {\n\t\t\taborted = true;\n\t\t\ttimestamps.abort();\n\t\t\tdiarization.abort();\n\t\t\tclean();\n\t\t};\n\n\t\tconst response = Promise.allSettled([timestamps, diarization]).then(async ([ts, d]) => {\n\t\t\tif(ts.status == 'rejected') throw new Error('Whisper.cpp timestamps:\\n' + ts.reason);\n\t\t\tif(d.status == 'rejected') throw new Error('Pyannote:\\n' + d.reason);\n\t\t\tif(aborted || !options.diarization) return ts.value;\n\t\t\treturn this.diarizeTranscript(ts.value, d.value, options.diarization == 'llm');\n\t\t}).finally(() => clean());\n\t\treturn <any>Object.assign(response, {abort});\n\t}\n\n\tasync downloadAsrModel(model: string = this.whisperModel): Promise<string> {\n\t\tif(!this.ai.options.whisper) throw new Error('Whisper not configured');\n\t\tif(!model.endsWith('.bin')) model += '.bin';\n\t\tconst p = Path.join(<string>this.ai.options.path, model);\n\t\tif(await fs.stat(p).then(() => true).catch(() => false)) return p;\n\t\tif(!!this.downloads[model]) return this.downloads[model];\n\t\tthis.downloads[model] = fetch(`https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${model}`)\n\t\t\t.then(resp => resp.arrayBuffer())\n\t\t\t.then(arr => Buffer.from(arr)).then(async buffer => {\n\t\t\t\tawait fs.writeFile(p, buffer);\n\t\t\t\tdelete this.downloads[model];\n\t\t\t\treturn p;\n\t\t\t});\n\t\treturn this.downloads[model];\n\t}\n}\n","import {createWorker} from 'tesseract.js';\nimport {AbortablePromise, Ai} from './ai.ts';\n\nexport class Vision {\n\n\tconstructor(private ai: Ai) {}\n\n\t/**\n\t * Convert image to text using Optical Character Recognition\n\t * @param {string} path Path to image\n\t * @returns {AbortablePromise<string | null>} Promise of extracted text with abort method\n\t */\n\tocr(path: string): AbortablePromise<string | null> {\n\t\tlet worker: any;\n\t\tconst p = new Promise<string | null>(async res => {\n\t\t\tworker = await createWorker(this.ai.options.ocr || 'eng', 2, {cachePath: this.ai.options.path});\n\t\t\tconst {data} = await worker.recognize(path);\n\t\t\tawait worker.terminate();\n\t\t\tres(data.text.trim() || null);\n\t\t});\n\t\treturn Object.assign(p, {abort: () => worker?.terminate()});\n\t}\n}\n","import * as os from 'node:os';\nimport LLM, {AnthropicConfig, OllamaConfig, OpenAiConfig, LLMRequest} from './llm';\nimport { Audio } from './audio.ts';\nimport {Vision} from './vision.ts';\n\nexport type AbortablePromise<T> = Promise<T> & {\n\tabort: () => any\n};\n\nexport type AiOptions = {\n\t/** Token to pull models from hugging face */\n\thfToken?: string;\n\t/** Path to models */\n\tpath?: string;\n\t/** Whisper ASR model: ggml-tiny.en.bin, ggml-base.en.bin */\n\tasr?: string;\n\t/** Embedding model: all-MiniLM-L6-v2, bge-small-en-v1.5, bge-large-en-v1.5 */\n\tembedder?: string;\n\t/** Large language models, first is default */\n\tllm?: Omit<LLMRequest, 'model'> & {\n\t\tmodels: {[model: string]: AnthropicConfig | OllamaConfig | OpenAiConfig};\n\t}\n\t/** OCR model: eng, eng_best, eng_fast */\n\tocr?: string;\n\t/** Whisper binary */\n\twhisper?: string;\n}\n\nexport class Ai {\n\t/** Audio processing AI */\n\taudio!: Audio;\n\t/** Language processing AI */\n\tlanguage!: LLM;\n\t/** Vision processing AI */\n\tvision!: Vision;\n\n\tconstructor(public readonly options: AiOptions) {\n\t\tif(!options.path) options.path = os.tmpdir();\n\t\tprocess.env.TRANSFORMERS_CACHE = options.path;\n\t\tthis.audio = new Audio(this);\n\t\tthis.language = new LLM(this);\n\t\tthis.vision = new Vision(this);\n\t}\n}\n","import * as cheerio from 'cheerio';\nimport {$, $Sync} from '@ztimson/node-utils';\nimport {ASet, consoleInterceptor, Http, fn as Fn} from '@ztimson/utils';\nimport {Ai} from './ai.ts';\nimport {LLMRequest} from './llm.ts';\n\nexport type AiToolArg = {[key: string]: {\n\t/** Argument type */\n\ttype: 'array' | 'boolean' | 'number' | 'object' | 'string',\n\t/** Argument description */\n\tdescription: string,\n\t/** Required argument */\n\trequired?: boolean;\n\t/** Default value */\n\tdefault?: any,\n\t/** Options */\n\tenum?: string[],\n\t/** Minimum value or length */\n\tmin?: number,\n\t/** Maximum value or length */\n\tmax?: number,\n\t/** Match pattern */\n\tpattern?: string,\n\t/** Child arguments */\n\titems?: {[key: string]: AiToolArg}\n}}\n\nexport type AiTool = {\n\t/** Tool ID / Name - Must be snail_case */\n\tname: string,\n\t/** Tool description / prompt */\n\tdescription: string,\n\t/** Tool arguments */\n\targs?: AiToolArg,\n\t/** Callback function */\n\tfn: (args: any, stream: LLMRequest['stream'], ai: Ai) => any | Promise<any>,\n};\n\nexport const CliTool: AiTool = {\n\tname: 'cli',\n\tdescription: 'Use the command line interface, returns any output',\n\targs: {command: {type: 'string', description: 'Command to run', required: true}},\n\tfn: (args: {command: string}) => $`${args.command}`\n}\n\nexport const DateTimeTool: AiTool = {\n\tname: 'get_datetime',\n\tdescription: 'Get current UTC date / time',\n\targs: {},\n\tfn: async () => new Date().toUTCString()\n}\n\nexport const ExecTool: AiTool = {\n\tname: 'exec',\n\tdescription: 'Run code/scripts',\n\targs: {\n\t\tlanguage: {type: 'string', description: 'Execution language', enum: ['cli', 'node', 'python'], required: true},\n\t\tcode: {type: 'string', description: 'Code to execute', required: true}\n\t},\n\tfn: async (args, stream, ai) => {\n\t\ttry {\n\t\t\tswitch(args.type) {\n\t\t\t\tcase 'bash':\n\t\t\t\t\treturn await CliTool.fn({command: args.code}, stream, ai);\n\t\t\t\tcase 'node':\n\t\t\t\t\treturn await JSTool.fn({code: args.code}, stream, ai);\n\t\t\t\tcase 'python': {\n\t\t\t\t\treturn await PythonTool.fn({code: args.code}, stream, ai);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch(err: any) {\n\t\t\treturn {error: err?.message || err.toString()};\n\t\t}\n\t}\n}\n\nexport const FetchTool: AiTool = {\n\tname: 'fetch',\n\tdescription: 'Make HTTP request to URL',\n\targs: {\n\t\turl: {type: 'string', description: 'URL to fetch', required: true},\n\t\tmethod: {type: 'string', description: 'HTTP method to use', enum: ['GET', 'POST', 'PUT', 'DELETE'], default: 'GET'},\n\t\theaders: {type: 'object', description: 'HTTP headers to send', default: {}},\n\t\tbody: {type: 'object', description: 'HTTP body to send'},\n\t},\n\tfn: (args: {\n\t\turl: string;\n\t\tmethod: 'GET' | 'POST' | 'PUT' | 'DELETE';\n\t\theaders: {[key: string]: string};\n\t\tbody: any;\n\t}) => new Http({url: args.url, headers: args.headers}).request({method: args.method || 'GET', body: args.body})\n}\n\nexport const JSTool: AiTool = {\n\tname: 'exec_javascript',\n\tdescription: 'Execute commonjs javascript',\n\targs: {\n\t\tcode: {type: 'string', description: 'CommonJS javascript', required: true}\n\t},\n\tfn: async (args: {code: string}) => {\n\t\tconst console = consoleInterceptor(null);\n\t\tconst resp = await Fn<any>({console}, args.code, true).catch((err: any) => console.output.error.push(err));\n\t\treturn {...console.output, return: resp, stdout: undefined, stderr: undefined};\n\t}\n}\n\nexport const PythonTool: AiTool = {\n\tname: 'exec_javascript',\n\tdescription: 'Execute commonjs javascript',\n\targs: {\n\t\tcode: {type: 'string', description: 'CommonJS javascript', required: true}\n\t},\n\tfn: async (args: {code: string}) => ({result: $Sync`python -c \"${args.code}\"`})\n}\n\nexport const ReadWebpageTool: AiTool = {\n\tname: 'read_webpage',\n\tdescription: 'Extract clean, structured content from a webpage. Use after web_search to read specific URLs',\n\targs: {\n\t\turl: {type: 'string', description: 'URL to extract content from', required: true},\n\t\tfocus: {type: 'string', description: 'Optional: What aspect to focus on (e.g., \"pricing\", \"features\", \"contact info\")'}\n\t},\n\tfn: async (args: {url: string; focus?: string}) => {\n\t\tconst html = await fetch(args.url, {headers: {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64)\"}})\n\t\t\t.then(r => r.text()).catch(err => {throw new Error(`Failed to fetch: ${err.message}`)});\n\n\t\tconst $ = cheerio.load(html);\n\t\t$('script, style, nav, footer, header, aside, iframe, noscript, [role=\"navigation\"], [role=\"banner\"], .ad, .ads, .cookie, .popup').remove();\n\t\tconst metadata = {\n\t\t\ttitle: $('meta[property=\"og:title\"]').attr('content') || $('title').text() || '',\n\t\t\tdescription: $('meta[name=\"description\"]').attr('content') || $('meta[property=\"og:description\"]').attr('content') || '',\n\t\t};\n\n\t\tlet content = '';\n\t\tconst contentSelectors = ['article', 'main', '[role=\"main\"]', '.content', '.post', '.entry', 'body'];\n\t\tfor (const selector of contentSelectors) {\n\t\t\tconst el = $(selector).first();\n\t\t\tif (el.length && el.text().trim().length > 200) {\n\t\t\t\tcontent = el.text();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!content) content = $('body').text();\n\t\tcontent = content.replace(/\\s+/g, ' ').trim().slice(0, 8000);\n\n\t\treturn {url: args.url, title: metadata.title.trim(), description: metadata.description.trim(), content, focus: args.focus};\n\t}\n}\n\nexport const WebSearchTool: AiTool = {\n\tname: 'web_search',\n\tdescription: 'Use duckduckgo (anonymous) to find find relevant online resources. Returns a list of URLs that works great with the `read_webpage` tool',\n\targs: {\n\t\tquery: {type: 'string', description: 'Search string', required: true},\n\t\tlength: {type: 'string', description: 'Number of results to return', default: 5},\n\t},\n\tfn: async (args: {\n\t\tquery: string;\n\t\tlength: number;\n\t}) => {\n\t\tconst html = await fetch(`https://html.duckduckgo.com/html/?q=${encodeURIComponent(args.query)}`, {\n\t\t\theaders: {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64)\", \"Accept-Language\": \"en-US,en;q=0.9\"}\n\t\t}).then(resp => resp.text());\n\t\tlet match, regex = /<a .*?href=\"(.+?)\".+?<\\/a>/g;\n\t\tconst results = new ASet<string>();\n\t\twhile((match = regex.exec(html)) !== null) {\n\t\t\tlet url = /uddg=(.+)&amp?/.exec(decodeURIComponent(match[1]))?.[1];\n\t\t\tif(url) url = decodeURIComponent(url);\n\t\t\tif(url) results.add(url);\n\t\t\tif(results.size >= (args.length || 5)) break;\n\t\t}\n\t\treturn results;\n\t}\n}\n"],"names":["LLMProvider","Anthropic","ai","apiToken","model","anthropic","history","timestamp","messages","h","textContent","c","m","i","message","options","controller","res","tools","requestParams","t","objectMap","key","value","resp","isFirstMessage","err","chunk","text","last","JSONAttemptParse","toolCalls","results","toolCall","tool","findByProp","result","JSONSanitize","OpenAi","host","token","openAI","clean","tc","record","h2","rest","rej","args","LLM","config","abort","search","query","subject","limit","o","q","score","a","b","relevant","e","newMem","compressed","codeBlock","max","min","keep","tokens","system","recent","process","summary","d","v1","v2","dotProduct","normA","normB","denominator","target","maxTokens","overlapTokens","objString","obj","path","p","l","chunks","j","next","opts","aborted","embed","resolve","reject","join","dirname","fileURLToPath","_documentCurrentScript","proc","spawn","output","data","code","embedding","searchTerms","vector","dimensions","char","index","v","similarities","refVector","acc","s","schema","Audio","timestampData","llm","cadence","countSyllables","word","matches","count","skip","prevWord","nextWord","capital","length","expected","speakers","speakerMap","speakerCount","seg","punctuatedText","sentences","words","w","sentencesWithSpeakers","sentence","sentenceWords","speakerWordCount","sw","wordTime","speaker","spkNum","bestSpeaker","maxWords","merged","item","transcript","names","name","file","fs","checkPython","cmd","p3","binary","tmp","mkdtempSync","tmpdir","execSync","Path","timestamps","diarization","response","ts","arr","buffer","Vision","worker","createWorker","Ai","os","CliTool","$","DateTimeTool","ExecTool","stream","JSTool","PythonTool","FetchTool","Http","console","consoleInterceptor","Fn","$Sync","ReadWebpageTool","html","r","cheerio","metadata","content","contentSelectors","selector","el","WebSearchTool","match","regex","ASet","url"],"mappings":"qvBAGO,MAAeA,CAAY,CAElC,CCCO,MAAMC,UAAkBD,CAAY,CAG1C,YAA4BE,EAAwBC,EAAyBC,EAAe,CAC3F,MAAA,EAD2B,KAAA,GAAAF,EAAwB,KAAA,SAAAC,EAAyB,KAAA,MAAAC,EAE5E,KAAK,OAAS,IAAIC,EAAAA,UAAU,CAAC,OAAQF,EAAS,CAC/C,CALA,OAOQ,WAAWG,EAA8B,CAChD,MAAMC,EAAY,KAAK,IAAA,EACjBC,EAAyB,CAAA,EAC/B,QAAQC,KAAKH,EACZ,GAAG,OAAOG,EAAE,SAAW,SACtBD,EAAS,KAAU,CAAC,UAAAD,EAAW,GAAGE,EAAE,MAC9B,CACN,MAAMC,EAAcD,EAAE,SAAS,OAAQE,GAAWA,EAAE,MAAQ,MAAM,EAAE,IAAKA,GAAWA,EAAE,IAAI,EAAE,KAAK;AAAA;AAAA,CAAM,EACpGD,GAAaF,EAAS,KAAK,CAAC,UAAAD,EAAW,KAAME,EAAE,KAAM,QAASC,EAAY,EAC7ED,EAAE,QAAQ,QAASE,GAAW,CAC7B,GAAGA,EAAE,MAAQ,WACZH,EAAS,KAAK,CAAC,UAAAD,EAAW,KAAM,OAAQ,GAAII,EAAE,GAAI,KAAMA,EAAE,KAAM,KAAMA,EAAE,MAAO,QAAS,OAAU,UACzFA,EAAE,MAAQ,cAAe,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