|
| 1 | +import fs from 'fs/promises'; |
| 2 | +import os from 'os'; |
| 3 | +import path from 'path'; |
| 4 | +import { OpenAI } from "openai"; |
| 5 | +import { Anthropic } from '@anthropic-ai/sdk'; |
| 6 | +import { Groq } from "groq-sdk"; |
| 7 | +import { GoogleGenerativeAI } from "@google/generative-ai"; |
| 8 | +import { encode } from "gpt-tokenizer/esm/model/davinci-codex"; // tokenizer |
| 9 | + |
| 10 | +// Map of model shortcodes to full model names |
| 11 | +export const MODELS = { |
| 12 | + g: 'gpt-4o', |
| 13 | + G: 'gpt-4-32k-0314', |
| 14 | + h: 'claude-3-haiku-20240307', |
| 15 | + s: 'claude-3-sonnet-20240229', |
| 16 | + o: 'claude-3-opus-20240229', |
| 17 | + l: 'llama3-8b-8192', |
| 18 | + L: 'llama3-70b-8192', |
| 19 | + i: 'gemini-1.5-flash-latest', |
| 20 | + I: 'gemini-1.5-pro-latest' |
| 21 | +}; |
| 22 | + |
| 23 | +// Factory function to create a stateful OpenAI chat |
| 24 | +export function openAIChat(clientClass) { |
| 25 | + const messages = []; |
| 26 | + |
| 27 | + async function ask(userMessage, { system, model, temperature = 0.0, max_tokens = 4096, stream = true }) { |
| 28 | + model = MODELS[model] || model; |
| 29 | + const client = new clientClass({ apiKey: await getToken(clientClass.name.toLowerCase()) }); |
| 30 | + |
| 31 | + if (messages.length === 0) { |
| 32 | + messages.push({ role: "system", content: system }); |
| 33 | + } |
| 34 | + |
| 35 | + messages.push({ role: "user", content: userMessage }); |
| 36 | + |
| 37 | + const params = { messages, model, temperature, max_tokens, stream }; |
| 38 | + |
| 39 | + let result = ""; |
| 40 | + const response = await client.chat.completions.create(params); |
| 41 | + |
| 42 | + for await (const chunk of response) { |
| 43 | + const text = chunk.choices[0]?.delta?.content || ""; |
| 44 | + process.stdout.write(text); |
| 45 | + result += text; |
| 46 | + } |
| 47 | + |
| 48 | + messages.push({ role: 'assistant', content: result }); |
| 49 | + |
| 50 | + return result; |
| 51 | + } |
| 52 | + |
| 53 | + return ask; |
| 54 | +} |
| 55 | + |
| 56 | +// Factory function to create a stateful Anthropic chat |
| 57 | +export function anthropicChat(clientClass) { |
| 58 | + const messages = []; |
| 59 | + |
| 60 | + async function ask(userMessage, { system, model, temperature = 0.0, max_tokens = 4096, stream = true }) { |
| 61 | + model = MODELS[model] || model; |
| 62 | + const client = new clientClass({ apiKey: await getToken(clientClass.name.toLowerCase()) }); |
| 63 | + |
| 64 | + messages.push({ role: "user", content: userMessage }); |
| 65 | + |
| 66 | + const params = { system, model, temperature, max_tokens, stream }; |
| 67 | + |
| 68 | + let result = ""; |
| 69 | + const response = client.messages |
| 70 | + .stream({ ...params, messages }) |
| 71 | + .on('text', (text) => { |
| 72 | + process.stdout.write(text); |
| 73 | + result += text; |
| 74 | + }); |
| 75 | + await response.finalMessage(); |
| 76 | + |
| 77 | + messages.push({ role: 'assistant', content: result }); |
| 78 | + |
| 79 | + return result; |
| 80 | + } |
| 81 | + |
| 82 | + return ask; |
| 83 | +} |
| 84 | + |
| 85 | +export function geminiChat(clientClass) { |
| 86 | + const messages = []; |
| 87 | + |
| 88 | + async function ask(userMessage, { system, model, temperature = 0.0, max_tokens = 4096, stream = true }) { |
| 89 | + model = MODELS[model] || model; |
| 90 | + const client = new clientClass(await getToken(clientClass.name.toLowerCase())); |
| 91 | + |
| 92 | + const generationConfig = { |
| 93 | + maxOutputTokens: max_tokens, |
| 94 | + temperature, |
| 95 | + }; |
| 96 | + |
| 97 | + const chat = client.getGenerativeModel({ model, systemInstruction: system, generationConfig }) |
| 98 | + .startChat({ history: messages }); |
| 99 | + |
| 100 | + messages.push({ role: "user", parts: [{ text: userMessage }] }); |
| 101 | + |
| 102 | + let result = ""; |
| 103 | + if (stream) { |
| 104 | + const response = await chat.sendMessageStream(userMessage); |
| 105 | + for await (const chunk of response.stream) { |
| 106 | + const text = chunk.text(); |
| 107 | + process.stdout.write(text); |
| 108 | + result += text; |
| 109 | + } |
| 110 | + } else { |
| 111 | + const response = await chat.sendMessage(userMessage); |
| 112 | + result = (await response.response).text(); |
| 113 | + } |
| 114 | + |
| 115 | + messages.push({ role: 'model', parts: [{ text: result }] }); |
| 116 | + |
| 117 | + return result; |
| 118 | + } |
| 119 | + |
| 120 | + return ask; |
| 121 | +} |
| 122 | + |
| 123 | +// Generic asker function that dispatches to the correct asker based on the model name |
| 124 | +export function chat(model) { |
| 125 | + model = MODELS[model] || model; |
| 126 | + if (model.startsWith('gpt')) { |
| 127 | + return openAIChat(OpenAI); |
| 128 | + } else if (model.startsWith('claude')) { |
| 129 | + return anthropicChat(Anthropic); |
| 130 | + } else if (model.startsWith('llama')) { |
| 131 | + return openAIChat(Groq); |
| 132 | + } else if (model.startsWith('gemini')) { |
| 133 | + return geminiChat(GoogleGenerativeAI); |
| 134 | + } else { |
| 135 | + throw new Error(`Unsupported model: ${model}`); |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +// Utility function to read the API token for a given vendor |
| 140 | +async function getToken(vendor) { |
| 141 | + const tokenPath = path.join(os.homedir(), '.config', `${vendor}.token`); |
| 142 | + try { |
| 143 | + return (await fs.readFile(tokenPath, 'utf8')).trim(); |
| 144 | + } catch (err) { |
| 145 | + console.error(`Error reading ${vendor}.token file:`, err.message); |
| 146 | + process.exit(1); |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +export function tokenCount(inputText) { |
| 151 | + // Encode the input string into tokens |
| 152 | + const tokens = encode(inputText); |
| 153 | + |
| 154 | + // Get the number of tokens |
| 155 | + const numberOfTokens = tokens.length; |
| 156 | + |
| 157 | + // Return the number of tokens |
| 158 | + return numberOfTokens; |
| 159 | +} |
0 commit comments