@lowire/loop 0.0.19 → 0.0.21
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/lib/cache.js +1 -1
- package/lib/fetchWithTimeout.d.ts +19 -0
- package/lib/fetchWithTimeout.js +38 -0
- package/lib/loop.d.ts +2 -0
- package/lib/loop.js +19 -8
- package/lib/providers/anthropic.js +3 -1
- package/lib/providers/google.js +3 -1
- package/lib/providers/openai.js +3 -1
- package/lib/providers/openaiCompatible.js +3 -1
- package/lib/types.d.ts +1 -0
- package/package.json +1 -1
package/lib/cache.js
CHANGED
|
@@ -36,7 +36,7 @@ async function cachedCompleteNoSecrets(provider, conversation, caches, options)
|
|
|
36
36
|
if (!process.env.LOWIRE_NO_CACHE && caches.output[key])
|
|
37
37
|
return caches.output[key];
|
|
38
38
|
if (process.env.LOWIRE_FORCE_CACHE)
|
|
39
|
-
throw new Error('Cache missing but
|
|
39
|
+
throw new Error('Cache missing but LOWIRE_FORCE_CACHE is set' + JSON.stringify(conversation, null, 2));
|
|
40
40
|
const result = await provider.complete(conversation, options);
|
|
41
41
|
caches.output[key] = result;
|
|
42
42
|
return result;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Microsoft Corporation.
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
export declare function fetchWithTimeout(url: string, options: RequestInit & {
|
|
17
|
+
signal?: AbortSignal;
|
|
18
|
+
timeout?: number;
|
|
19
|
+
}): Promise<Response>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Copyright (c) Microsoft Corporation.
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
+
exports.fetchWithTimeout = fetchWithTimeout;
|
|
19
|
+
async function fetchWithTimeout(url, options) {
|
|
20
|
+
if (!options.timeout)
|
|
21
|
+
return fetch(url, options);
|
|
22
|
+
const controller = new AbortController();
|
|
23
|
+
const timeoutId = setTimeout(() => controller.abort(), options.timeout);
|
|
24
|
+
const abort = () => controller.abort();
|
|
25
|
+
options.signal?.addEventListener('abort', abort);
|
|
26
|
+
try {
|
|
27
|
+
return await fetch(url, { ...options, signal: controller.signal });
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (options.signal?.aborted)
|
|
31
|
+
throw error;
|
|
32
|
+
throw new Error(`Fetch timeout after ${options.timeout}ms`);
|
|
33
|
+
}
|
|
34
|
+
finally {
|
|
35
|
+
clearTimeout(timeoutId);
|
|
36
|
+
options.signal?.removeEventListener('abort', abort);
|
|
37
|
+
}
|
|
38
|
+
}
|
package/lib/loop.d.ts
CHANGED
|
@@ -45,6 +45,8 @@ export type LoopOptions = types.CompletionOptions & LoopEvents & {
|
|
|
45
45
|
tools?: types.Tool[];
|
|
46
46
|
callTool?: types.ToolCallback;
|
|
47
47
|
maxTurns?: number;
|
|
48
|
+
maxToolCalls?: number;
|
|
49
|
+
maxToolCallRetries?: number;
|
|
48
50
|
cache?: types.ReplayCache;
|
|
49
51
|
secrets?: Record<string, string>;
|
|
50
52
|
summarize?: boolean;
|
package/lib/loop.js
CHANGED
|
@@ -39,12 +39,16 @@ class Loop {
|
|
|
39
39
|
tools: allTools,
|
|
40
40
|
};
|
|
41
41
|
const debug = options.debug;
|
|
42
|
-
|
|
42
|
+
const budget = {
|
|
43
|
+
tokens: options.maxTokens,
|
|
44
|
+
toolCalls: options.maxToolCalls,
|
|
45
|
+
toolCallRetries: options.maxToolCallRetries,
|
|
46
|
+
};
|
|
43
47
|
const totalUsage = { input: 0, output: 0 };
|
|
44
|
-
debug?.('lowire:loop')(`Starting ${this._provider.name} loop
|
|
48
|
+
debug?.('lowire:loop')(`Starting ${this._provider.name} loop\n${task}`);
|
|
45
49
|
const maxTurns = options.maxTurns || 100;
|
|
46
50
|
for (let turns = 0; turns < maxTurns; ++turns) {
|
|
47
|
-
if (options.maxTokens &&
|
|
51
|
+
if (options.maxTokens && budget.tokens !== undefined && budget.tokens <= 0)
|
|
48
52
|
throw new Error(`Budget tokens ${options.maxTokens} exhausted`);
|
|
49
53
|
debug?.('lowire:loop')(`Turn ${turns + 1} of (max ${maxTurns})`);
|
|
50
54
|
const caches = options.cache ? {
|
|
@@ -52,23 +56,23 @@ class Loop {
|
|
|
52
56
|
output: this._cacheOutput,
|
|
53
57
|
} : undefined;
|
|
54
58
|
const summarizedConversation = options.summarize ? this._summarizeConversation(task, conversation, options) : conversation;
|
|
55
|
-
await options.onBeforeTurn?.({ conversation: summarizedConversation, totalUsage, budgetTokens });
|
|
59
|
+
await options.onBeforeTurn?.({ conversation: summarizedConversation, totalUsage, budgetTokens: budget.tokens });
|
|
56
60
|
if (abortController?.signal.aborted)
|
|
57
61
|
return { status: 'break', usage: totalUsage, turns };
|
|
58
62
|
debug?.('lowire:loop')(`Request`, JSON.stringify({ ...summarizedConversation, tools: `${summarizedConversation.tools.length} tools` }, null, 2));
|
|
59
63
|
const { result: assistantMessage, usage } = await (0, cache_1.cachedComplete)(this._provider, summarizedConversation, caches, {
|
|
60
64
|
...options,
|
|
61
|
-
maxTokens:
|
|
65
|
+
maxTokens: budget.tokens,
|
|
62
66
|
signal: abortController?.signal,
|
|
63
67
|
});
|
|
64
68
|
const intent = assistantMessage.content.filter(part => part.type === 'text').map(part => part.text).join('\n');
|
|
65
69
|
totalUsage.input += usage.input;
|
|
66
70
|
totalUsage.output += usage.output;
|
|
67
|
-
if (
|
|
68
|
-
|
|
71
|
+
if (budget.tokens !== undefined)
|
|
72
|
+
budget.tokens -= usage.input + usage.output;
|
|
69
73
|
debug?.('lowire:loop')('Usage', `input: ${usage.input}, output: ${usage.output}`);
|
|
70
74
|
debug?.('lowire:loop')('Assistant', intent, JSON.stringify(assistantMessage.content, null, 2));
|
|
71
|
-
await options.onAfterTurn?.({ assistantMessage, totalUsage, budgetTokens });
|
|
75
|
+
await options.onAfterTurn?.({ assistantMessage, totalUsage, budgetTokens: budget.tokens });
|
|
72
76
|
if (abortController?.signal.aborted)
|
|
73
77
|
return { status: 'break', usage: totalUsage, turns };
|
|
74
78
|
conversation.messages.push(assistantMessage);
|
|
@@ -78,6 +82,8 @@ class Loop {
|
|
|
78
82
|
continue;
|
|
79
83
|
}
|
|
80
84
|
for (const toolCall of toolCalls) {
|
|
85
|
+
if (budget.toolCalls !== undefined && --budget.toolCalls < 0)
|
|
86
|
+
throw new Error(`Failed to perform step, max tool calls (${options.maxToolCalls}) reached`);
|
|
81
87
|
const { name, arguments: args } = toolCall;
|
|
82
88
|
debug?.('lowire:loop')('Call tool', name, JSON.stringify(args, null, 2));
|
|
83
89
|
const status = await options.onBeforeToolCall?.({ assistantMessage, toolCall });
|
|
@@ -129,6 +135,11 @@ class Loop {
|
|
|
129
135
|
};
|
|
130
136
|
}
|
|
131
137
|
}
|
|
138
|
+
const hasErrors = toolCalls.some(toolCall => toolCall.result?.isError);
|
|
139
|
+
if (!hasErrors)
|
|
140
|
+
budget.toolCallRetries = options.maxToolCallRetries;
|
|
141
|
+
if (hasErrors && budget.toolCallRetries !== undefined && --budget.toolCallRetries < 0)
|
|
142
|
+
throw new Error(`Failed to perform action after ${options.maxToolCallRetries} tool call retries`);
|
|
132
143
|
}
|
|
133
144
|
throw new Error('Failed to perform step, max attempts reached');
|
|
134
145
|
}
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
18
|
exports.Anthropic = void 0;
|
|
19
|
+
const fetchWithTimeout_1 = require("../fetchWithTimeout");
|
|
19
20
|
class Anthropic {
|
|
20
21
|
name = 'anthropic';
|
|
21
22
|
async complete(conversation, options) {
|
|
@@ -49,11 +50,12 @@ async function create(createParams, options) {
|
|
|
49
50
|
};
|
|
50
51
|
const debugBody = { ...createParams, tools: `${createParams.tools?.length ?? 0} tools` };
|
|
51
52
|
options.debug?.('lowire:anthropic')('Request:', JSON.stringify(debugBody, null, 2));
|
|
52
|
-
const response = await
|
|
53
|
+
const response = await (0, fetchWithTimeout_1.fetchWithTimeout)(options.apiEndpoint ?? `https://api.anthropic.com/v1/messages`, {
|
|
53
54
|
method: 'POST',
|
|
54
55
|
headers,
|
|
55
56
|
body: JSON.stringify(createParams),
|
|
56
57
|
signal: options.signal,
|
|
58
|
+
timeout: options.apiTimeout
|
|
57
59
|
});
|
|
58
60
|
if (!response.ok) {
|
|
59
61
|
options.debug?.('lowire:anthropic')('Response:', response.status);
|
package/lib/providers/google.js
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
18
|
exports.Google = void 0;
|
|
19
|
+
const fetchWithTimeout_1 = require("../fetchWithTimeout");
|
|
19
20
|
class Google {
|
|
20
21
|
name = 'google';
|
|
21
22
|
async complete(conversation, options) {
|
|
@@ -46,7 +47,7 @@ exports.Google = Google;
|
|
|
46
47
|
async function create(model, createParams, options) {
|
|
47
48
|
const debugBody = { ...createParams, tools: `${createParams.tools?.length ?? 0} tools` };
|
|
48
49
|
options.debug?.('lowire:google')('Request:', JSON.stringify(debugBody, null, 2));
|
|
49
|
-
const response = await
|
|
50
|
+
const response = await (0, fetchWithTimeout_1.fetchWithTimeout)(options.apiEndpoint ?? `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`, {
|
|
50
51
|
method: 'POST',
|
|
51
52
|
headers: {
|
|
52
53
|
'Content-Type': 'application/json',
|
|
@@ -54,6 +55,7 @@ async function create(model, createParams, options) {
|
|
|
54
55
|
},
|
|
55
56
|
body: JSON.stringify(createParams),
|
|
56
57
|
signal: options.signal,
|
|
58
|
+
timeout: options.apiTimeout
|
|
57
59
|
});
|
|
58
60
|
if (!response.ok) {
|
|
59
61
|
options.debug?.('lowire:google')('Response:', response.status);
|
package/lib/providers/openai.js
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
18
|
exports.OpenAI = void 0;
|
|
19
|
+
const fetchWithTimeout_1 = require("../fetchWithTimeout");
|
|
19
20
|
class OpenAI {
|
|
20
21
|
name = 'openai';
|
|
21
22
|
async complete(conversation, options) {
|
|
@@ -69,11 +70,12 @@ async function create(createParams, options) {
|
|
|
69
70
|
};
|
|
70
71
|
const debugBody = { ...createParams, tools: `${createParams.tools?.length ?? 0} tools` };
|
|
71
72
|
options.debug?.('lowire:openai-responses')('Request:', JSON.stringify(debugBody, null, 2));
|
|
72
|
-
const response = await
|
|
73
|
+
const response = await (0, fetchWithTimeout_1.fetchWithTimeout)(options.apiEndpoint ?? `https://api.openai.com/v1/responses`, {
|
|
73
74
|
method: 'POST',
|
|
74
75
|
headers,
|
|
75
76
|
body: JSON.stringify(createParams),
|
|
76
77
|
signal: options.signal,
|
|
78
|
+
timeout: options.apiTimeout
|
|
77
79
|
});
|
|
78
80
|
if (!response.ok) {
|
|
79
81
|
options.debug?.('lowire:openai-responses')('Response:', response.status);
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
18
|
exports.OpenAICompatible = void 0;
|
|
19
|
+
const fetchWithTimeout_1 = require("../fetchWithTimeout");
|
|
19
20
|
class OpenAICompatible {
|
|
20
21
|
name = 'openai-compatible';
|
|
21
22
|
async complete(conversation, options) {
|
|
@@ -67,11 +68,12 @@ async function create(createParams, options) {
|
|
|
67
68
|
};
|
|
68
69
|
const debugBody = { ...createParams, tools: `${createParams.tools?.length ?? 0} tools` };
|
|
69
70
|
options.debug?.('lowire:openai')('Request:', JSON.stringify(debugBody, null, 2));
|
|
70
|
-
const response = await
|
|
71
|
+
const response = await (0, fetchWithTimeout_1.fetchWithTimeout)(options.apiEndpoint ?? `https://api.openai.com/v1/chat/completions`, {
|
|
71
72
|
method: 'POST',
|
|
72
73
|
headers,
|
|
73
74
|
body: JSON.stringify(createParams),
|
|
74
75
|
signal: options.signal,
|
|
76
|
+
timeout: options.apiTimeout
|
|
75
77
|
});
|
|
76
78
|
if (!response.ok) {
|
|
77
79
|
options.debug?.('lowire:openai')('Response:', response.status);
|
package/lib/types.d.ts
CHANGED