@openrouter/sdk 1.5.56 → 1.5.58
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/esm/lib/config.d.ts +2 -2
- package/esm/lib/config.js +2 -2
- package/esm/models/additionaltoolsitem.d.ts +5 -4
- package/esm/models/additionaltoolsitem.js +3 -0
- package/esm/models/alignmentresponsesrejected.d.ts +4 -1
- package/esm/models/alignmentresponsesrejected.js +6 -0
- package/esm/models/byokproviderslug.d.ts +1 -0
- package/esm/models/byokproviderslug.js +1 -0
- package/esm/models/createworkspacerequest.d.ts +1 -0
- package/esm/models/createworkspacerequest.js +1 -0
- package/esm/models/decisionschoicequestion.d.ts +4 -4
- package/esm/models/decisionschoicequestion.js +1 -5
- package/esm/models/decisionsnoulquestion.d.ts +12 -12
- package/esm/models/decisionsnoulquestion.js +3 -7
- package/esm/models/decisionsresponse.d.ts +12 -0
- package/esm/models/decisionsresponse.js +5 -0
- package/esm/models/decisionsscorequestion.d.ts +4 -4
- package/esm/models/decisionsscorequestion.js +1 -5
- package/esm/models/imagegenerationproviderpreferences.d.ts +6 -0
- package/esm/models/imagegenerationproviderpreferences.js +1 -0
- package/esm/models/imagegenerationrequest.d.ts +1 -1
- package/esm/models/index.d.ts +6 -0
- package/esm/models/index.js +6 -0
- package/esm/models/mcpapprovalrequestitem.d.ts +7 -0
- package/esm/models/mcpapprovalrequestitem.js +19 -1
- package/esm/models/mcpcallitem.d.ts +17 -1
- package/esm/models/mcpcallitem.js +18 -0
- package/esm/models/mcpservertool.d.ts +78 -69
- package/esm/models/mcpservertool.js +135 -105
- package/esm/models/mcpservertoolopenrouter.d.ts +28 -0
- package/esm/models/mcpservertoolopenrouter.js +20 -0
- package/esm/models/mcpservertoolparameters.d.ts +152 -0
- package/esm/models/mcpservertoolparameters.js +134 -0
- package/esm/models/openairesponsestoolchoiceunion.d.ts +3 -2
- package/esm/models/openairesponsestoolchoiceunion.js +3 -0
- package/esm/models/operations/listbyokkeys.d.ts +1 -0
- package/esm/models/operations/listbyokkeys.js +1 -0
- package/esm/models/outputitemmcpapprovalrequest.d.ts +14 -0
- package/esm/models/outputitemmcpapprovalrequest.js +23 -0
- package/esm/models/outputitemmcpcall.d.ts +74 -0
- package/esm/models/outputitemmcpcall.js +94 -0
- package/esm/models/outputitemmcplisttools.d.ts +25 -0
- package/esm/models/outputitemmcplisttools.js +37 -0
- package/esm/models/outputitems.d.ts +3 -0
- package/esm/models/outputitems.js +2 -0
- package/esm/models/providername.d.ts +1 -0
- package/esm/models/providername.js +1 -0
- package/esm/models/provideroptions.d.ts +6 -0
- package/esm/models/provideroptions.js +1 -0
- package/esm/models/providerresponse.d.ts +1 -0
- package/esm/models/providerresponse.js +1 -0
- package/esm/models/responsesrequest.d.ts +9 -0
- package/esm/models/responsesrequest.js +3 -0
- package/esm/models/toolchoicemcp.d.ts +33 -0
- package/esm/models/toolchoicemcp.js +42 -0
- package/esm/models/toolsearchoutputitem.d.ts +5 -4
- package/esm/models/toolsearchoutputitem.js +3 -0
- package/esm/models/updateworkspacerequest.d.ts +1 -0
- package/esm/models/updateworkspacerequest.js +1 -0
- package/esm/models/videogenerationrequest.d.ts +6 -0
- package/esm/models/videogenerationrequest.js +1 -0
- package/esm/sdk/sdk.d.ts +0 -9
- package/esm/sdk/sdk.js +1 -7
- package/jsr.json +1 -1
- package/package.json +8 -8
- package/esm/funcs/call-model.d.ts +0 -67
- package/esm/funcs/call-model.js +0 -98
- package/esm/lib/anthropic-compat.d.ts +0 -51
- package/esm/lib/anthropic-compat.js +0 -222
- package/esm/lib/async-params.d.ts +0 -107
- package/esm/lib/async-params.js +0 -88
- package/esm/lib/chat-compat.d.ts +0 -47
- package/esm/lib/chat-compat.js +0 -111
- package/esm/lib/claude-constants.d.ts +0 -22
- package/esm/lib/claude-constants.js +0 -20
- package/esm/lib/claude-type-guards.d.ts +0 -10
- package/esm/lib/claude-type-guards.js +0 -70
- package/esm/lib/conversation-state.d.ts +0 -63
- package/esm/lib/conversation-state.js +0 -210
- package/esm/lib/model-result.d.ts +0 -373
- package/esm/lib/model-result.js +0 -1414
- package/esm/lib/next-turn-params.d.ts +0 -30
- package/esm/lib/next-turn-params.js +0 -135
- package/esm/lib/reusable-stream.d.ts +0 -39
- package/esm/lib/reusable-stream.js +0 -192
- package/esm/lib/stop-conditions.d.ts +0 -80
- package/esm/lib/stop-conditions.js +0 -104
- package/esm/lib/stream-transformers.d.ts +0 -118
- package/esm/lib/stream-transformers.js +0 -852
- package/esm/lib/stream-type-guards.d.ts +0 -49
- package/esm/lib/stream-type-guards.js +0 -85
- package/esm/lib/tool-context.d.ts +0 -68
- package/esm/lib/tool-context.js +0 -175
- package/esm/lib/tool-event-broadcaster.d.ts +0 -44
- package/esm/lib/tool-event-broadcaster.js +0 -146
- package/esm/lib/tool-executor.d.ts +0 -74
- package/esm/lib/tool-executor.js +0 -267
- package/esm/lib/tool-orchestrator.d.ts +0 -52
- package/esm/lib/tool-orchestrator.js +0 -180
- package/esm/lib/tool-types.d.ts +0 -573
- package/esm/lib/tool-types.js +0 -80
- package/esm/lib/tool.d.ts +0 -108
- package/esm/lib/tool.js +0 -74
- package/esm/lib/turn-context.d.ts +0 -52
- package/esm/lib/turn-context.js +0 -59
package/esm/lib/tool-executor.js
DELETED
|
@@ -1,267 +0,0 @@
|
|
|
1
|
-
import * as z4 from 'zod/v4';
|
|
2
|
-
import { hasExecuteFunction, isGeneratorTool, isRegularExecuteTool } from './tool-types.js';
|
|
3
|
-
import { buildToolExecuteContext } from './tool-context.js';
|
|
4
|
-
// Re-export ZodError for convenience
|
|
5
|
-
export const ZodError = z4.ZodError;
|
|
6
|
-
/**
|
|
7
|
-
* Typeguard to check if a value is a non-null object (not an array).
|
|
8
|
-
*/
|
|
9
|
-
function isNonNullObject(value) {
|
|
10
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
11
|
-
}
|
|
12
|
-
export function sanitizeJsonSchema(obj) {
|
|
13
|
-
if (obj === null || typeof obj !== 'object') {
|
|
14
|
-
return obj;
|
|
15
|
-
}
|
|
16
|
-
if (Array.isArray(obj)) {
|
|
17
|
-
return obj.map(sanitizeJsonSchema);
|
|
18
|
-
}
|
|
19
|
-
// At this point, obj is a non-null, non-array object
|
|
20
|
-
// Use typeguard to narrow the type for type-safe property access
|
|
21
|
-
if (!isNonNullObject(obj)) {
|
|
22
|
-
return obj;
|
|
23
|
-
}
|
|
24
|
-
const result = {};
|
|
25
|
-
for (const key of Object.keys(obj)) {
|
|
26
|
-
if (!key.startsWith('~')) {
|
|
27
|
-
result[key] = sanitizeJsonSchema(obj[key]);
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
return result;
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Typeguard to check if a value is a valid Zod schema compatible with zod/v4.
|
|
34
|
-
* Zod schemas have a _zod property that contains schema metadata.
|
|
35
|
-
*/
|
|
36
|
-
function isZodSchema(value) {
|
|
37
|
-
if (typeof value !== 'object' || value === null) {
|
|
38
|
-
return false;
|
|
39
|
-
}
|
|
40
|
-
if (!('_zod' in value)) {
|
|
41
|
-
return false;
|
|
42
|
-
}
|
|
43
|
-
// After the 'in' check, TypeScript knows value has _zod property
|
|
44
|
-
return typeof value._zod === 'object';
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Convert a Zod schema to JSON Schema using Zod v4's toJSONSchema function.
|
|
48
|
-
* Accepts ZodType from the main zod package for user compatibility.
|
|
49
|
-
* The resulting schema is sanitized to remove metadata properties (like ~standard)
|
|
50
|
-
* that would cause 400 errors with downstream providers.
|
|
51
|
-
*/
|
|
52
|
-
export function convertZodToJsonSchema(zodSchema) {
|
|
53
|
-
if (!isZodSchema(zodSchema)) {
|
|
54
|
-
throw new Error('Invalid Zod schema provided');
|
|
55
|
-
}
|
|
56
|
-
// Use draft-7 as it's closest to OpenAPI 3.0's JSON Schema variant
|
|
57
|
-
const jsonSchema = z4.toJSONSchema(zodSchema, {
|
|
58
|
-
target: 'draft-7',
|
|
59
|
-
});
|
|
60
|
-
// jsonSchema is always a Record<string, unknown> from toJSONSchema
|
|
61
|
-
// The overloaded sanitizeJsonSchema preserves this type
|
|
62
|
-
return sanitizeJsonSchema(jsonSchema);
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* Convert tools to OpenRouter API format
|
|
66
|
-
* Accepts readonly arrays for better type compatibility
|
|
67
|
-
*/
|
|
68
|
-
export function convertToolsToAPIFormat(tools) {
|
|
69
|
-
return tools.map((tool) => ({
|
|
70
|
-
type: 'function',
|
|
71
|
-
name: tool.function.name,
|
|
72
|
-
description: tool.function.description || null,
|
|
73
|
-
strict: null,
|
|
74
|
-
parameters: convertZodToJsonSchema(tool.function.inputSchema),
|
|
75
|
-
}));
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* Validate tool input against Zod schema
|
|
79
|
-
* @throws ZodError if validation fails
|
|
80
|
-
*/
|
|
81
|
-
export function validateToolInput(schema, args) {
|
|
82
|
-
return z4.parse(schema, args);
|
|
83
|
-
}
|
|
84
|
-
/**
|
|
85
|
-
* Validate tool output against Zod schema
|
|
86
|
-
* @throws ZodError if validation fails
|
|
87
|
-
*/
|
|
88
|
-
export function validateToolOutput(schema, result) {
|
|
89
|
-
return z4.parse(schema, result);
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* Try to validate a value against a Zod schema without throwing
|
|
93
|
-
* @returns true if validation succeeds, false otherwise
|
|
94
|
-
*/
|
|
95
|
-
function tryValidate(schema, value) {
|
|
96
|
-
const result = z4.safeParse(schema, value);
|
|
97
|
-
return result.success;
|
|
98
|
-
}
|
|
99
|
-
/**
|
|
100
|
-
* Parse tool call arguments from JSON string.
|
|
101
|
-
* Treats empty/whitespace-only strings as an empty object — some providers
|
|
102
|
-
* return `arguments: ""` for tools that take no parameters.
|
|
103
|
-
*/
|
|
104
|
-
export function parseToolCallArguments(argumentsString) {
|
|
105
|
-
const trimmed = argumentsString.trim();
|
|
106
|
-
if (!trimmed) {
|
|
107
|
-
return {};
|
|
108
|
-
}
|
|
109
|
-
try {
|
|
110
|
-
return JSON.parse(trimmed);
|
|
111
|
-
}
|
|
112
|
-
catch (error) {
|
|
113
|
-
throw new Error(`Failed to parse tool call arguments: ${error instanceof Error ? error.message : String(error)}`);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
/**
|
|
117
|
-
* Build a ToolExecuteContext for a tool from a TurnContext and optional context store
|
|
118
|
-
*/
|
|
119
|
-
function buildExecuteCtx(tool, turnContext, contextStore, sharedSchema) {
|
|
120
|
-
return buildToolExecuteContext(turnContext, contextStore, tool.function.name, tool.function.contextSchema, sharedSchema);
|
|
121
|
-
}
|
|
122
|
-
/**
|
|
123
|
-
* Execute a regular (non-generator) tool
|
|
124
|
-
*/
|
|
125
|
-
export async function executeRegularTool(tool, toolCall, context, contextStore, sharedSchema) {
|
|
126
|
-
if (!isRegularExecuteTool(tool)) {
|
|
127
|
-
throw new Error(`Tool "${toolCall.name}" is not a regular execute tool or has no execute function`);
|
|
128
|
-
}
|
|
129
|
-
try {
|
|
130
|
-
const validatedInput = validateToolInput(tool.function.inputSchema, toolCall.arguments);
|
|
131
|
-
const executeContext = buildExecuteCtx(tool, context, contextStore, sharedSchema);
|
|
132
|
-
// Execute tool with context
|
|
133
|
-
const result = await Promise.resolve(tool.function.execute(validatedInput, executeContext));
|
|
134
|
-
// Validate output if schema is provided
|
|
135
|
-
if (tool.function.outputSchema) {
|
|
136
|
-
const validatedOutput = validateToolOutput(tool.function.outputSchema, result);
|
|
137
|
-
return {
|
|
138
|
-
toolCallId: toolCall.id,
|
|
139
|
-
toolName: toolCall.name,
|
|
140
|
-
result: validatedOutput,
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
return {
|
|
144
|
-
toolCallId: toolCall.id,
|
|
145
|
-
toolName: toolCall.name,
|
|
146
|
-
result,
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
catch (error) {
|
|
150
|
-
return {
|
|
151
|
-
toolCallId: toolCall.id,
|
|
152
|
-
toolName: toolCall.name,
|
|
153
|
-
result: null,
|
|
154
|
-
error: error instanceof Error ? error : new Error(String(error)),
|
|
155
|
-
};
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
/**
|
|
159
|
-
* Execute a generator tool and collect preliminary and final results
|
|
160
|
-
* - Intermediate yields are validated against eventSchema (preliminary events)
|
|
161
|
-
* - Last yield is validated against outputSchema (final result sent to model)
|
|
162
|
-
* - Generator must emit at least one value
|
|
163
|
-
*/
|
|
164
|
-
export async function executeGeneratorTool(tool, toolCall, context, onPreliminaryResult, contextStore, sharedSchema) {
|
|
165
|
-
if (!isGeneratorTool(tool)) {
|
|
166
|
-
throw new Error(`Tool "${toolCall.name}" is not a generator tool`);
|
|
167
|
-
}
|
|
168
|
-
try {
|
|
169
|
-
const validatedInput = validateToolInput(tool.function.inputSchema, toolCall.arguments);
|
|
170
|
-
const executeContext = buildExecuteCtx(tool, context, contextStore, sharedSchema);
|
|
171
|
-
const preliminaryResults = [];
|
|
172
|
-
let finalResult;
|
|
173
|
-
let hasFinalResult = false;
|
|
174
|
-
let lastEmittedValue;
|
|
175
|
-
let hasEmittedValue = false;
|
|
176
|
-
const iterator = tool.function.execute(validatedInput, executeContext);
|
|
177
|
-
let iterResult = await iterator.next();
|
|
178
|
-
while (!iterResult.done) {
|
|
179
|
-
const event = iterResult.value;
|
|
180
|
-
lastEmittedValue = event;
|
|
181
|
-
hasEmittedValue = true;
|
|
182
|
-
const matchesOutputSchema = tryValidate(tool.function.outputSchema, event);
|
|
183
|
-
const matchesEventSchema = tryValidate(tool.function.eventSchema, event);
|
|
184
|
-
if (matchesOutputSchema && !matchesEventSchema && !hasFinalResult) {
|
|
185
|
-
finalResult = validateToolOutput(tool.function.outputSchema, event);
|
|
186
|
-
hasFinalResult = true;
|
|
187
|
-
}
|
|
188
|
-
else {
|
|
189
|
-
const validatedPreliminary = validateToolOutput(tool.function.eventSchema, event);
|
|
190
|
-
preliminaryResults.push(validatedPreliminary);
|
|
191
|
-
if (onPreliminaryResult) {
|
|
192
|
-
onPreliminaryResult(toolCall.id, validatedPreliminary);
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
iterResult = await iterator.next();
|
|
196
|
-
}
|
|
197
|
-
if (iterResult.value !== undefined) {
|
|
198
|
-
finalResult = validateToolOutput(tool.function.outputSchema, iterResult.value);
|
|
199
|
-
hasFinalResult = true;
|
|
200
|
-
}
|
|
201
|
-
if (!hasFinalResult) {
|
|
202
|
-
if (!hasEmittedValue) {
|
|
203
|
-
throw new Error(`Generator tool "${toolCall.name}" completed without emitting any values or returning a result`);
|
|
204
|
-
}
|
|
205
|
-
finalResult = validateToolOutput(tool.function.outputSchema, lastEmittedValue);
|
|
206
|
-
}
|
|
207
|
-
return {
|
|
208
|
-
toolCallId: toolCall.id,
|
|
209
|
-
toolName: toolCall.name,
|
|
210
|
-
result: finalResult,
|
|
211
|
-
preliminaryResults,
|
|
212
|
-
};
|
|
213
|
-
}
|
|
214
|
-
catch (error) {
|
|
215
|
-
return {
|
|
216
|
-
toolCallId: toolCall.id,
|
|
217
|
-
toolName: toolCall.name,
|
|
218
|
-
result: null,
|
|
219
|
-
error: error instanceof Error ? error : new Error(String(error)),
|
|
220
|
-
};
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
/**
|
|
224
|
-
* Execute a tool call
|
|
225
|
-
* Automatically detects if it's a regular or generator tool
|
|
226
|
-
*/
|
|
227
|
-
export async function executeTool(tool, toolCall, context, onPreliminaryResult, contextStore, sharedSchema) {
|
|
228
|
-
if (!hasExecuteFunction(tool)) {
|
|
229
|
-
throw new Error(`Tool "${toolCall.name}" has no execute function. Use manual tool execution.`);
|
|
230
|
-
}
|
|
231
|
-
if (isGeneratorTool(tool)) {
|
|
232
|
-
return executeGeneratorTool(tool, toolCall, context, onPreliminaryResult, contextStore, sharedSchema);
|
|
233
|
-
}
|
|
234
|
-
return executeRegularTool(tool, toolCall, context, contextStore, sharedSchema);
|
|
235
|
-
}
|
|
236
|
-
/**
|
|
237
|
-
* Find a tool by name in the tools array
|
|
238
|
-
*/
|
|
239
|
-
export function findToolByName(tools, name) {
|
|
240
|
-
return tools.find((tool) => tool.function.name === name);
|
|
241
|
-
}
|
|
242
|
-
/**
|
|
243
|
-
* Format tool execution result as a string for sending to the model
|
|
244
|
-
*/
|
|
245
|
-
export function formatToolResultForModel(result) {
|
|
246
|
-
if (result.error) {
|
|
247
|
-
return JSON.stringify({
|
|
248
|
-
error: result.error.message,
|
|
249
|
-
toolName: result.toolName,
|
|
250
|
-
});
|
|
251
|
-
}
|
|
252
|
-
return JSON.stringify(result.result);
|
|
253
|
-
}
|
|
254
|
-
/**
|
|
255
|
-
* Create a user-friendly error message for tool execution errors
|
|
256
|
-
*/
|
|
257
|
-
export function formatToolExecutionError(error, toolCall) {
|
|
258
|
-
if (error instanceof ZodError) {
|
|
259
|
-
const issues = error.issues.map((issue) => ({
|
|
260
|
-
path: issue.path.join('.'),
|
|
261
|
-
message: issue.message,
|
|
262
|
-
}));
|
|
263
|
-
return `Tool "${toolCall.name}" validation error:\n${JSON.stringify(issues, null, 2)}`;
|
|
264
|
-
}
|
|
265
|
-
return `Tool "${toolCall.name}" execution error: ${error.message}`;
|
|
266
|
-
}
|
|
267
|
-
//# sourceMappingURL=tool-executor.js.map
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import type { InputsUnion } from '../models/inputsunion.js';
|
|
2
|
-
import type { OpenResponsesResult } from '../models/openresponsesresult.js';
|
|
3
|
-
import type { ResponsesRequest } from '../models/responsesrequest.js';
|
|
4
|
-
import type { APITool, Tool, ToolExecutionResult } from './tool-types.js';
|
|
5
|
-
/**
|
|
6
|
-
* Options for tool execution
|
|
7
|
-
*/
|
|
8
|
-
export interface ToolExecutionOptions {
|
|
9
|
-
onPreliminaryResult?: (toolCallId: string, result: unknown) => void;
|
|
10
|
-
}
|
|
11
|
-
/**
|
|
12
|
-
* Result of the tool execution loop
|
|
13
|
-
*/
|
|
14
|
-
export interface ToolOrchestrationResult {
|
|
15
|
-
finalResponse: OpenResponsesResult;
|
|
16
|
-
allResponses: OpenResponsesResult[];
|
|
17
|
-
toolExecutionResults: ToolExecutionResult<Tool>[];
|
|
18
|
-
conversationInput: InputsUnion;
|
|
19
|
-
}
|
|
20
|
-
/**
|
|
21
|
-
* Execute tool calls and manage multi-turn conversations
|
|
22
|
-
* This orchestrates the loop of: request -> tool calls -> execute -> send results -> repeat
|
|
23
|
-
*
|
|
24
|
-
* @param sendRequest - Function to send a request and get a response
|
|
25
|
-
* @param initialInput - Starting input for the conversation
|
|
26
|
-
* @param initialRequest - Full initial request with all parameters
|
|
27
|
-
* @param tools - Enhanced tools with Zod schemas and execute functions
|
|
28
|
-
* @param apiTools - Converted tools in API format (JSON Schema)
|
|
29
|
-
* @param options - Execution options
|
|
30
|
-
* @returns Result containing final response and all execution data
|
|
31
|
-
*/
|
|
32
|
-
export declare function executeToolLoop(sendRequest: (input: InputsUnion, tools: APITool[]) => Promise<OpenResponsesResult>, initialInput: InputsUnion, initialRequest: ResponsesRequest, tools: Tool[], apiTools: APITool[], options?: ToolExecutionOptions): Promise<ToolOrchestrationResult>;
|
|
33
|
-
/**
|
|
34
|
-
* Convert tool execution results to a map for easy lookup
|
|
35
|
-
*/
|
|
36
|
-
export declare function toolResultsToMap(results: ToolExecutionResult<Tool>[]): Map<string, {
|
|
37
|
-
result: unknown;
|
|
38
|
-
preliminaryResults?: unknown[];
|
|
39
|
-
}>;
|
|
40
|
-
/**
|
|
41
|
-
* Build a summary of tool executions for debugging/logging
|
|
42
|
-
*/
|
|
43
|
-
export declare function summarizeToolExecutions(results: ToolExecutionResult<Tool>[]): string;
|
|
44
|
-
/**
|
|
45
|
-
* Check if any tool executions had errors
|
|
46
|
-
*/
|
|
47
|
-
export declare function hasToolExecutionErrors(results: ToolExecutionResult<Tool>[]): boolean;
|
|
48
|
-
/**
|
|
49
|
-
* Get all tool execution errors
|
|
50
|
-
*/
|
|
51
|
-
export declare function getToolExecutionErrors(results: ToolExecutionResult<Tool>[]): Error[];
|
|
52
|
-
//# sourceMappingURL=tool-orchestrator.d.ts.map
|
|
@@ -1,180 +0,0 @@
|
|
|
1
|
-
import { extractToolCallsFromResponse, responseHasToolCalls } from './stream-transformers.js';
|
|
2
|
-
import { isFunctionCallItem } from './stream-type-guards.js';
|
|
3
|
-
import { executeTool, findToolByName } from './tool-executor.js';
|
|
4
|
-
import { hasExecuteFunction } from './tool-types.js';
|
|
5
|
-
import { buildTurnContext } from './turn-context.js';
|
|
6
|
-
import { executeNextTurnParamsFunctions, applyNextTurnParamsToRequest } from './next-turn-params.js';
|
|
7
|
-
/**
|
|
8
|
-
* Execute tool calls and manage multi-turn conversations
|
|
9
|
-
* This orchestrates the loop of: request -> tool calls -> execute -> send results -> repeat
|
|
10
|
-
*
|
|
11
|
-
* @param sendRequest - Function to send a request and get a response
|
|
12
|
-
* @param initialInput - Starting input for the conversation
|
|
13
|
-
* @param initialRequest - Full initial request with all parameters
|
|
14
|
-
* @param tools - Enhanced tools with Zod schemas and execute functions
|
|
15
|
-
* @param apiTools - Converted tools in API format (JSON Schema)
|
|
16
|
-
* @param options - Execution options
|
|
17
|
-
* @returns Result containing final response and all execution data
|
|
18
|
-
*/
|
|
19
|
-
export async function executeToolLoop(sendRequest, initialInput, initialRequest, tools, apiTools, options = {}) {
|
|
20
|
-
const onPreliminaryResult = options.onPreliminaryResult;
|
|
21
|
-
const allResponses = [];
|
|
22
|
-
const toolExecutionResults = [];
|
|
23
|
-
let conversationInput = initialInput;
|
|
24
|
-
let currentRequest = { ...initialRequest };
|
|
25
|
-
let currentRound = 0;
|
|
26
|
-
let currentResponse;
|
|
27
|
-
// Initial request
|
|
28
|
-
currentResponse = await sendRequest(conversationInput, apiTools);
|
|
29
|
-
allResponses.push(currentResponse);
|
|
30
|
-
// Loop until no more tool calls (model decides when to stop)
|
|
31
|
-
while (responseHasToolCalls(currentResponse)) {
|
|
32
|
-
currentRound++;
|
|
33
|
-
// Extract tool calls from response
|
|
34
|
-
const toolCalls = extractToolCallsFromResponse(currentResponse);
|
|
35
|
-
if (toolCalls.length === 0) {
|
|
36
|
-
break;
|
|
37
|
-
}
|
|
38
|
-
// Check if any tools have execute functions
|
|
39
|
-
const hasExecutableTools = toolCalls.some((toolCall) => {
|
|
40
|
-
const tool = findToolByName(tools, toolCall.name);
|
|
41
|
-
return tool && hasExecuteFunction(tool);
|
|
42
|
-
});
|
|
43
|
-
// If no executable tools, return (manual execution mode)
|
|
44
|
-
if (!hasExecutableTools) {
|
|
45
|
-
break;
|
|
46
|
-
}
|
|
47
|
-
// Execute all tool calls in parallel (parallel tool calling)
|
|
48
|
-
const toolCallPromises = toolCalls.map(async (toolCall) => {
|
|
49
|
-
const tool = findToolByName(tools, toolCall.name);
|
|
50
|
-
if (!tool) {
|
|
51
|
-
// Tool not found in definitions
|
|
52
|
-
return {
|
|
53
|
-
toolCallId: toolCall.id,
|
|
54
|
-
toolName: toolCall.name,
|
|
55
|
-
result: null,
|
|
56
|
-
error: new Error(`Tool "${toolCall.name}" not found in tool definitions`),
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
if (!hasExecuteFunction(tool)) {
|
|
60
|
-
// Tool has no execute function - return null to filter out
|
|
61
|
-
return null;
|
|
62
|
-
}
|
|
63
|
-
// Find the raw tool call from the response output
|
|
64
|
-
const rawToolCall = currentResponse.output.find((item) => isFunctionCallItem(item) && item.callId === toolCall.id);
|
|
65
|
-
if (!rawToolCall) {
|
|
66
|
-
throw new Error(`Could not find raw tool call for ${toolCall.id}`);
|
|
67
|
-
}
|
|
68
|
-
// Convert to FunctionCallItem format
|
|
69
|
-
const openResponsesToolCall = {
|
|
70
|
-
type: 'function_call',
|
|
71
|
-
callId: rawToolCall.callId,
|
|
72
|
-
name: rawToolCall.name,
|
|
73
|
-
arguments: rawToolCall.arguments,
|
|
74
|
-
id: rawToolCall.callId,
|
|
75
|
-
status: rawToolCall.status,
|
|
76
|
-
};
|
|
77
|
-
// Build turn context with full information
|
|
78
|
-
const turnContext = buildTurnContext({
|
|
79
|
-
numberOfTurns: currentRound,
|
|
80
|
-
toolCall: openResponsesToolCall,
|
|
81
|
-
turnRequest: currentRequest,
|
|
82
|
-
});
|
|
83
|
-
// Execute the tool
|
|
84
|
-
return executeTool(tool, toolCall, turnContext, onPreliminaryResult);
|
|
85
|
-
});
|
|
86
|
-
// Wait for all tool executions to complete in parallel
|
|
87
|
-
const settledResults = await Promise.allSettled(toolCallPromises);
|
|
88
|
-
// Process settled results, handling both fulfilled and rejected promises
|
|
89
|
-
const roundResults = [];
|
|
90
|
-
settledResults.forEach((settled, i) => {
|
|
91
|
-
const toolCall = toolCalls[i];
|
|
92
|
-
if (!toolCall)
|
|
93
|
-
return;
|
|
94
|
-
if (settled.status === "fulfilled") {
|
|
95
|
-
if (settled.value !== null) {
|
|
96
|
-
roundResults.push(settled.value);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
else {
|
|
100
|
-
// Promise rejected - create error result
|
|
101
|
-
roundResults.push({
|
|
102
|
-
toolCallId: toolCall.id,
|
|
103
|
-
toolName: toolCall.name,
|
|
104
|
-
result: null,
|
|
105
|
-
error: settled.reason instanceof Error
|
|
106
|
-
? settled.reason
|
|
107
|
-
: new Error(String(settled.reason)),
|
|
108
|
-
});
|
|
109
|
-
}
|
|
110
|
-
});
|
|
111
|
-
toolExecutionResults.push(...roundResults);
|
|
112
|
-
// Execute nextTurnParams functions for tools that were called
|
|
113
|
-
const computedParams = await executeNextTurnParamsFunctions(toolCalls, tools, currentRequest);
|
|
114
|
-
// Apply computed parameters to request
|
|
115
|
-
if (Object.keys(computedParams).length > 0) {
|
|
116
|
-
currentRequest = applyNextTurnParamsToRequest(currentRequest, computedParams);
|
|
117
|
-
conversationInput = currentRequest.input ?? conversationInput;
|
|
118
|
-
}
|
|
119
|
-
// Build array input with all output from previous response plus tool results
|
|
120
|
-
// The API expects continuation via previousResponseId, not by including outputs
|
|
121
|
-
// For now, we'll keep the conversation going via previousResponseId
|
|
122
|
-
// conversationInput is updated above if nextTurnParams modified it
|
|
123
|
-
// Note: The OpenRouter Responses API uses previousResponseId for continuation
|
|
124
|
-
// Tool results are automatically associated with the previous response's tool calls
|
|
125
|
-
// Send updated conversation to API - this should use previousResponseId
|
|
126
|
-
currentResponse = await sendRequest(conversationInput, apiTools);
|
|
127
|
-
allResponses.push(currentResponse);
|
|
128
|
-
}
|
|
129
|
-
return {
|
|
130
|
-
finalResponse: currentResponse,
|
|
131
|
-
allResponses,
|
|
132
|
-
toolExecutionResults,
|
|
133
|
-
conversationInput,
|
|
134
|
-
};
|
|
135
|
-
}
|
|
136
|
-
/**
|
|
137
|
-
* Convert tool execution results to a map for easy lookup
|
|
138
|
-
*/
|
|
139
|
-
export function toolResultsToMap(results) {
|
|
140
|
-
const map = new Map();
|
|
141
|
-
for (const result of results) {
|
|
142
|
-
map.set(result.toolCallId, {
|
|
143
|
-
result: result.result,
|
|
144
|
-
preliminaryResults: result.preliminaryResults,
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
return map;
|
|
148
|
-
}
|
|
149
|
-
/**
|
|
150
|
-
* Build a summary of tool executions for debugging/logging
|
|
151
|
-
*/
|
|
152
|
-
export function summarizeToolExecutions(results) {
|
|
153
|
-
const lines = [];
|
|
154
|
-
for (const result of results) {
|
|
155
|
-
if (result.error) {
|
|
156
|
-
lines.push(`❌ ${result.toolName} (${result.toolCallId}): ERROR - ${result.error.message}`);
|
|
157
|
-
}
|
|
158
|
-
else {
|
|
159
|
-
const prelimCount = result.preliminaryResults?.length ?? 0;
|
|
160
|
-
const prelimInfo = prelimCount > 0 ? ` (${prelimCount} preliminary results)` : '';
|
|
161
|
-
lines.push(`✅ ${result.toolName} (${result.toolCallId}): SUCCESS${prelimInfo}`);
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
return lines.join('\n');
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Check if any tool executions had errors
|
|
168
|
-
*/
|
|
169
|
-
export function hasToolExecutionErrors(results) {
|
|
170
|
-
return results.some((result) => result.error !== undefined);
|
|
171
|
-
}
|
|
172
|
-
/**
|
|
173
|
-
* Get all tool execution errors
|
|
174
|
-
*/
|
|
175
|
-
export function getToolExecutionErrors(results) {
|
|
176
|
-
return results
|
|
177
|
-
.filter((result) => result.error !== undefined)
|
|
178
|
-
.map((result) => result.error);
|
|
179
|
-
}
|
|
180
|
-
//# sourceMappingURL=tool-orchestrator.js.map
|