@openrouter/sdk 1.5.55 → 1.5.57

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.
Files changed (104) hide show
  1. package/esm/lib/config.d.ts +2 -2
  2. package/esm/lib/config.js +2 -2
  3. package/esm/models/additionaltoolsitem.d.ts +5 -4
  4. package/esm/models/additionaltoolsitem.js +3 -0
  5. package/esm/models/alignmentresponsesrejected.d.ts +4 -1
  6. package/esm/models/alignmentresponsesrejected.js +6 -0
  7. package/esm/models/byokproviderslug.d.ts +1 -0
  8. package/esm/models/byokproviderslug.js +1 -0
  9. package/esm/models/createworkspacerequest.d.ts +1 -0
  10. package/esm/models/createworkspacerequest.js +1 -0
  11. package/esm/models/decisionschoicequestion.d.ts +4 -4
  12. package/esm/models/decisionschoicequestion.js +1 -5
  13. package/esm/models/decisionsnoulquestion.d.ts +12 -12
  14. package/esm/models/decisionsnoulquestion.js +3 -7
  15. package/esm/models/decisionsscorequestion.d.ts +4 -4
  16. package/esm/models/decisionsscorequestion.js +1 -5
  17. package/esm/models/imagegenerationproviderpreferences.d.ts +6 -0
  18. package/esm/models/imagegenerationproviderpreferences.js +1 -0
  19. package/esm/models/imagegenerationrequest.d.ts +51 -4
  20. package/esm/models/imagegenerationrequest.js +32 -1
  21. package/esm/models/index.d.ts +6 -0
  22. package/esm/models/index.js +6 -0
  23. package/esm/models/mcpapprovalrequestitem.d.ts +7 -0
  24. package/esm/models/mcpapprovalrequestitem.js +19 -1
  25. package/esm/models/mcpcallitem.d.ts +17 -1
  26. package/esm/models/mcpcallitem.js +18 -0
  27. package/esm/models/mcpservertool.d.ts +78 -69
  28. package/esm/models/mcpservertool.js +135 -105
  29. package/esm/models/mcpservertoolopenrouter.d.ts +28 -0
  30. package/esm/models/mcpservertoolopenrouter.js +20 -0
  31. package/esm/models/mcpservertoolparameters.d.ts +152 -0
  32. package/esm/models/mcpservertoolparameters.js +134 -0
  33. package/esm/models/openairesponsestoolchoiceunion.d.ts +3 -2
  34. package/esm/models/openairesponsestoolchoiceunion.js +3 -0
  35. package/esm/models/operations/listbyokkeys.d.ts +1 -0
  36. package/esm/models/operations/listbyokkeys.js +1 -0
  37. package/esm/models/outputitemmcpapprovalrequest.d.ts +14 -0
  38. package/esm/models/outputitemmcpapprovalrequest.js +23 -0
  39. package/esm/models/outputitemmcpcall.d.ts +74 -0
  40. package/esm/models/outputitemmcpcall.js +94 -0
  41. package/esm/models/outputitemmcplisttools.d.ts +25 -0
  42. package/esm/models/outputitemmcplisttools.js +37 -0
  43. package/esm/models/outputitems.d.ts +3 -0
  44. package/esm/models/outputitems.js +2 -0
  45. package/esm/models/providername.d.ts +1 -0
  46. package/esm/models/providername.js +1 -0
  47. package/esm/models/provideroptions.d.ts +6 -0
  48. package/esm/models/provideroptions.js +1 -0
  49. package/esm/models/providerresponse.d.ts +1 -0
  50. package/esm/models/providerresponse.js +1 -0
  51. package/esm/models/responsesrequest.d.ts +9 -0
  52. package/esm/models/responsesrequest.js +3 -0
  53. package/esm/models/toolchoicemcp.d.ts +33 -0
  54. package/esm/models/toolchoicemcp.js +42 -0
  55. package/esm/models/toolsearchoutputitem.d.ts +5 -4
  56. package/esm/models/toolsearchoutputitem.js +3 -0
  57. package/esm/models/updateworkspacerequest.d.ts +1 -0
  58. package/esm/models/updateworkspacerequest.js +1 -0
  59. package/esm/models/videogenerationrequest.d.ts +6 -0
  60. package/esm/models/videogenerationrequest.js +1 -0
  61. package/esm/sdk/sdk.d.ts +0 -9
  62. package/esm/sdk/sdk.js +1 -7
  63. package/jsr.json +1 -1
  64. package/package.json +5 -5
  65. package/esm/funcs/call-model.d.ts +0 -67
  66. package/esm/funcs/call-model.js +0 -98
  67. package/esm/lib/anthropic-compat.d.ts +0 -51
  68. package/esm/lib/anthropic-compat.js +0 -222
  69. package/esm/lib/async-params.d.ts +0 -107
  70. package/esm/lib/async-params.js +0 -88
  71. package/esm/lib/chat-compat.d.ts +0 -47
  72. package/esm/lib/chat-compat.js +0 -111
  73. package/esm/lib/claude-constants.d.ts +0 -22
  74. package/esm/lib/claude-constants.js +0 -20
  75. package/esm/lib/claude-type-guards.d.ts +0 -10
  76. package/esm/lib/claude-type-guards.js +0 -70
  77. package/esm/lib/conversation-state.d.ts +0 -63
  78. package/esm/lib/conversation-state.js +0 -210
  79. package/esm/lib/model-result.d.ts +0 -373
  80. package/esm/lib/model-result.js +0 -1414
  81. package/esm/lib/next-turn-params.d.ts +0 -30
  82. package/esm/lib/next-turn-params.js +0 -135
  83. package/esm/lib/reusable-stream.d.ts +0 -39
  84. package/esm/lib/reusable-stream.js +0 -192
  85. package/esm/lib/stop-conditions.d.ts +0 -80
  86. package/esm/lib/stop-conditions.js +0 -104
  87. package/esm/lib/stream-transformers.d.ts +0 -118
  88. package/esm/lib/stream-transformers.js +0 -852
  89. package/esm/lib/stream-type-guards.d.ts +0 -49
  90. package/esm/lib/stream-type-guards.js +0 -85
  91. package/esm/lib/tool-context.d.ts +0 -68
  92. package/esm/lib/tool-context.js +0 -175
  93. package/esm/lib/tool-event-broadcaster.d.ts +0 -44
  94. package/esm/lib/tool-event-broadcaster.js +0 -146
  95. package/esm/lib/tool-executor.d.ts +0 -74
  96. package/esm/lib/tool-executor.js +0 -267
  97. package/esm/lib/tool-orchestrator.d.ts +0 -52
  98. package/esm/lib/tool-orchestrator.js +0 -180
  99. package/esm/lib/tool-types.d.ts +0 -573
  100. package/esm/lib/tool-types.js +0 -80
  101. package/esm/lib/tool.d.ts +0 -108
  102. package/esm/lib/tool.js +0 -74
  103. package/esm/lib/turn-context.d.ts +0 -52
  104. package/esm/lib/turn-context.js +0 -59
