132 lines
5.3 KiB
JavaScript
132 lines
5.3 KiB
JavaScript
const Conversation = require("./conversation");
|
|
const lmStudio = require("./lmstudio");
|
|
const cleanText = require("./clean-text");
|
|
|
|
const MAX_TRANSPORT_ATTEMPTS = 10;
|
|
const MAX_CONTINUATIONS = 10;
|
|
const CONTINUE_PROMPT = [
|
|
"Your previous response ended before you produced the requested final answer.",
|
|
"Continue from where you left off. Do not restart the task or discard the work you already did.",
|
|
"Keep investigating as deeply as necessary. When you have actually finished, provide the final deliverable required by the original prompt."
|
|
].join("\n");
|
|
|
|
function providerFor(name) {
|
|
switch (String(name || "").toLowerCase()) {
|
|
case "lm-studio":
|
|
return lmStudio;
|
|
default:
|
|
throw new Error(`Unsupported LLM provider: ${name}`);
|
|
}
|
|
}
|
|
|
|
function validateSettings(settings) {
|
|
if (!settings || typeof settings !== "object") throw new Error("Perry settings are required.");
|
|
if (typeof settings.provider !== "string" || !settings.provider.trim()) throw new Error("Perry setting 'provider' is required.");
|
|
if (typeof settings.model !== "string" || !settings.model.trim()) throw new Error("Perry setting 'model' is required.");
|
|
|
|
return {
|
|
provider: settings.provider.trim().toLowerCase(),
|
|
model: settings.model
|
|
};
|
|
}
|
|
|
|
function createPerry(settings) {
|
|
const configured = validateSettings(settings);
|
|
const llm = providerFor(configured.provider);
|
|
|
|
function warmUp() {
|
|
return llm.warmUp(configured);
|
|
}
|
|
|
|
function prepare(name, systemPrompt, segments = []) {
|
|
const conversation = Conversation.start(systemPrompt);
|
|
for (const segment of segments) conversation.add(segment);
|
|
return { name: name || "anonymous", conversation };
|
|
}
|
|
|
|
function addFallbackContinuation(conversation, reply) {
|
|
if (reply.reasoning?.trim()) {
|
|
conversation.add({
|
|
role: "assistant",
|
|
content: [
|
|
"[UNFINISHED PRIVATE WORK FROM MY PREVIOUS RESPONSE]",
|
|
reply.reasoning.trim(),
|
|
"[END UNFINISHED PRIVATE WORK]"
|
|
].join("\n")
|
|
});
|
|
}
|
|
conversation.add({ role: "user", content: CONTINUE_PROMPT });
|
|
}
|
|
|
|
async function askConversation(agent, conversation, options = {}) {
|
|
const reasoning = [];
|
|
let previousResponseId = null;
|
|
let useStatefulContinuation = false;
|
|
|
|
for (let continuation = 0; continuation <= MAX_CONTINUATIONS; continuation++) {
|
|
for (let attempt = 1; attempt <= MAX_TRANSPORT_ATTEMPTS; attempt++) {
|
|
const sendOptions = { ...options };
|
|
delete sendOptions.live;
|
|
|
|
if (useStatefulContinuation && previousResponseId) {
|
|
sendOptions.previousResponseId = previousResponseId;
|
|
sendOptions.continuationInput = CONTINUE_PROMPT;
|
|
}
|
|
|
|
try {
|
|
await warmUp();
|
|
const reply = await llm.send(conversation, configured, sendOptions);
|
|
if (reply.reasoning?.trim()) reasoning.push(reply.reasoning.trim());
|
|
if (reply.content?.trim()) {
|
|
delete reply.responseId;
|
|
if (reasoning.length > 0) reply.reasoning = reasoning.join("\n\n--- continuation ---\n\n");
|
|
return reply;
|
|
}
|
|
if (continuation >= MAX_CONTINUATIONS) {
|
|
throw Object.assign(new Error(`LLM returned no final response content for ${agent.name} after ${MAX_CONTINUATIONS} continuations.`), { retryable: false });
|
|
}
|
|
|
|
if (reply.responseId) {
|
|
previousResponseId = reply.responseId;
|
|
useStatefulContinuation = true;
|
|
} else {
|
|
previousResponseId = null;
|
|
useStatefulContinuation = false;
|
|
addFallbackContinuation(conversation, reply);
|
|
}
|
|
break;
|
|
} catch (error) {
|
|
const retryable = error.retryable !== false;
|
|
if (!retryable || attempt === MAX_TRANSPORT_ATTEMPTS) throw error;
|
|
const delayMs = Math.min(attempt, 5) * 1000;
|
|
await new Promise(resolve => setTimeout(resolve, delayMs));
|
|
}
|
|
}
|
|
}
|
|
throw new Error(`LLM request for ${agent.name} failed unexpectedly.`);
|
|
}
|
|
|
|
async function ask(agent, input, options = {}) {
|
|
const conversation = Conversation.from(agent.conversation);
|
|
conversation.add({ role: "user", content: input });
|
|
return askConversation(agent, conversation, options);
|
|
}
|
|
|
|
async function followUp(agent, originalInput, previousReply, input, options = {}) {
|
|
const conversation = Conversation.from(agent.conversation);
|
|
conversation.add({ role: "user", content: originalInput });
|
|
conversation.add(previousReply);
|
|
conversation.add({ role: "user", content: input });
|
|
return askConversation(agent, conversation, options);
|
|
}
|
|
|
|
function model() {
|
|
return configured.model;
|
|
}
|
|
|
|
return { warmUp, prepare, ask, followUp, model };
|
|
}
|
|
|
|
createPerry.cleanText = cleanText;
|
|
module.exports = createPerry;
|