@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/funcs/call-model.js
DELETED
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
import { ModelResult } from '../lib/model-result.js';
|
|
2
|
-
import { convertToolsToAPIFormat } from '../lib/tool-executor.js';
|
|
3
|
-
/**
|
|
4
|
-
* Get a response with multiple consumption patterns
|
|
5
|
-
*
|
|
6
|
-
* @remarks
|
|
7
|
-
* Creates a response using the OpenResponses API and returns
|
|
8
|
-
* a wrapper that allows consuming the response in multiple ways:
|
|
9
|
-
*
|
|
10
|
-
* - `await response.getText()` - Get just the text content (tools auto-executed)
|
|
11
|
-
* - `await response.getResponse()` - Get full response with usage data (inputTokens, cachedTokens, etc.)
|
|
12
|
-
* - `for await (const delta of response.getTextStream())` - Stream text deltas
|
|
13
|
-
* - `for await (const delta of response.getReasoningStream())` - Stream reasoning deltas
|
|
14
|
-
* - `for await (const event of response.getToolStream())` - Stream tool events (incl. preliminary results)
|
|
15
|
-
* - `for await (const toolCall of response.getToolCallsStream())` - Stream structured tool calls
|
|
16
|
-
* - `await response.getToolCalls()` - Get all tool calls from completed response
|
|
17
|
-
* - `for await (const msg of response.getNewMessagesStream())` - Stream cumulative message snapshots
|
|
18
|
-
* - `for await (const event of response.getFullResponsesStream())` - Stream all events (incl. tool preliminary)
|
|
19
|
-
*
|
|
20
|
-
* All consumption patterns can be used concurrently on the same response.
|
|
21
|
-
*
|
|
22
|
-
* **Context:**
|
|
23
|
-
*
|
|
24
|
-
* Tools can declare a `contextSchema` to receive typed context data.
|
|
25
|
-
* The `context` parameter on callModel is typed as the intersection of all tool schemas:
|
|
26
|
-
*
|
|
27
|
-
* @example
|
|
28
|
-
* ```typescript
|
|
29
|
-
* const result = callModel(client, {
|
|
30
|
-
* model: 'gpt-4',
|
|
31
|
-
* input: 'Hello',
|
|
32
|
-
* tools: [weatherTool, dbTool] as const,
|
|
33
|
-
* context: {
|
|
34
|
-
* get_weather: { apiKey: 'sk-...' },
|
|
35
|
-
* db_query: { dbUrl: 'postgres://...' },
|
|
36
|
-
* },
|
|
37
|
-
* });
|
|
38
|
-
* ```
|
|
39
|
-
*
|
|
40
|
-
* Context can also be a function or async function:
|
|
41
|
-
* ```typescript
|
|
42
|
-
* context: (turn) => ({
|
|
43
|
-
* get_weather: { apiKey: turn.numberOfTurns > 1 ? refreshedKey : initialKey },
|
|
44
|
-
* })
|
|
45
|
-
* ```
|
|
46
|
-
*
|
|
47
|
-
* **Stop Conditions:**
|
|
48
|
-
*
|
|
49
|
-
* Control when tool execution stops using the `stopWhen` parameter:
|
|
50
|
-
*
|
|
51
|
-
* @example
|
|
52
|
-
* ```typescript
|
|
53
|
-
* stopWhen: stepCountIs(3)
|
|
54
|
-
* stopWhen: [stepCountIs(10), maxCost(0.50), hasToolCall('finalize')]
|
|
55
|
-
* ```
|
|
56
|
-
*
|
|
57
|
-
* Default: `stepCountIs(5)` if not specified
|
|
58
|
-
*/
|
|
59
|
-
export function callModel(client, request, options) {
|
|
60
|
-
// Destructure state management options along with tools and stopWhen
|
|
61
|
-
const { tools, stopWhen, state, requireApproval, approveToolCalls, rejectToolCalls, context, sharedContextSchema, onTurnStart, onTurnEnd, ...apiRequest } = request;
|
|
62
|
-
// Convert tools to API format - no cast needed now that convertToolsToAPIFormat accepts readonly
|
|
63
|
-
const apiTools = tools ? convertToolsToAPIFormat(tools) : undefined;
|
|
64
|
-
// Build the request with converted tools
|
|
65
|
-
// Note: async functions are resolved later in ModelResult.executeToolsIfNeeded()
|
|
66
|
-
// The request can have async fields (functions) or sync fields, and the tools are converted to API format
|
|
67
|
-
const finalRequest = {
|
|
68
|
-
...apiRequest,
|
|
69
|
-
};
|
|
70
|
-
if (apiTools !== undefined) {
|
|
71
|
-
finalRequest['tools'] = apiTools;
|
|
72
|
-
}
|
|
73
|
-
// Inject x-openrouter-callmodel header into every callModel request
|
|
74
|
-
const callModelOptions = {
|
|
75
|
-
...options,
|
|
76
|
-
headers: {
|
|
77
|
-
...Object.fromEntries(new Headers(options?.headers ?? options?.fetchOptions?.headers ?? undefined)),
|
|
78
|
-
'x-openrouter-callmodel': 'true',
|
|
79
|
-
},
|
|
80
|
-
};
|
|
81
|
-
return new ModelResult({
|
|
82
|
-
client,
|
|
83
|
-
request: finalRequest,
|
|
84
|
-
options: callModelOptions,
|
|
85
|
-
tools,
|
|
86
|
-
...(stopWhen !== undefined && { stopWhen }),
|
|
87
|
-
// Pass state management options
|
|
88
|
-
...(state !== undefined && { state }),
|
|
89
|
-
...(requireApproval !== undefined && { requireApproval }),
|
|
90
|
-
...(approveToolCalls !== undefined && { approveToolCalls }),
|
|
91
|
-
...(rejectToolCalls !== undefined && { rejectToolCalls }),
|
|
92
|
-
...(context !== undefined && { context }),
|
|
93
|
-
...(sharedContextSchema !== undefined && { sharedContextSchema }),
|
|
94
|
-
...(onTurnStart !== undefined && { onTurnStart }),
|
|
95
|
-
...(onTurnEnd !== undefined && { onTurnEnd }),
|
|
96
|
-
});
|
|
97
|
-
}
|
|
98
|
-
//# sourceMappingURL=call-model.js.map
|
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
import type { InputsUnion } from '../models/inputsunion.js';
|
|
2
|
-
import type { ClaudeMessageParam } from '../models/claude-message.js';
|
|
3
|
-
import { convertToClaudeMessage } from './stream-transformers.js';
|
|
4
|
-
/**
|
|
5
|
-
* Convert Anthropic Claude-style messages to OpenResponses input format.
|
|
6
|
-
*
|
|
7
|
-
* This function transforms ClaudeMessageParam[] (Anthropic SDK format) to
|
|
8
|
-
* OpenResponsesInput format that can be passed directly to callModel().
|
|
9
|
-
*
|
|
10
|
-
* Note: Some Claude features are lost in conversion as OpenRouter doesn't support them:
|
|
11
|
-
* - cache_control on content blocks
|
|
12
|
-
* - is_error flag on tool_result blocks
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* ```typescript
|
|
16
|
-
* import { fromClaudeMessages } from '@openrouter/sdk';
|
|
17
|
-
*
|
|
18
|
-
* const claudeMessages = [
|
|
19
|
-
* { role: "user", content: "Hello!" },
|
|
20
|
-
* { role: "assistant", content: "Hi there!" },
|
|
21
|
-
* ];
|
|
22
|
-
*
|
|
23
|
-
* const response = openrouter.callModel({
|
|
24
|
-
* model: "anthropic/claude-3-sonnet",
|
|
25
|
-
* input: fromClaudeMessages(claudeMessages),
|
|
26
|
-
* });
|
|
27
|
-
* ```
|
|
28
|
-
*/
|
|
29
|
-
export declare function fromClaudeMessages(messages: ClaudeMessageParam[]): InputsUnion;
|
|
30
|
-
/**
|
|
31
|
-
* Convert an OpenResponses response to Anthropic Claude message format.
|
|
32
|
-
*
|
|
33
|
-
* This function transforms OpenResponsesResult to ClaudeMessage
|
|
34
|
-
* (Anthropic SDK format) for compatibility with code expecting Claude responses.
|
|
35
|
-
*
|
|
36
|
-
* @example
|
|
37
|
-
* ```typescript
|
|
38
|
-
* import { toClaudeMessage } from '@openrouter/sdk';
|
|
39
|
-
*
|
|
40
|
-
* const response = await openrouter.callModel({
|
|
41
|
-
* model: "anthropic/claude-3-sonnet",
|
|
42
|
-
* input: "Hello!",
|
|
43
|
-
* });
|
|
44
|
-
*
|
|
45
|
-
* const openResponsesResult = await response.getResponse();
|
|
46
|
-
* const claudeMessage = toClaudeMessage(openResponsesResult);
|
|
47
|
-
* // claudeMessage is now compatible with Anthropic SDK types
|
|
48
|
-
* ```
|
|
49
|
-
*/
|
|
50
|
-
export declare const toClaudeMessage: typeof convertToClaudeMessage;
|
|
51
|
-
//# sourceMappingURL=anthropic-compat.d.ts.map
|
|
@@ -1,222 +0,0 @@
|
|
|
1
|
-
import { EasyInputMessageRoleAssistant, EasyInputMessageRoleUser, } from '../models/easyinputmessage.js';
|
|
2
|
-
import { InputMessageItemRoleUser, InputMessageItemRoleDeveloper } from '../models/inputmessageitem.js';
|
|
3
|
-
import { convertToClaudeMessage } from './stream-transformers.js';
|
|
4
|
-
/**
|
|
5
|
-
* Maps Claude role strings to OpenResponses role types
|
|
6
|
-
*/
|
|
7
|
-
function mapClaudeRole(role) {
|
|
8
|
-
if (role === 'user') {
|
|
9
|
-
return EasyInputMessageRoleUser.User;
|
|
10
|
-
}
|
|
11
|
-
return EasyInputMessageRoleAssistant.Assistant;
|
|
12
|
-
}
|
|
13
|
-
/**
|
|
14
|
-
* Creates a properly typed EasyInputMessage
|
|
15
|
-
*/
|
|
16
|
-
function createEasyInputMessage(role, content) {
|
|
17
|
-
return {
|
|
18
|
-
role: mapClaudeRole(role),
|
|
19
|
-
content,
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* Creates a properly typed FunctionCallOutputItem
|
|
24
|
-
*/
|
|
25
|
-
function createFunctionCallOutput(callId, output) {
|
|
26
|
-
return {
|
|
27
|
-
type: "function_call_output",
|
|
28
|
-
callId,
|
|
29
|
-
output,
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Convert Anthropic Claude-style messages to OpenResponses input format.
|
|
34
|
-
*
|
|
35
|
-
* This function transforms ClaudeMessageParam[] (Anthropic SDK format) to
|
|
36
|
-
* OpenResponsesInput format that can be passed directly to callModel().
|
|
37
|
-
*
|
|
38
|
-
* Note: Some Claude features are lost in conversion as OpenRouter doesn't support them:
|
|
39
|
-
* - cache_control on content blocks
|
|
40
|
-
* - is_error flag on tool_result blocks
|
|
41
|
-
*
|
|
42
|
-
* @example
|
|
43
|
-
* ```typescript
|
|
44
|
-
* import { fromClaudeMessages } from '@openrouter/sdk';
|
|
45
|
-
*
|
|
46
|
-
* const claudeMessages = [
|
|
47
|
-
* { role: "user", content: "Hello!" },
|
|
48
|
-
* { role: "assistant", content: "Hi there!" },
|
|
49
|
-
* ];
|
|
50
|
-
*
|
|
51
|
-
* const response = openrouter.callModel({
|
|
52
|
-
* model: "anthropic/claude-3-sonnet",
|
|
53
|
-
* input: fromClaudeMessages(claudeMessages),
|
|
54
|
-
* });
|
|
55
|
-
* ```
|
|
56
|
-
*/
|
|
57
|
-
export function fromClaudeMessages(messages) {
|
|
58
|
-
const result = [];
|
|
59
|
-
for (const msg of messages) {
|
|
60
|
-
const { role, content } = msg;
|
|
61
|
-
if (typeof content === 'string') {
|
|
62
|
-
result.push(createEasyInputMessage(role, content));
|
|
63
|
-
continue;
|
|
64
|
-
}
|
|
65
|
-
// Separate content blocks into categories for clearer processing
|
|
66
|
-
const textBlocks = [];
|
|
67
|
-
const imageBlocks = [];
|
|
68
|
-
const toolUseBlocks = [];
|
|
69
|
-
const toolResultBlocks = [];
|
|
70
|
-
for (const block of content) {
|
|
71
|
-
switch (block.type) {
|
|
72
|
-
case 'text':
|
|
73
|
-
textBlocks.push(block);
|
|
74
|
-
break;
|
|
75
|
-
case 'image':
|
|
76
|
-
imageBlocks.push(block);
|
|
77
|
-
break;
|
|
78
|
-
case 'tool_use':
|
|
79
|
-
toolUseBlocks.push(block);
|
|
80
|
-
break;
|
|
81
|
-
case 'tool_result':
|
|
82
|
-
toolResultBlocks.push(block);
|
|
83
|
-
break;
|
|
84
|
-
default: {
|
|
85
|
-
// Exhaustiveness check - TypeScript will error if we don't handle all block types
|
|
86
|
-
const exhaustiveCheck = block;
|
|
87
|
-
throw new Error(`Unhandled content block type: ${JSON.stringify(exhaustiveCheck)}`);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
// Process tool use blocks first (they go directly to result)
|
|
92
|
-
for (const toolUseBlock of toolUseBlocks) {
|
|
93
|
-
result.push({
|
|
94
|
-
type: 'function_call',
|
|
95
|
-
callId: toolUseBlock.id,
|
|
96
|
-
name: toolUseBlock.name,
|
|
97
|
-
arguments: JSON.stringify(toolUseBlock.input),
|
|
98
|
-
id: toolUseBlock.id,
|
|
99
|
-
status: 'completed',
|
|
100
|
-
});
|
|
101
|
-
}
|
|
102
|
-
// Process tool result blocks
|
|
103
|
-
for (const toolResultBlock of toolResultBlocks) {
|
|
104
|
-
let toolOutput = '';
|
|
105
|
-
if (typeof toolResultBlock.content === 'string') {
|
|
106
|
-
toolOutput = toolResultBlock.content;
|
|
107
|
-
}
|
|
108
|
-
else {
|
|
109
|
-
// Extract text and handle images separately
|
|
110
|
-
const textParts = [];
|
|
111
|
-
const imageParts = [];
|
|
112
|
-
for (const part of toolResultBlock.content) {
|
|
113
|
-
if (part.type === 'text') {
|
|
114
|
-
textParts.push(part.text);
|
|
115
|
-
}
|
|
116
|
-
else if (part.type === 'image') {
|
|
117
|
-
imageParts.push(part);
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
toolOutput = textParts.join('');
|
|
121
|
-
// Map images to image_generation_call items
|
|
122
|
-
imageParts.forEach((imagePart, i) => {
|
|
123
|
-
let imageUrl;
|
|
124
|
-
if (imagePart.source.type === 'url') {
|
|
125
|
-
imageUrl = imagePart.source.url;
|
|
126
|
-
}
|
|
127
|
-
else if (imagePart.source.type === 'base64') {
|
|
128
|
-
imageUrl = `data:${imagePart.source.media_type};base64,${imagePart.source.data}`;
|
|
129
|
-
}
|
|
130
|
-
else {
|
|
131
|
-
const exhaustiveCheck = imagePart.source;
|
|
132
|
-
throw new Error(`Unhandled image source type: ${exhaustiveCheck}`);
|
|
133
|
-
}
|
|
134
|
-
result.push({
|
|
135
|
-
type: 'image_generation_call',
|
|
136
|
-
id: `${toolResultBlock.tool_use_id}-image-${i}`,
|
|
137
|
-
result: imageUrl,
|
|
138
|
-
status: 'completed',
|
|
139
|
-
});
|
|
140
|
-
});
|
|
141
|
-
}
|
|
142
|
-
// Add the function call output for the text portion (if any)
|
|
143
|
-
if (toolOutput.length > 0) {
|
|
144
|
-
result.push(createFunctionCallOutput(toolResultBlock.tool_use_id, toolOutput));
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
// Process text and image blocks (these become message content)
|
|
148
|
-
if (textBlocks.length > 0 || imageBlocks.length > 0) {
|
|
149
|
-
const contentItems = [];
|
|
150
|
-
// Add text blocks
|
|
151
|
-
for (const textBlock of textBlocks) {
|
|
152
|
-
contentItems.push({
|
|
153
|
-
type: 'input_text',
|
|
154
|
-
text: textBlock.text,
|
|
155
|
-
});
|
|
156
|
-
}
|
|
157
|
-
// Add image blocks
|
|
158
|
-
for (const imageBlock of imageBlocks) {
|
|
159
|
-
let imageUrl;
|
|
160
|
-
if (imageBlock.source.type === 'url') {
|
|
161
|
-
imageUrl = imageBlock.source.url;
|
|
162
|
-
}
|
|
163
|
-
else if (imageBlock.source.type === 'base64') {
|
|
164
|
-
imageUrl = `data:${imageBlock.source.media_type};base64,${imageBlock.source.data}`;
|
|
165
|
-
}
|
|
166
|
-
else {
|
|
167
|
-
const exhaustiveCheck = imageBlock.source;
|
|
168
|
-
throw new Error(`Unhandled image source type: ${exhaustiveCheck}`);
|
|
169
|
-
}
|
|
170
|
-
contentItems.push({
|
|
171
|
-
type: 'input_image',
|
|
172
|
-
detail: 'auto',
|
|
173
|
-
imageUrl,
|
|
174
|
-
});
|
|
175
|
-
}
|
|
176
|
-
// Determine output format based on content
|
|
177
|
-
if (imageBlocks.length > 0) {
|
|
178
|
-
// Use structured format for messages with images
|
|
179
|
-
result.push({
|
|
180
|
-
type: 'message',
|
|
181
|
-
role: role === 'user'
|
|
182
|
-
? InputMessageItemRoleUser.User
|
|
183
|
-
: InputMessageItemRoleDeveloper.Developer,
|
|
184
|
-
content: contentItems,
|
|
185
|
-
});
|
|
186
|
-
}
|
|
187
|
-
else {
|
|
188
|
-
// Use simple string format for text-only messages
|
|
189
|
-
const textContent = contentItems
|
|
190
|
-
.filter((item) => item.type === 'input_text')
|
|
191
|
-
.map((item) => item.text)
|
|
192
|
-
.join('');
|
|
193
|
-
if (textContent.length > 0) {
|
|
194
|
-
result.push(createEasyInputMessage(role, textContent));
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
return result;
|
|
200
|
-
}
|
|
201
|
-
/**
|
|
202
|
-
* Convert an OpenResponses response to Anthropic Claude message format.
|
|
203
|
-
*
|
|
204
|
-
* This function transforms OpenResponsesResult to ClaudeMessage
|
|
205
|
-
* (Anthropic SDK format) for compatibility with code expecting Claude responses.
|
|
206
|
-
*
|
|
207
|
-
* @example
|
|
208
|
-
* ```typescript
|
|
209
|
-
* import { toClaudeMessage } from '@openrouter/sdk';
|
|
210
|
-
*
|
|
211
|
-
* const response = await openrouter.callModel({
|
|
212
|
-
* model: "anthropic/claude-3-sonnet",
|
|
213
|
-
* input: "Hello!",
|
|
214
|
-
* });
|
|
215
|
-
*
|
|
216
|
-
* const openResponsesResult = await response.getResponse();
|
|
217
|
-
* const claudeMessage = toClaudeMessage(openResponsesResult);
|
|
218
|
-
* // claudeMessage is now compatible with Anthropic SDK types
|
|
219
|
-
* ```
|
|
220
|
-
*/
|
|
221
|
-
export const toClaudeMessage = convertToClaudeMessage;
|
|
222
|
-
//# sourceMappingURL=anthropic-compat.js.map
|
|
@@ -1,107 +0,0 @@
|
|
|
1
|
-
import type { OpenResponsesResult } from '../models/openresponsesresult.js';
|
|
2
|
-
import type { ResponsesRequest } from '../models/responsesrequest.js';
|
|
3
|
-
import type { ToolContextMapWithShared, ParsedToolCall, StateAccessor, StopWhen, Tool, TurnContext } from './tool-types.js';
|
|
4
|
-
import type { ContextInput } from './tool-context.js';
|
|
5
|
-
export type { Tool } from './tool-types.js';
|
|
6
|
-
/**
|
|
7
|
-
* A field can be either a value of type T or a function that computes T
|
|
8
|
-
*/
|
|
9
|
-
export type FieldOrAsyncFunction<T> = T | ((context: TurnContext) => T | Promise<T>);
|
|
10
|
-
/**
|
|
11
|
-
* Base input type for callModel without approval-related fields
|
|
12
|
-
*/
|
|
13
|
-
type BaseCallModelInput<TTools extends readonly Tool[] = readonly Tool[], TShared extends Record<string, unknown> = Record<string, never>> = {
|
|
14
|
-
[K in keyof Omit<ResponsesRequest, 'stream' | 'tools'>]?: FieldOrAsyncFunction<ResponsesRequest[K]>;
|
|
15
|
-
} & {
|
|
16
|
-
tools?: TTools;
|
|
17
|
-
stopWhen?: StopWhen<TTools>;
|
|
18
|
-
/** Typed context data passed to tools via contextSchema. Includes optional `shared` key. */
|
|
19
|
-
context?: ContextInput<ToolContextMapWithShared<TTools, TShared>>;
|
|
20
|
-
/**
|
|
21
|
-
* Call-level approval check - overrides tool-level requireApproval setting
|
|
22
|
-
* Receives the tool call and turn context, can be sync or async
|
|
23
|
-
*/
|
|
24
|
-
requireApproval?: (toolCall: ParsedToolCall<TTools[number]>, context: TurnContext) => boolean | Promise<boolean>;
|
|
25
|
-
/**
|
|
26
|
-
* Callback invoked at the start of each tool execution turn
|
|
27
|
-
* Receives the turn context with the current turn number
|
|
28
|
-
*/
|
|
29
|
-
onTurnStart?: (context: TurnContext) => void | Promise<void>;
|
|
30
|
-
/**
|
|
31
|
-
* Callback invoked at the end of each tool execution turn
|
|
32
|
-
* Receives the turn context and the completed response for that turn
|
|
33
|
-
*/
|
|
34
|
-
onTurnEnd?: (context: TurnContext, response: OpenResponsesResult) => void | Promise<void>;
|
|
35
|
-
};
|
|
36
|
-
/**
|
|
37
|
-
* Approval params when state is provided (allows approve/reject)
|
|
38
|
-
*/
|
|
39
|
-
type ApprovalParamsWithState<TTools extends readonly Tool[] = readonly Tool[]> = {
|
|
40
|
-
/** State accessor for multi-turn persistence and approval gates */
|
|
41
|
-
state: StateAccessor<TTools>;
|
|
42
|
-
/** Tool call IDs to approve (for resuming from awaiting_approval status) */
|
|
43
|
-
approveToolCalls?: string[];
|
|
44
|
-
/** Tool call IDs to reject (for resuming from awaiting_approval status) */
|
|
45
|
-
rejectToolCalls?: string[];
|
|
46
|
-
};
|
|
47
|
-
/**
|
|
48
|
-
* Approval params when state is NOT provided (forbids approve/reject)
|
|
49
|
-
*/
|
|
50
|
-
type ApprovalParamsWithoutState = {
|
|
51
|
-
/** State accessor for multi-turn persistence and approval gates */
|
|
52
|
-
state?: undefined;
|
|
53
|
-
/** Not allowed without state - will cause type error */
|
|
54
|
-
approveToolCalls?: never;
|
|
55
|
-
/** Not allowed without state - will cause type error */
|
|
56
|
-
rejectToolCalls?: never;
|
|
57
|
-
};
|
|
58
|
-
/**
|
|
59
|
-
* Input type for callModel function
|
|
60
|
-
* Each field can independently be a static value or a function that computes the value
|
|
61
|
-
* Generic over TTools to enable proper type inference for stopWhen conditions
|
|
62
|
-
*
|
|
63
|
-
* Type enforcement:
|
|
64
|
-
* - `approveToolCalls` and `rejectToolCalls` are only valid when `state` is provided
|
|
65
|
-
* - Using these without `state` will cause a TypeScript error
|
|
66
|
-
*/
|
|
67
|
-
export type CallModelInput<TTools extends readonly Tool[] = readonly Tool[], TShared extends Record<string, unknown> = Record<string, never>> = BaseCallModelInput<TTools, TShared> & (ApprovalParamsWithState<TTools> | ApprovalParamsWithoutState);
|
|
68
|
-
/**
|
|
69
|
-
* CallModelInput variant that requires state - use when approval workflows are needed
|
|
70
|
-
*/
|
|
71
|
-
export type CallModelInputWithState<TTools extends readonly Tool[] = readonly Tool[], TShared extends Record<string, unknown> = Record<string, never>> = BaseCallModelInput<TTools, TShared> & ApprovalParamsWithState<TTools>;
|
|
72
|
-
/**
|
|
73
|
-
* Resolved CallModelInput (all functions evaluated to values)
|
|
74
|
-
* This is the type after all async functions have been resolved to their values
|
|
75
|
-
*/
|
|
76
|
-
export type ResolvedCallModelInput = Omit<ResponsesRequest, 'stream' | 'tools'> & {
|
|
77
|
-
tools?: never;
|
|
78
|
-
};
|
|
79
|
-
/**
|
|
80
|
-
* Resolve all async functions in CallModelInput to their values
|
|
81
|
-
*
|
|
82
|
-
* @param input - Input with possible functions
|
|
83
|
-
* @param context - Turn context for function execution
|
|
84
|
-
* @returns Resolved input with all values (no functions)
|
|
85
|
-
*
|
|
86
|
-
* @example
|
|
87
|
-
* ```typescript
|
|
88
|
-
* const resolved = await resolveAsyncFunctions(
|
|
89
|
-
* {
|
|
90
|
-
* model: 'gpt-4',
|
|
91
|
-
* temperature: (ctx) => ctx.numberOfTurns * 0.1,
|
|
92
|
-
* input: 'Hello',
|
|
93
|
-
* },
|
|
94
|
-
* { numberOfTurns: 2 }
|
|
95
|
-
* );
|
|
96
|
-
* // resolved.temperature === 0.2
|
|
97
|
-
* ```
|
|
98
|
-
*/
|
|
99
|
-
export declare function resolveAsyncFunctions<TTools extends readonly Tool[] = readonly Tool[]>(input: CallModelInput<TTools>, context: TurnContext): Promise<ResolvedCallModelInput>;
|
|
100
|
-
/**
|
|
101
|
-
* Check if input has any async functions that need resolution
|
|
102
|
-
*
|
|
103
|
-
* @param input - Input to check
|
|
104
|
-
* @returns True if any field is a function
|
|
105
|
-
*/
|
|
106
|
-
export declare function hasAsyncFunctions(input: unknown): boolean;
|
|
107
|
-
//# sourceMappingURL=async-params.d.ts.map
|
package/esm/lib/async-params.js
DELETED
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Type guard to check if a value is a parameter function
|
|
3
|
-
* Parameter functions take TurnContext and return a value or promise
|
|
4
|
-
*/
|
|
5
|
-
function isParameterFunction(value) {
|
|
6
|
-
return typeof value === 'function';
|
|
7
|
-
}
|
|
8
|
-
/**
|
|
9
|
-
* Build a resolved request object from entries
|
|
10
|
-
* This validates the structure matches the expected ResolvedCallModelInput shape
|
|
11
|
-
*/
|
|
12
|
-
function buildResolvedRequest(entries) {
|
|
13
|
-
const obj = Object.fromEntries(entries);
|
|
14
|
-
return obj;
|
|
15
|
-
}
|
|
16
|
-
/**
|
|
17
|
-
* Resolve all async functions in CallModelInput to their values
|
|
18
|
-
*
|
|
19
|
-
* @param input - Input with possible functions
|
|
20
|
-
* @param context - Turn context for function execution
|
|
21
|
-
* @returns Resolved input with all values (no functions)
|
|
22
|
-
*
|
|
23
|
-
* @example
|
|
24
|
-
* ```typescript
|
|
25
|
-
* const resolved = await resolveAsyncFunctions(
|
|
26
|
-
* {
|
|
27
|
-
* model: 'gpt-4',
|
|
28
|
-
* temperature: (ctx) => ctx.numberOfTurns * 0.1,
|
|
29
|
-
* input: 'Hello',
|
|
30
|
-
* },
|
|
31
|
-
* { numberOfTurns: 2 }
|
|
32
|
-
* );
|
|
33
|
-
* // resolved.temperature === 0.2
|
|
34
|
-
* ```
|
|
35
|
-
*/
|
|
36
|
-
export async function resolveAsyncFunctions(input, context) {
|
|
37
|
-
// Build array of resolved entries
|
|
38
|
-
const resolvedEntries = [];
|
|
39
|
-
// Fields that should not be sent to the API (client-side only)
|
|
40
|
-
const clientOnlyFields = new Set([
|
|
41
|
-
'stopWhen', // Handled separately in ModelResult
|
|
42
|
-
'state', // Client-side state management
|
|
43
|
-
'requireApproval', // Client-side approval check function
|
|
44
|
-
'approveToolCalls', // Client-side approval decisions
|
|
45
|
-
'rejectToolCalls', // Client-side rejection decisions
|
|
46
|
-
'context', // Passed through via GetResponseOptions, not sent to API
|
|
47
|
-
'sharedContextSchema', // Client-side schema for shared context validation
|
|
48
|
-
'onTurnStart', // Client-side turn start callback
|
|
49
|
-
'onTurnEnd', // Client-side turn end callback
|
|
50
|
-
]);
|
|
51
|
-
// Iterate over all keys in the input
|
|
52
|
-
for (const [key, value] of Object.entries(input)) {
|
|
53
|
-
// Skip client-only fields - they're handled separately and shouldn't be sent to the API
|
|
54
|
-
// Note: tools are already in API format at this point (converted in callModel()), so we include them
|
|
55
|
-
if (clientOnlyFields.has(key)) {
|
|
56
|
-
continue;
|
|
57
|
-
}
|
|
58
|
-
if (isParameterFunction(value)) {
|
|
59
|
-
try {
|
|
60
|
-
// Execute the function with context and store the result
|
|
61
|
-
const result = await Promise.resolve(value(context));
|
|
62
|
-
resolvedEntries.push([key, result]);
|
|
63
|
-
}
|
|
64
|
-
catch (error) {
|
|
65
|
-
// Wrap errors with context about which field failed
|
|
66
|
-
throw new Error(`Failed to resolve async function for field "${key}": ${error instanceof Error ? error.message : String(error)}`);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
else {
|
|
70
|
-
// Not a function, use as-is
|
|
71
|
-
resolvedEntries.push([key, value]);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
return buildResolvedRequest(resolvedEntries);
|
|
75
|
-
}
|
|
76
|
-
/**
|
|
77
|
-
* Check if input has any async functions that need resolution
|
|
78
|
-
*
|
|
79
|
-
* @param input - Input to check
|
|
80
|
-
* @returns True if any field is a function
|
|
81
|
-
*/
|
|
82
|
-
export function hasAsyncFunctions(input) {
|
|
83
|
-
if (!input || typeof input !== 'object') {
|
|
84
|
-
return false;
|
|
85
|
-
}
|
|
86
|
-
return Object.values(input).some((value) => typeof value === 'function');
|
|
87
|
-
}
|
|
88
|
-
//# sourceMappingURL=async-params.js.map
|
package/esm/lib/chat-compat.d.ts
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import type { ChatMessages } from "../models/chatmessages.js";
|
|
2
|
-
import type { InputsUnion } from "../models/inputsunion.js";
|
|
3
|
-
import { extractMessageFromResponse } from "./stream-transformers.js";
|
|
4
|
-
/**
|
|
5
|
-
* Convert OpenAI chat-style messages to OpenResponses input format.
|
|
6
|
-
*
|
|
7
|
-
* This function transforms Message[] (OpenAI chat format) to OpenResponsesInput
|
|
8
|
-
* format that can be passed directly to callModel().
|
|
9
|
-
*
|
|
10
|
-
* @example
|
|
11
|
-
* ```typescript
|
|
12
|
-
* import { fromChatMessages } from '@openrouter/sdk';
|
|
13
|
-
*
|
|
14
|
-
* const chatMessages = [
|
|
15
|
-
* { role: "system", content: "You are a helpful assistant." },
|
|
16
|
-
* { role: "user", content: "Hello!" },
|
|
17
|
-
* ];
|
|
18
|
-
*
|
|
19
|
-
* const response = openrouter.callModel({
|
|
20
|
-
* model: "openai/gpt-4",
|
|
21
|
-
* input: fromChatMessages(chatMessages),
|
|
22
|
-
* });
|
|
23
|
-
* ```
|
|
24
|
-
*/
|
|
25
|
-
export declare function fromChatMessages(messages: ChatMessages[]): InputsUnion;
|
|
26
|
-
/**
|
|
27
|
-
* Convert an OpenResponses response to OpenAI chat message format.
|
|
28
|
-
*
|
|
29
|
-
* This function transforms OpenResponsesResult to ChatAssistantMessage
|
|
30
|
-
* (OpenAI chat format) for compatibility with code expecting chat responses.
|
|
31
|
-
*
|
|
32
|
-
* @example
|
|
33
|
-
* ```typescript
|
|
34
|
-
* import { toChatMessage } from '@openrouter/sdk';
|
|
35
|
-
*
|
|
36
|
-
* const response = await openrouter.callModel({
|
|
37
|
-
* model: "openai/gpt-4",
|
|
38
|
-
* input: "Hello!",
|
|
39
|
-
* });
|
|
40
|
-
*
|
|
41
|
-
* const openResponsesResult = await response.getResponse();
|
|
42
|
-
* const chatMessage = toChatMessage(openResponsesResult);
|
|
43
|
-
* // chatMessage is now { role: "assistant", content: "..." }
|
|
44
|
-
* ```
|
|
45
|
-
*/
|
|
46
|
-
export declare const toChatMessage: typeof extractMessageFromResponse;
|
|
47
|
-
//# sourceMappingURL=chat-compat.d.ts.map
|