@@ -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
@@ -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
@@ -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
@@ -1,111 +0,0 @@
1
- import { EasyInputMessageRoleUser, EasyInputMessageRoleSystem, EasyInputMessageRoleAssistant, EasyInputMessageRoleDeveloper, } from "../models/easyinputmessage.js";
2
- import { extractMessageFromResponse } from "./stream-transformers.js";
3
- /**
4
- * Type guard for ChatToolMessage
5
- */
6
- function isToolResponseMessage(msg) {
7
- return msg.role === "tool";
8
- }
9
- /**
10
- * Type guard for ChatAssistantMessage
11
- */
12
- function isAssistantMessage(msg) {
13
- return msg.role === "assistant";
14
- }
15
- /**
16
- * Maps chat role strings to OpenResponses role types
17
- */
18
- function mapChatRole(role) {
19
- switch (role) {
20
- case "user":
21
- return EasyInputMessageRoleUser.User;
22
- case "system":
23
- return EasyInputMessageRoleSystem.System;
24
- case "assistant":
25
- return EasyInputMessageRoleAssistant.Assistant;
26
- case "developer":
27
- return EasyInputMessageRoleDeveloper.Developer;
28
- default: {
29
- const exhaustiveCheck = role;
30
- throw new Error(`Unhandled role type: ${exhaustiveCheck}`);
31
- }
32
- }
33
- }
34
- /**
35
- * Convert message content to a string representation.
36
- * Handles string, null, undefined, and object content types.
37
- */
38
- function contentToString(content) {
39
- if (typeof content === "string") {
40
- return content;
41
- }
42
- if (content === null || content === undefined) {
43
- return "";
44
- }
45
- return JSON.stringify(content);
46
- }
47
- /**
48
- * Convert OpenAI chat-style messages to OpenResponses input format.
49
- *
50
- * This function transforms Message[] (OpenAI chat format) to OpenResponsesInput
51
- * format that can be passed directly to callModel().
52
- *
53
- * @example
54
- * ```typescript
55
- * import { fromChatMessages } from '@openrouter/sdk';
56
- *
57
- * const chatMessages = [
58
- * { role: "system", content: "You are a helpful assistant." },
59
- * { role: "user", content: "Hello!" },
60
- * ];
61
- *
62
- * const response = openrouter.callModel({
63
- * model: "openai/gpt-4",
64
- * input: fromChatMessages(chatMessages),
65
- * });
66
- * ```
67
- */
68
- export function fromChatMessages(messages) {
69
- return messages.map((msg) => {
70
- if (isToolResponseMessage(msg)) {
71
- return {
72
- type: "function_call_output",
73
- callId: msg.toolCallId,
74
- output: contentToString(msg.content),
75
- };
76
- }
77
- if (isAssistantMessage(msg)) {
78
- return {
79
- role: mapChatRole("assistant"),
80
- content: contentToString(msg.content),
81
- };
82
- }
83
- // System, user, developer messages
84
- return {
85
- role: mapChatRole(msg.role),
86
- content: contentToString(msg.content),
87
- };
88
- });
89
- }
90
- /**
91
- * Convert an OpenResponses response to OpenAI chat message format.
92
- *
93
- * This function transforms OpenResponsesResult to ChatAssistantMessage
94
- * (OpenAI chat format) for compatibility with code expecting chat responses.
95
- *
96
- * @example
97
- * ```typescript
98
- * import { toChatMessage } from '@openrouter/sdk';
99
- *
100
- * const response = await openrouter.callModel({
101
- * model: "openai/gpt-4",
102
- * input: "Hello!",
103
- * });
104
- *
105
- * const openResponsesResult = await response.getResponse();
106
- * const chatMessage = toChatMessage(openResponsesResult);
107
- * // chatMessage is now { role: "assistant", content: "..." }
108
- * ```
109
- */
110
- export const toChatMessage = extractMessageFromResponse;
111
- //# sourceMappingURL=chat-compat.js.map
@@ -1,22 +0,0 @@
1
- /**
2
- * Claude-specific content block types
3
- * Used for detecting Claude message format
4
- */
5
- export declare const ClaudeContentBlockType: {
6
- readonly Text: "text";
7
- readonly Image: "image";
8
- readonly ToolUse: "tool_use";
9
- readonly ToolResult: "tool_result";
10
- };
11
- export type ClaudeContentBlockType = (typeof ClaudeContentBlockType)[keyof typeof ClaudeContentBlockType];
12
- /**
13
- * Message roles that are NOT supported in Claude format
14
- * Used for distinguishing Claude vs OpenAI format
15
- */
16
- export declare const NonClaudeMessageRole: {
17
- readonly System: "system";
18
- readonly Developer: "developer";
19
- readonly Tool: "tool";
20
- };
21
- export type NonClaudeMessageRole = (typeof NonClaudeMessageRole)[keyof typeof NonClaudeMessageRole];
22
- //# sourceMappingURL=claude-constants.d.ts.map
@@ -1,20 +0,0 @@
1
- /**
2
- * Claude-specific content block types
3
- * Used for detecting Claude message format
4
- */
5
- export const ClaudeContentBlockType = {
6
- Text: "text",
7
- Image: "image",
8
- ToolUse: "tool_use",
9
- ToolResult: "tool_result",
10
- };
11
- /**
12
- * Message roles that are NOT supported in Claude format
13
- * Used for distinguishing Claude vs OpenAI format
14
- */
15
- export const NonClaudeMessageRole = {
16
- System: "system",
17
- Developer: "developer",
18
- Tool: "tool",
19
- };
20
- //# sourceMappingURL=claude-constants.js.map
@@ -1,10 +0,0 @@
1
- import type { ClaudeMessageParam } from "../models/claude-message.js";
2
- /**
3
- * Check if input is in Claude message format
4
- * Uses structural analysis to detect Claude-specific patterns
5
- *
6
- * @param input - Input to check
7
- * @returns True if input appears to be Claude format
8
- */
9
- export declare function isClaudeStyleMessages(input: unknown): input is ClaudeMessageParam[];
10
- //# sourceMappingURL=claude-type-guards.d.ts.map