diff --git a/eslint.config.mjs b/eslint.config.mjs index 67bccfec..9c558468 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,22 +1,30 @@ -import globals from "globals"; -import pluginJs from "@eslint/js"; -import tseslint from "typescript-eslint"; +import pluginJs from '@eslint/js'; +import globals from 'globals'; +import tseslint from 'typescript-eslint'; /** @type {import('eslint').Linter.Config[]} */ export default [ - { files: ["**/*.{js,mjs,cjs,ts}"] }, - { languageOptions: { globals: globals.browser } }, + { + files: [ + '**/*.{js,mjs,cjs,ts}', + ], + }, + { + languageOptions: { + globals: globals.browser, + }, + }, pluginJs.configs.recommended, ...tseslint.configs.recommended, { rules: { - "no-constant-condition": "off", - "no-useless-escape": "off", + 'no-constant-condition': 'off', + 'no-useless-escape': 'off', // Handled by typescript compiler - "@typescript-eslint/no-unused-vars": "off", - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-empty-object-type": "off", - "@typescript-eslint/no-namespace": "off", + '@typescript-eslint/no-unused-vars': 'off', + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-empty-object-type': 'off', + '@typescript-eslint/no-namespace': 'off', }, }, ]; diff --git a/examples/anthropic-multimodal-tools.example.ts b/examples/anthropic-multimodal-tools.example.ts index ca643695..b2d537ee 100644 --- a/examples/anthropic-multimodal-tools.example.ts +++ b/examples/anthropic-multimodal-tools.example.ts @@ -1,4 +1,4 @@ -import dotenv from "dotenv"; +import dotenv from 'dotenv'; dotenv.config(); @@ -21,21 +21,17 @@ dotenv.config(); * bun run anthropic-multimodal-tools.example.ts */ -import type { ClaudeMessageParam } from "../src/models/claude-message.js"; -import { - OpenRouter, - fromClaudeMessages, - toClaudeMessage, - ToolType, -} from "../src/index.js"; -import { z } from "zod/v4"; - -if (!process.env["OPENROUTER_API_KEY"]) { - throw new Error("Missing OPENROUTER_API_KEY environment variable"); +import type { ClaudeMessageParam } from '../src/models/claude-message.js'; + +import { z } from 'zod/v4'; +import { fromClaudeMessages, OpenRouter, ToolType, toClaudeMessage } from '../src/index.js'; + +if (!process.env['OPENROUTER_API_KEY']) { + throw new Error('Missing OPENROUTER_API_KEY environment variable'); } const openRouter = new OpenRouter({ - apiKey: process.env["OPENROUTER_API_KEY"] ?? "", + apiKey: process.env['OPENROUTER_API_KEY'] ?? '', }); // Mock tool definition for image analysis @@ -43,11 +39,18 @@ const tools = [ { type: ToolType.Function, function: { - name: "analyze_image_details", - description: "Analyzes detailed visual features of an image including colors, objects, and composition", + name: 'analyze_image_details', + description: + 'Analyzes detailed visual features of an image including colors, objects, and composition', inputSchema: z.object({ - image_id: z.string().describe("The ID of the image to analyze"), - analysis_type: z.enum(["color_palette", "object_detection", "scene_classification"]).describe("Type of analysis to perform"), + image_id: z.string().describe('The ID of the image to analyze'), + analysis_type: z + .enum([ + 'color_palette', + 'object_detection', + 'scene_classification', + ]) + .describe('Type of analysis to perform'), }), outputSchema: z.object({ colors: z.array(z.string()).optional(), @@ -60,10 +63,11 @@ const tools = [ { type: ToolType.Function, function: { - name: "get_image_metadata", - description: "Retrieves metadata about an image such as dimensions, format, and creation date", + name: 'get_image_metadata', + description: + 'Retrieves metadata about an image such as dimensions, format, and creation date', inputSchema: z.object({ - image_id: z.string().describe("The ID of the image"), + image_id: z.string().describe('The ID of the image'), }), outputSchema: z.object({ width: z.number(), @@ -78,32 +82,34 @@ const tools = [ async function multiTurnMultimodalConversation() { // Using GPT-5 as requested - const model = "openai/gpt-5"; + const model = 'openai/gpt-5'; // Initialize message history with Claude-style message format // Turn 1: User sends an image with a question const messages: ClaudeMessageParam[] = [ { - role: "user", + role: 'user', content: [ { - type: "text", - text: "I have this image of a sunset landscape. Can you analyze its visual features?", + type: 'text', + text: 'I have this image of a sunset landscape. Can you analyze its visual features?', }, { - type: "image", + type: 'image', source: { - type: "url", - url: "https://images.unsplash.com/photo-1506905925346-21bda4d32df4", + type: 'url', + url: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4', }, }, ], }, ]; - console.log("=== Turn 1 ==="); - console.log("User: I have this image of a sunset landscape. Can you analyze its visual features?"); - console.log("User: [Image URL: https://images.unsplash.com/photo-1506905925346-21bda4d32df4]"); + console.log('=== Turn 1 ==='); + console.log( + 'User: I have this image of a sunset landscape. Can you analyze its visual features?', + ); + console.log('User: [Image URL: https://images.unsplash.com/photo-1506905925346-21bda4d32df4]'); console.log(); // First turn - convert Claude messages to OpenResponses format and call with tools @@ -111,24 +117,28 @@ async function multiTurnMultimodalConversation() { model, input: fromClaudeMessages(messages), tools, - toolChoice: "auto", + toolChoice: 'auto', }); // Get the response and convert back to Claude format const response1 = await result1.getResponse(); const claudeMessage1 = toClaudeMessage(response1); - console.log("Assistant response:"); - console.log("Stop reason:", claudeMessage1.stop_reason); + console.log('Assistant response:'); + console.log('Stop reason:', claudeMessage1.stop_reason); // Extract content and tool calls const textContent1: string[] = []; - const toolCalls1: Array<{ id: string; name: string; input: Record }> = []; + const toolCalls1: Array<{ + id: string; + name: string; + input: Record; + }> = []; for (const block of claudeMessage1.content) { - if (block.type === "text") { + if (block.type === 'text') { textContent1.push(block.text); - } else if (block.type === "tool_use") { + } else if (block.type === 'tool_use') { toolCalls1.push({ id: block.id, name: block.name, @@ -138,14 +148,14 @@ async function multiTurnMultimodalConversation() { } if (textContent1.length > 0) { - console.log("Text:", textContent1.join("\n")); + console.log('Text:', textContent1.join('\n')); } if (toolCalls1.length > 0) { - console.log("\nTool calls made:"); + console.log('\nTool calls made:'); for (const call of toolCalls1) { console.log(`- ${call.name} (${call.id})`); - console.log(` Arguments:`, JSON.stringify(call.input, null, 2)); + console.log(' Arguments:', JSON.stringify(call.input, null, 2)); } } @@ -153,65 +163,85 @@ async function multiTurnMultimodalConversation() { // Add assistant response to history (as Claude-style message) messages.push({ - role: "assistant", - content: claudeMessage1.content.map(block => { - if (block.type === "text") { - return { type: "text" as const, text: block.text }; - } else if (block.type === "tool_use") { + role: 'assistant', + content: claudeMessage1.content + .map((block) => { + if (block.type === 'text') { + return { + type: 'text' as const, + text: block.text, + }; + } + if (block.type === 'tool_use') { + return { + type: 'tool_use' as const, + id: block.id, + name: block.name, + input: block.input, + }; + } + // Handle other block types if needed return { - type: "tool_use" as const, - id: block.id, - name: block.name, - input: block.input, + type: 'text' as const, + text: '', }; - } - // Handle other block types if needed - return { type: "text" as const, text: "" }; - }).filter(block => block.type !== "text" || block.text !== ""), + }) + .filter((block) => block.type !== 'text' || block.text !== ''), }); // Turn 2: User provides tool results with an image result - console.log("=== Turn 2 ==="); - console.log("User provides tool results:"); + console.log('=== Turn 2 ==='); + console.log('User provides tool results:'); const toolResults: ClaudeMessageParam = { - role: "user", + role: 'user', content: toolCalls1.map((call, idx) => { - if (call.name === "analyze_image_details") { + if (call.name === 'analyze_image_details') { // Simulate a tool result with text console.log(`Tool result for ${call.id}:`); - console.log(" Analysis: The image shows warm orange and pink hues typical of sunset."); + console.log(' Analysis: The image shows warm orange and pink hues typical of sunset.'); return { - type: "tool_result" as const, + type: 'tool_result' as const, tool_use_id: call.id, content: JSON.stringify({ - colors: ["#FF6B35", "#F7931E", "#FDC830", "#F37335"], - dominant_objects: ["sky", "clouds", "mountains", "horizon"], - composition: "rule_of_thirds", - lighting: "golden_hour", + colors: [ + '#FF6B35', + '#F7931E', + '#FDC830', + '#F37335', + ], + dominant_objects: [ + 'sky', + 'clouds', + 'mountains', + 'horizon', + ], + composition: 'rule_of_thirds', + lighting: 'golden_hour', }), }; - } else if (call.name === "get_image_metadata") { + } + if (call.name === 'get_image_metadata') { console.log(`Tool result for ${call.id}:`); - console.log(" Metadata: 3840x2160, JPEG format"); + console.log(' Metadata: 3840x2160, JPEG format'); return { - type: "tool_result" as const, + type: 'tool_result' as const, tool_use_id: call.id, content: JSON.stringify({ width: 3840, height: 2160, - format: "JPEG", - created: "2023-06-15T18:45:00Z", - file_size: "2.4MB", + format: 'JPEG', + created: '2023-06-15T18:45:00Z', + file_size: '2.4MB', }), }; } return { - type: "tool_result" as const, + type: 'tool_result' as const, tool_use_id: call.id, - content: "Tool execution successful", + content: 'Tool execution successful', }; }), }; @@ -229,42 +259,43 @@ async function multiTurnMultimodalConversation() { const response2 = await result2.getResponse(); const claudeMessage2 = toClaudeMessage(response2); - console.log("Assistant response:"); + console.log('Assistant response:'); const textContent2: string[] = []; for (const block of claudeMessage2.content) { - if (block.type === "text") { + if (block.type === 'text') { textContent2.push(block.text); } } - console.log(textContent2.join("\n")); + console.log(textContent2.join('\n')); console.log(); // Add assistant response to history messages.push({ - role: "assistant", - content: textContent2.join("\n"), + role: 'assistant', + content: textContent2.join('\n'), }); // Turn 3: User asks a follow-up question with another image using base64 - console.log("=== Turn 3 ==="); + console.log('=== Turn 3 ==='); // Create a simple base64 encoded 1x1 pixel PNG (for demonstration) - const base64Image = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="; + const base64Image = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='; messages.push({ - role: "user", + role: 'user', content: [ { - type: "text", - text: "Great! Now I have another image here. How would you compare these two images in terms of color composition?", + type: 'text', + text: 'Great! Now I have another image here. How would you compare these two images in terms of color composition?', }, { - type: "image", + type: 'image', source: { - type: "base64", - media_type: "image/png", + type: 'base64', + media_type: 'image/png', data: base64Image, }, }, @@ -281,14 +312,18 @@ async function multiTurnMultimodalConversation() { const response3 = await result3.getResponse(); const claudeMessage3 = toClaudeMessage(response3); - console.log("Assistant response:"); + console.log('Assistant response:'); const textContent3: string[] = []; - const toolCalls3: Array<{ id: string; name: string; input: Record }> = []; + const toolCalls3: Array<{ + id: string; + name: string; + input: Record; + }> = []; for (const block of claudeMessage3.content) { - if (block.type === "text") { + if (block.type === 'text') { textContent3.push(block.text); - } else if (block.type === "tool_use") { + } else if (block.type === 'tool_use') { toolCalls3.push({ id: block.id, name: block.name, @@ -297,13 +332,13 @@ async function multiTurnMultimodalConversation() { } } - console.log(textContent3.join("\n")); + console.log(textContent3.join('\n')); if (toolCalls3.length > 0) { - console.log("\nTool calls made:"); + console.log('\nTool calls made:'); for (const call of toolCalls3) { console.log(`- ${call.name} (${call.id})`); - console.log(` Arguments:`, JSON.stringify(call.input, null, 2)); + console.log(' Arguments:', JSON.stringify(call.input, null, 2)); } } @@ -311,30 +346,39 @@ async function multiTurnMultimodalConversation() { // Add final assistant response to history messages.push({ - role: "assistant", - content: claudeMessage3.content.map(block => { - if (block.type === "text") { - return { type: "text" as const, text: block.text }; - } else if (block.type === "tool_use") { + role: 'assistant', + content: claudeMessage3.content + .map((block) => { + if (block.type === 'text') { + return { + type: 'text' as const, + text: block.text, + }; + } + if (block.type === 'tool_use') { + return { + type: 'tool_use' as const, + id: block.id, + name: block.name, + input: block.input, + }; + } return { - type: "tool_use" as const, - id: block.id, - name: block.name, - input: block.input, + type: 'text' as const, + text: '', }; - } - return { type: "text" as const, text: "" }; - }).filter(block => block.type !== "text" || block.text !== ""), + }) + .filter((block) => block.type !== 'text' || block.text !== ''), }); - console.log("=== Conversation Complete ==="); + console.log('=== Conversation Complete ==='); console.log(`Total messages in history: ${messages.length}`); // Show the final Claude message structure - console.log("\n=== Final Claude Message Structure ==="); - console.log("Stop reason:", claudeMessage3.stop_reason); - console.log("Model:", claudeMessage3.model); - console.log("Usage:", claudeMessage3.usage); + console.log('\n=== Final Claude Message Structure ==='); + console.log('Stop reason:', claudeMessage3.stop_reason); + console.log('Model:', claudeMessage3.model); + console.log('Usage:', claudeMessage3.usage); return messages; } @@ -343,7 +387,7 @@ async function main() { try { await multiTurnMultimodalConversation(); } catch (error) { - console.error("Error:", error); + console.error('Error:', error); } } diff --git a/examples/anthropic-reasoning.example.ts b/examples/anthropic-reasoning.example.ts index 00c133e2..9b61a2fd 100644 --- a/examples/anthropic-reasoning.example.ts +++ b/examples/anthropic-reasoning.example.ts @@ -2,7 +2,7 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import dotenv from "dotenv"; +import dotenv from 'dotenv'; dotenv.config(); @@ -19,34 +19,31 @@ dotenv.config(); * bun run anthropic-reasoning.example.ts */ -import type { ClaudeMessageParam } from "../src/models/claude-message.js"; -import { - OpenRouter, - fromClaudeMessages, - toClaudeMessage, -} from "../src/index.js"; +import type { ClaudeMessageParam } from '../src/models/claude-message.js'; -if (!process.env["OPENROUTER_API_KEY"]) { - throw new Error("Missing OPENROUTER_API_KEY environment variable"); +import { fromClaudeMessages, OpenRouter, toClaudeMessage } from '../src/index.js'; + +if (!process.env['OPENROUTER_API_KEY']) { + throw new Error('Missing OPENROUTER_API_KEY environment variable'); } const openRouter = new OpenRouter({ - apiKey: process.env["OPENROUTER_API_KEY"] ?? "", + apiKey: process.env['OPENROUTER_API_KEY'] ?? '', }); async function multiTurnClaudeConversation() { - const model = "anthropic/claude-sonnet-4"; + const model = 'anthropic/claude-sonnet-4'; // Initialize message history with Claude-style message format const messages: ClaudeMessageParam[] = [ { - role: "user", - content: "What are the key differences between functional and object-oriented programming?", + role: 'user', + content: 'What are the key differences between functional and object-oriented programming?', }, ]; - console.log("=== Turn 1 ==="); - console.log("User:", messages[0].content); + console.log('=== Turn 1 ==='); + console.log('User:', messages[0].content); console.log(); // First turn - convert Claude messages to OpenResponses format @@ -61,23 +58,24 @@ async function multiTurnClaudeConversation() { // Extract text content from Claude message const content1 = extractTextContent(claudeMessage1.content); - console.log("Assistant:", content1); + console.log('Assistant:', content1); console.log(); // Add assistant response to history (as Claude-style message) messages.push({ - role: "assistant", + role: 'assistant', content: content1, }); // Add next user message messages.push({ - role: "user", - content: "Can you show me an example of how the same problem would be solved differently in each paradigm?", + role: 'user', + content: + 'Can you show me an example of how the same problem would be solved differently in each paradigm?', }); - console.log("=== Turn 2 ==="); - console.log("User:", messages[messages.length - 1].content); + console.log('=== Turn 2 ==='); + console.log('User:', messages[messages.length - 1].content); console.log(); // Second turn @@ -89,22 +87,23 @@ async function multiTurnClaudeConversation() { const response2 = await result2.getResponse(); const claudeMessage2 = toClaudeMessage(response2); const content2 = extractTextContent(claudeMessage2.content); - console.log("Assistant:", content2); + console.log('Assistant:', content2); console.log(); // Add to history messages.push({ - role: "assistant", + role: 'assistant', content: content2, }); messages.push({ - role: "user", - content: "Which paradigm would you recommend for building a large-scale web application and why?", + role: 'user', + content: + 'Which paradigm would you recommend for building a large-scale web application and why?', }); - console.log("=== Turn 3 ==="); - console.log("User:", messages[messages.length - 1].content); + console.log('=== Turn 3 ==='); + console.log('User:', messages[messages.length - 1].content); console.log(); // Third turn @@ -116,42 +115,45 @@ async function multiTurnClaudeConversation() { const response3 = await result3.getResponse(); const claudeMessage3 = toClaudeMessage(response3); const content3 = extractTextContent(claudeMessage3.content); - console.log("Assistant:", content3); + console.log('Assistant:', content3); console.log(); // Final message history messages.push({ - role: "assistant", + role: 'assistant', content: content3, }); - console.log("=== Conversation Complete ==="); + console.log('=== Conversation Complete ==='); console.log(`Total messages in history: ${messages.length}`); // Show the final Claude message structure - console.log("\n=== Final Claude Message Structure ==="); - console.log("Stop reason:", claudeMessage3.stop_reason); - console.log("Model:", claudeMessage3.model); - console.log("Usage:", claudeMessage3.usage); + console.log('\n=== Final Claude Message Structure ==='); + console.log('Stop reason:', claudeMessage3.stop_reason); + console.log('Model:', claudeMessage3.model); + console.log('Usage:', claudeMessage3.usage); } /** * Helper to extract text content from Claude message content blocks */ function extractTextContent( - content: Array<{ type: string; text?: string }> + content: Array<{ + type: string; + text?: string; + }>, ): string { return content - .filter((block) => block.type === "text" && block.text) + .filter((block) => block.type === 'text' && block.text) .map((block) => block.text) - .join(""); + .join(''); } async function main() { try { await multiTurnClaudeConversation(); } catch (error) { - console.error("Error:", error); + console.error('Error:', error); } } diff --git a/examples/betaResponsesSend.example.ts b/examples/betaResponsesSend.example.ts index 0a738675..a5646342 100644 --- a/examples/betaResponsesSend.example.ts +++ b/examples/betaResponsesSend.example.ts @@ -3,8 +3,10 @@ * @generated-id: 66896eb477c6 */ -import dotenv from "dotenv"; +import dotenv from 'dotenv'; + dotenv.config(); + /** * Example usage of the @openrouter/sdk SDK * @@ -12,10 +14,10 @@ dotenv.config(); * npm run build && npx tsx betaResponsesSend.example.ts */ -import { OpenRouter } from "@openrouter/sdk"; +import { OpenRouter } from '@openrouter/sdk'; const openRouter = new OpenRouter({ - apiKey: process.env["OPENROUTER_API_KEY"] ?? "", + apiKey: process.env['OPENROUTER_API_KEY'] ?? '', }); async function main() { diff --git a/examples/callModel-typed-tool-calling.example.ts b/examples/callModel-typed-tool-calling.example.ts index 2f383ac2..ed472ab8 100644 --- a/examples/callModel-typed-tool-calling.example.ts +++ b/examples/callModel-typed-tool-calling.example.ts @@ -14,24 +14,25 @@ * npm run build && npx tsx callModel-typed-tool-calling.example.ts */ -import dotenv from "dotenv"; +import dotenv from 'dotenv'; + dotenv.config(); -import { OpenRouter, tool } from "../src/index.js"; -import z from "zod"; +import z from 'zod'; +import { OpenRouter, tool } from '../src/index.js'; const openRouter = new OpenRouter({ - apiKey: process.env["OPENROUTER_API_KEY"] ?? "", + apiKey: process.env['OPENROUTER_API_KEY'] ?? '', }); // Create a typed regular tool using tool() // The execute function params are automatically typed as z.infer // The return type is enforced based on outputSchema const weatherTool = tool({ - name: "get_weather", - description: "Get the current weather for a location", + name: 'get_weather', + description: 'Get the current weather for a location', inputSchema: z.object({ - location: z.string().describe("The city and country, e.g. San Francisco, CA"), + location: z.string().describe('The city and country, e.g. San Francisco, CA'), }), outputSchema: z.object({ temperature: z.number(), @@ -43,7 +44,7 @@ const weatherTool = tool({ // Return type is enforced as { temperature: number; description: string } return { temperature: 20, - description: "Sunny", + description: 'Sunny', }; }, }); @@ -51,10 +52,10 @@ const weatherTool = tool({ // Create a generator tool with typed progress events by providing eventSchema // The eventSchema triggers generator mode - execute becomes an async generator const searchTool = tool({ - name: "search_database", - description: "Search database with progress updates", + name: 'search_database', + description: 'Search database with progress updates', inputSchema: z.object({ - query: z.string().describe("The search query"), + query: z.string().describe('The search query'), }), eventSchema: z.object({ progress: z.number(), @@ -68,36 +69,52 @@ const searchTool = tool({ execute: async function* (params) { console.log(`Searching for: ${params.query}`); // Each yield is typed as { progress: number; message: string } - yield { progress: 25, message: "Searching..." }; - yield { progress: 50, message: "Processing results..." }; - yield { progress: 75, message: "Almost done..." }; + yield { + progress: 25, + message: 'Searching...', + }; + yield { + progress: 50, + message: 'Processing results...', + }; + yield { + progress: 75, + message: 'Almost done...', + }; // Final result is typed as { results: string[]; totalFound: number } - yield { progress: 100, message: "Complete!" }; + yield { + progress: 100, + message: 'Complete!', + }; }, }); async function main() { - console.log("=== Typed Tool Calling Example ===\n"); + console.log('=== Typed Tool Calling Example ===\n'); // Use 'as const' to enable full type inference for tool calls const result = openRouter.callModel({ - instructions: "You are a helpful assistant. Your name is Mark", - model: "openai/gpt-4o-mini", - input: "Hello! What is the weather in San Francisco?", - tools: [weatherTool] as const, + instructions: 'You are a helpful assistant. Your name is Mark', + model: 'openai/gpt-4o-mini', + input: 'Hello! What is the weather in San Francisco?', + tools: [ + weatherTool, + ] as const, }); // Get text response (tools are auto-executed) const text = await result.getText(); - console.log("Response:", text); + console.log('Response:', text); - console.log("\n=== Getting Tool Calls ===\n"); + console.log('\n=== Getting Tool Calls ===\n'); // Create a fresh request for demonstrating getToolCalls const result2 = openRouter.callModel({ - model: "openai/gpt-4o-mini", + model: 'openai/gpt-4o-mini', input: "What's the weather like in Paris?", - tools: [weatherTool] as const, + tools: [ + weatherTool, + ] as const, maxToolRounds: 0, // Don't auto-execute, just get the tool calls }); @@ -107,16 +124,18 @@ async function main() { for (const toolCall of toolCalls) { console.log(`Tool: ${toolCall.name}`); // toolCall.arguments is typed as { location: string } - console.log(`Arguments:`, toolCall.arguments); + console.log('Arguments:', toolCall.arguments); } - console.log("\n=== Streaming Tool Calls ===\n"); + console.log('\n=== Streaming Tool Calls ===\n'); // Create another request for demonstrating streaming const result3 = openRouter.callModel({ - model: "openai/gpt-4o-mini", + model: 'openai/gpt-4o-mini', input: "What's the weather in Tokyo?", - tools: [weatherTool] as const, + tools: [ + weatherTool, + ] as const, maxToolRounds: 0, }); @@ -124,44 +143,49 @@ async function main() { for await (const toolCall of result3.getToolCallsStream()) { console.log(`Streamed tool: ${toolCall.name}`); // toolCall.arguments is typed based on tool definitions - console.log(`Streamed arguments:`, toolCall.arguments); + console.log('Streamed arguments:', toolCall.arguments); } - console.log("\n=== Generator Tool with Typed Events ===\n"); + console.log('\n=== Generator Tool with Typed Events ===\n'); // Use generator tool with typed progress events const result4 = openRouter.callModel({ - model: "openai/gpt-4o-mini", - input: "Search for documents about TypeScript", - tools: [searchTool] as const, + model: 'openai/gpt-4o-mini', + input: 'Search for documents about TypeScript', + tools: [ + searchTool, + ] as const, }); // Stream events from getToolStream - events are fully typed! for await (const event of result4.getToolStream()) { - if (event.type === "preliminary_result") { + if (event.type === 'preliminary_result') { // event.result is typed as { progress: number; message: string } console.log(`Progress: ${event.result.progress}% - ${event.result.message}`); - } else if (event.type === "delta") { + } else if (event.type === 'delta') { // Tool argument deltas process.stdout.write(event.content); } } - console.log("\n=== Mixed Tools with Typed Events ===\n"); + console.log('\n=== Mixed Tools with Typed Events ===\n'); // Use both regular and generator tools together const result5 = openRouter.callModel({ - model: "openai/gpt-4o-mini", - input: "First search for weather data, then get the weather in Seattle", - tools: [weatherTool, searchTool] as const, + model: 'openai/gpt-4o-mini', + input: 'First search for weather data, then get the weather in Seattle', + tools: [ + weatherTool, + searchTool, + ] as const, }); // Events are a union of all generator tool event types for await (const event of result5.getToolStream()) { - if (event.type === "preliminary_result") { + if (event.type === 'preliminary_result') { // event.result is typed as { progress: number; message: string } // (only searchTool has eventSchema, so that's the event type) - console.log(`Event:`, event.result); + console.log('Event:', event.result); } } } diff --git a/examples/callModel.example.ts b/examples/callModel.example.ts index 77c1a4e6..9fa4248b 100644 --- a/examples/callModel.example.ts +++ b/examples/callModel.example.ts @@ -2,8 +2,10 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import dotenv from "dotenv"; +import dotenv from 'dotenv'; + dotenv.config(); + /** * Example usage of the @openrouter/sdk SDK * @@ -11,34 +13,37 @@ dotenv.config(); * npm run build && npx tsx betaResponsesSend.example.ts */ -import { OpenRouter } from "../src/index.js"; -import type { OpenResponsesEasyInputMessage } from "../src/models"; +import type { OpenResponsesEasyInputMessage } from '../src/models'; +import { OpenRouter } from '../src/index.js'; const openRouter = new OpenRouter({ - apiKey: process.env["OPENROUTER_API_KEY"] ?? "", + apiKey: process.env['OPENROUTER_API_KEY'] ?? '', }); -const text = "Hello! What is your name?"; +const text = 'Hello! What is your name?'; const responsesMessages: OpenResponsesEasyInputMessage[] = [ { - type: "message", - role: "user", + type: 'message', + role: 'user', content: [ { - type: "input_text", - text: "What is your name?", + type: 'input_text', + text: 'What is your name?', }, ], }, ]; -const supportedInputSchemas = [text, responsesMessages]; +const supportedInputSchemas = [ + text, + responsesMessages, +]; for (const input of supportedInputSchemas) { const result = await openRouter.callModel({ - instructions: "You are a helpful assistant. Your name is Mark", - model: "openai/gpt-4", + instructions: 'You are a helpful assistant. Your name is Mark', + model: 'openai/gpt-4', input: input, }); diff --git a/examples/chat-reasoning.example.ts b/examples/chat-reasoning.example.ts index 1b842d2f..73ea290b 100644 --- a/examples/chat-reasoning.example.ts +++ b/examples/chat-reasoning.example.ts @@ -2,7 +2,7 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import dotenv from "dotenv"; +import dotenv from 'dotenv'; dotenv.config(); @@ -16,30 +16,31 @@ dotenv.config(); * bun run chat-reasoning.example.ts */ -import type { Message } from "../src/models/index.js"; -import { OpenRouter } from "../src/index.js"; +import type { Message } from '../src/models/index.js'; -if (!process.env["OPENROUTER_API_KEY"]) { - throw new Error("Missing OPENROUTER_API_KEY environment variable"); +import { OpenRouter } from '../src/index.js'; + +if (!process.env['OPENROUTER_API_KEY']) { + throw new Error('Missing OPENROUTER_API_KEY environment variable'); } const openRouter = new OpenRouter({ - apiKey: process.env["OPENROUTER_API_KEY"] ?? "", + apiKey: process.env['OPENROUTER_API_KEY'] ?? '', }); async function multiTurnConversation() { - const model = "google/gemini-3-pro-preview"; + const model = 'google/gemini-3-pro-preview'; // Initialize message history with the first user message const messages: Message[] = [ { - role: "user", - content: "What are the three most important principles of good software architecture?", + role: 'user', + content: 'What are the three most important principles of good software architecture?', }, ]; - console.log("=== Turn 1 ==="); - console.log("User:", messages[0].content); + console.log('=== Turn 1 ==='); + console.log('User:', messages[0].content); console.log(); // First turn @@ -49,23 +50,23 @@ async function multiTurnConversation() { stream: false, }); - if (!("choices" in result1)) { - throw new Error("Unexpected response format"); + if (!('choices' in result1)) { + throw new Error('Unexpected response format'); } const assistant1 = result1.choices[0].message; - console.log("Assistant:", assistant1.content); + console.log('Assistant:', assistant1.content); console.log(); // Add assistant response and next user message to history messages.push(assistant1); messages.push({ - role: "user", - content: "Can you elaborate on the second principle? Give me a concrete example.", + role: 'user', + content: 'Can you elaborate on the second principle? Give me a concrete example.', }); - console.log("=== Turn 2 ==="); - console.log("User:", messages[messages.length - 1].content); + console.log('=== Turn 2 ==='); + console.log('User:', messages[messages.length - 1].content); console.log(); // Second turn @@ -75,23 +76,23 @@ async function multiTurnConversation() { stream: false, }); - if (!("choices" in result2)) { - throw new Error("Unexpected response format"); + if (!('choices' in result2)) { + throw new Error('Unexpected response format'); } const assistant2 = result2.choices[0].message; - console.log("Assistant:", assistant2.content); + console.log('Assistant:', assistant2.content); console.log(); // Add assistant response and next user message to history messages.push(assistant2); messages.push({ - role: "user", - content: "How would you apply this in a TypeScript project specifically?", + role: 'user', + content: 'How would you apply this in a TypeScript project specifically?', }); - console.log("=== Turn 3 ==="); - console.log("User:", messages[messages.length - 1].content); + console.log('=== Turn 3 ==='); + console.log('User:', messages[messages.length - 1].content); console.log(); // Third turn @@ -101,18 +102,18 @@ async function multiTurnConversation() { stream: false, }); - if (!("choices" in result3)) { - throw new Error("Unexpected response format"); + if (!('choices' in result3)) { + throw new Error('Unexpected response format'); } const assistant3 = result3.choices[0].message; - console.log("Assistant:", assistant3.content); + console.log('Assistant:', assistant3.content); console.log(); // Final message history messages.push(assistant3); - console.log("=== Conversation Complete ==="); + console.log('=== Conversation Complete ==='); console.log(`Total messages in history: ${messages.length}`); } @@ -120,7 +121,7 @@ async function main() { try { await multiTurnConversation(); } catch (error) { - console.error("Error:", error); + console.error('Error:', error); } } diff --git a/examples/chatCompletions.example.ts b/examples/chatCompletions.example.ts index 9529c6d7..9bde79fe 100644 --- a/examples/chatCompletions.example.ts +++ b/examples/chatCompletions.example.ts @@ -2,7 +2,7 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import dotenv from "dotenv"; +import dotenv from 'dotenv'; dotenv.config(); @@ -13,40 +13,40 @@ dotenv.config(); * bun run chatCompletions.example.ts */ -import { OpenRouter } from "../src/index.js"; +import { OpenRouter } from '../src/index.js'; -if (!process.env["OPENROUTER_API_KEY"]) { - throw new Error("Missing OPENROUTER_API_KEY environment variable"); +if (!process.env['OPENROUTER_API_KEY']) { + throw new Error('Missing OPENROUTER_API_KEY environment variable'); } const openRouter = new OpenRouter({ - apiKey: process.env["OPENROUTER_API_KEY"] ?? "", + apiKey: process.env['OPENROUTER_API_KEY'] ?? '', debugLogger: console, }); async function nonStreamingExample() { const result = await openRouter.chat.send({ - model: "qwen/qwen3-max", + model: 'qwen/qwen3-max', messages: [ { - role: "user", - content: "Tell me a short joke about programming", + role: 'user', + content: 'Tell me a short joke about programming', }, ], stream: false, }); - if ("choices" in result) { + if ('choices' in result) { console.log(result.choices[0].message.content); } } async function streamingExample() { const result = await openRouter.chat.send({ - model: "qwen/qwen3-max", + model: 'qwen/qwen3-max', messages: [ { - role: "user", - content: "Write a haiku about TypeScript", + role: 'user', + content: 'Write a haiku about TypeScript', }, ], stream: true, @@ -55,9 +55,9 @@ async function streamingExample() { }, }); - if (result && typeof result === "object" && Symbol.asyncIterator in result) { + if (result && typeof result === 'object' && Symbol.asyncIterator in result) { const stream = result; - let _fullContent = ""; + let _fullContent = ''; for await (const chunk of stream) { if (chunk.choices?.[0]?.delta?.content) { diff --git a/examples/embeddings.example.ts b/examples/embeddings.example.ts index 5523e509..f55a2908 100644 --- a/examples/embeddings.example.ts +++ b/examples/embeddings.example.ts @@ -1,4 +1,4 @@ -import dotenv from "dotenv"; +import dotenv from 'dotenv'; dotenv.config(); @@ -9,37 +9,35 @@ dotenv.config(); * bun run embeddings.example.ts */ -import { OpenRouter } from "../src/index.js"; +import { OpenRouter } from '../src/index.js'; -if (!process.env["OPENROUTER_API_KEY"]) { - throw new Error("Missing OPENROUTER_API_KEY environment variable"); +if (!process.env['OPENROUTER_API_KEY']) { + throw new Error('Missing OPENROUTER_API_KEY environment variable'); } const openRouter = new OpenRouter({ - apiKey: process.env["OPENROUTER_API_KEY"] ?? "", + apiKey: process.env['OPENROUTER_API_KEY'] ?? '', }); /** * Basic embedding generation with a single text input */ async function singleTextEmbedding() { - console.log("=== Single Text Embedding ===\n"); + console.log('=== Single Text Embedding ===\n'); const response = await openRouter.embeddings.generate({ - input: "The quick brown fox jumps over the lazy dog", - model: "openai/text-embedding-3-small", + input: 'The quick brown fox jumps over the lazy dog', + model: 'openai/text-embedding-3-small', }); - if (typeof response === "object" && "data" in response) { + if (typeof response === 'object' && 'data' in response) { console.log(`Model: ${response.model}`); console.log(`Number of embeddings: ${response.data.length}`); const embedding = response.data[0]; if (embedding && Array.isArray(embedding.embedding)) { console.log(`Embedding dimensions: ${embedding.embedding.length}`); - console.log( - `First 5 values: [${embedding.embedding.slice(0, 5).join(", ")}...]` - ); + console.log(`First 5 values: [${embedding.embedding.slice(0, 5).join(', ')}...]`); } if (response.usage) { @@ -47,30 +45,28 @@ async function singleTextEmbedding() { } } - console.log(""); + console.log(''); } /** * Batch embedding generation with multiple text inputs */ async function batchEmbeddings() { - console.log("=== Batch Embeddings ===\n"); + console.log('=== Batch Embeddings ===\n'); const texts = [ - "Machine learning is a subset of artificial intelligence.", - "Natural language processing helps computers understand text.", - "Embeddings represent text as numerical vectors.", + 'Machine learning is a subset of artificial intelligence.', + 'Natural language processing helps computers understand text.', + 'Embeddings represent text as numerical vectors.', ]; const response = await openRouter.embeddings.generate({ input: texts, - model: "openai/text-embedding-3-small", + model: 'openai/text-embedding-3-small', }); - if (typeof response === "object" && "data" in response) { - console.log( - `Generated ${response.data.length} embeddings for ${texts.length} texts` - ); + if (typeof response === 'object' && 'data' in response) { + console.log(`Generated ${response.data.length} embeddings for ${texts.length} texts`); response.data.forEach((item, index) => { if (item && Array.isArray(item.embedding)) { @@ -83,37 +79,37 @@ async function batchEmbeddings() { } } - console.log(""); + console.log(''); } /** * Generate embeddings with custom dimensions (if supported by the model) */ async function customDimensionsEmbedding() { - console.log("=== Custom Dimensions Embedding ===\n"); + console.log('=== Custom Dimensions Embedding ===\n'); const response = await openRouter.embeddings.generate({ - input: "This text will be embedded with reduced dimensions.", - model: "openai/text-embedding-3-small", + input: 'This text will be embedded with reduced dimensions.', + model: 'openai/text-embedding-3-small', dimensions: 256, // Request smaller embedding size }); - if (typeof response === "object" && "data" in response) { + if (typeof response === 'object' && 'data' in response) { const embedding = response.data[0]; if (embedding && Array.isArray(embedding.embedding)) { - console.log(`Requested dimensions: 256`); + console.log('Requested dimensions: 256'); console.log(`Actual dimensions: ${embedding.embedding.length}`); } } - console.log(""); + console.log(''); } /** * List available embedding models */ async function listEmbeddingModels() { - console.log("=== Available Embedding Models ===\n"); + console.log('=== Available Embedding Models ===\n'); const response = await openRouter.embeddings.listModels(); @@ -133,14 +129,14 @@ async function listEmbeddingModels() { } } - console.log(""); + console.log(''); } /** * Calculate cosine similarity between two embeddings */ function cosineSimilarity(a: number[], b: number[]): number { - if (a.length !== b.length) throw new Error("Vectors must have same length"); + if (a.length !== b.length) throw new Error('Vectors must have same length'); let dotProduct = 0; let normA = 0; @@ -159,20 +155,20 @@ function cosineSimilarity(a: number[], b: number[]): number { * Demonstrate semantic similarity using embeddings */ async function semanticSimilarity() { - console.log("=== Semantic Similarity ===\n"); + console.log('=== Semantic Similarity ===\n'); const texts = [ - "The cat sat on the mat.", - "A feline rested on the rug.", - "The stock market crashed today.", + 'The cat sat on the mat.', + 'A feline rested on the rug.', + 'The stock market crashed today.', ]; const response = await openRouter.embeddings.generate({ input: texts, - model: "openai/text-embedding-3-small", + model: 'openai/text-embedding-3-small', }); - if (typeof response === "object" && "data" in response) { + if (typeof response === 'object' && 'data' in response) { const embeddings = response.data .map((item) => (Array.isArray(item?.embedding) ? item.embedding : null)) .filter((e): e is number[] => e !== null); @@ -182,7 +178,7 @@ async function semanticSimilarity() { const sim02 = cosineSimilarity(embeddings[0], embeddings[2]); const sim12 = cosineSimilarity(embeddings[1], embeddings[2]); - console.log("Comparing semantic similarity:\n"); + console.log('Comparing semantic similarity:\n'); console.log(` "${texts[0]}"`); console.log(` "${texts[1]}"`); console.log(` Similarity: ${(sim01 * 100).toFixed(2)}%\n`); @@ -195,11 +191,11 @@ async function semanticSimilarity() { console.log(` "${texts[2]}"`); console.log(` Similarity: ${(sim12 * 100).toFixed(2)}%\n`); - console.log("Note: Higher similarity = more semantically related"); + console.log('Note: Higher similarity = more semantically related'); } } - console.log(""); + console.log(''); } async function main() { @@ -210,9 +206,9 @@ async function main() { await listEmbeddingModels(); await semanticSimilarity(); - console.log("All examples completed successfully!"); + console.log('All examples completed successfully!'); } catch (error) { - console.error("Error running examples:", error); + console.error('Error running examples:', error); process.exit(1); } } diff --git a/src/core.ts b/src/core.ts index 87473453..92f996cc 100644 --- a/src/core.ts +++ b/src/core.ts @@ -3,7 +3,7 @@ * @generated-id: f431fdbcd144 */ -import { ClientSDK } from "./lib/sdks.js"; +import { ClientSDK } from './lib/sdks.js'; /** * A minimal client to use when calling standalone SDK functions. Typically, an diff --git a/src/funcs/analyticsGetUserActivity.ts b/src/funcs/analyticsGetUserActivity.ts index 4768169a..cb756403 100644 --- a/src/funcs/analyticsGetUserActivity.ts +++ b/src/funcs/analyticsGetUserActivity.ts @@ -3,28 +3,30 @@ * @generated-id: 6525bcc66ab5 */ -import { OpenRouterCore } from "../core.js"; -import { encodeFormQuery } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeFormQuery } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Get user activity grouped by endpoint @@ -53,11 +55,7 @@ export function analyticsGetUserActivity( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -86,74 +84,117 @@ async function $do( > { const parsed = safeParse( request, - (value) => - operations.GetUserActivityRequest$outboundSchema.optional().parse(value), - "Input validation failed", + (value) => operations.GetUserActivityRequest$outboundSchema.optional().parse(value), + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; const body = null; - const path = pathToFunc("/activity")(); + const path = pathToFunc('/activity')(); const query = encodeFormQuery({ - "date": payload?.date, + date: payload?.date, }); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "getUserActivity", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'getUserActivity', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - query: query, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["400", "401", "403", "4XX", "500", "5XX"], + errorCodes: [ + '400', + '401', + '403', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -176,12 +217,28 @@ async function $do( M.jsonErr(401, errors.UnauthorizedResponseError$inboundSchema), M.jsonErr(403, errors.ForbiddenResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/apiKeysCreate.ts b/src/funcs/apiKeysCreate.ts index 2f05162d..fc50b38c 100644 --- a/src/funcs/apiKeysCreate.ts +++ b/src/funcs/apiKeysCreate.ts @@ -3,28 +3,30 @@ * @generated-id: 133e2c5f487c */ -import { OpenRouterCore } from "../core.js"; -import { encodeJSON } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeJSON } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Create a new API key @@ -50,11 +52,7 @@ export function apiKeysCreate( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -84,68 +82,114 @@ async function $do( const parsed = safeParse( request, (value) => operations.CreateKeysRequest$outboundSchema.parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; - const body = encodeJSON("body", payload, { explode: true }); + const body = encodeJSON('body', payload, { + explode: true, + }); - const path = pathToFunc("/keys")(); + const path = pathToFunc('/keys')(); - const headers = new Headers(compactMap({ - "Content-Type": "application/json", - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + 'Content-Type': 'application/json', + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "createKeys", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'createKeys', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "POST", - baseURL: options?.serverURL, - path: path, - headers: headers, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'POST', + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["400", "401", "429", "4XX", "500", "5XX"], + errorCodes: [ + '400', + '401', + '429', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -168,12 +212,28 @@ async function $do( M.jsonErr(401, errors.UnauthorizedResponseError$inboundSchema), M.jsonErr(429, errors.TooManyRequestsResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/apiKeysDelete.ts b/src/funcs/apiKeysDelete.ts index b365c6d4..2391a95e 100644 --- a/src/funcs/apiKeysDelete.ts +++ b/src/funcs/apiKeysDelete.ts @@ -3,28 +3,30 @@ * @generated-id: c151c399f75f */ -import { OpenRouterCore } from "../core.js"; -import { encodeSimple } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeSimple } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Delete an API key @@ -50,11 +52,7 @@ export function apiKeysDelete( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -84,74 +82,118 @@ async function $do( const parsed = safeParse( request, (value) => operations.DeleteKeysRequest$outboundSchema.parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; const body = null; const pathParams = { - hash: encodeSimple("hash", payload.hash, { + hash: encodeSimple('hash', payload.hash, { explode: false, - charEncoding: "percent", + charEncoding: 'percent', }), }; - const path = pathToFunc("/keys/{hash}")(pathParams); + const path = pathToFunc('/keys/{hash}')(pathParams); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "deleteKeys", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'deleteKeys', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "DELETE", - baseURL: options?.serverURL, - path: path, - headers: headers, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'DELETE', + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["401", "404", "429", "4XX", "500", "5XX"], + errorCodes: [ + '401', + '404', + '429', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -174,12 +216,28 @@ async function $do( M.jsonErr(404, errors.NotFoundResponseError$inboundSchema), M.jsonErr(429, errors.TooManyRequestsResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/apiKeysGet.ts b/src/funcs/apiKeysGet.ts index f1799990..5d91411b 100644 --- a/src/funcs/apiKeysGet.ts +++ b/src/funcs/apiKeysGet.ts @@ -3,28 +3,30 @@ * @generated-id: 12a5c2abbddd */ -import { OpenRouterCore } from "../core.js"; -import { encodeSimple } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeSimple } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Get a single API key @@ -50,11 +52,7 @@ export function apiKeysGet( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -84,74 +82,118 @@ async function $do( const parsed = safeParse( request, (value) => operations.GetKeyRequest$outboundSchema.parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; const body = null; const pathParams = { - hash: encodeSimple("hash", payload.hash, { + hash: encodeSimple('hash', payload.hash, { explode: false, - charEncoding: "percent", + charEncoding: 'percent', }), }; - const path = pathToFunc("/keys/{hash}")(pathParams); + const path = pathToFunc('/keys/{hash}')(pathParams); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "getKey", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'getKey', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["401", "404", "429", "4XX", "500", "5XX"], + errorCodes: [ + '401', + '404', + '429', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -174,12 +216,28 @@ async function $do( M.jsonErr(404, errors.NotFoundResponseError$inboundSchema), M.jsonErr(429, errors.TooManyRequestsResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/apiKeysGetCurrentKeyMetadata.ts b/src/funcs/apiKeysGetCurrentKeyMetadata.ts index 1f0aab97..19df4ee7 100644 --- a/src/funcs/apiKeysGetCurrentKeyMetadata.ts +++ b/src/funcs/apiKeysGetCurrentKeyMetadata.ts @@ -3,26 +3,28 @@ * @generated-id: d9449cb31931 */ -import { OpenRouterCore } from "../core.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Get current API key @@ -48,10 +50,7 @@ export function apiKeysGetCurrentKeyMetadata( | SDKValidationError > > { - return new APIPromise($do( - client, - options, - )); + return new APIPromise($do(client, options)); } async function $do( @@ -75,58 +74,95 @@ async function $do( APICall, ] > { - const path = pathToFunc("/key")(); + const path = pathToFunc('/key')(); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "getCurrentKey", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'getCurrentKey', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["401", "4XX", "500", "5XX"], + errorCodes: [ + '401', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -145,12 +181,28 @@ async function $do( M.json(200, operations.GetCurrentKeyResponse$inboundSchema), M.jsonErr(401, errors.UnauthorizedResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/apiKeysList.ts b/src/funcs/apiKeysList.ts index cdce4460..cca0c0d2 100644 --- a/src/funcs/apiKeysList.ts +++ b/src/funcs/apiKeysList.ts @@ -3,28 +3,30 @@ * @generated-id: 2afc8d8f1ce0 */ -import { OpenRouterCore } from "../core.js"; -import { encodeFormQuery } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeFormQuery } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * List API keys @@ -49,11 +51,7 @@ export function apiKeysList( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -82,73 +80,116 @@ async function $do( const parsed = safeParse( request, (value) => operations.ListRequest$outboundSchema.optional().parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; const body = null; - const path = pathToFunc("/keys")(); + const path = pathToFunc('/keys')(); const query = encodeFormQuery({ - "include_disabled": payload?.include_disabled, - "offset": payload?.offset, + include_disabled: payload?.include_disabled, + offset: payload?.offset, }); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "list", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'list', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - query: query, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["401", "429", "4XX", "500", "5XX"], + errorCodes: [ + '401', + '429', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -169,12 +210,28 @@ async function $do( M.jsonErr(401, errors.UnauthorizedResponseError$inboundSchema), M.jsonErr(429, errors.TooManyRequestsResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/apiKeysUpdate.ts b/src/funcs/apiKeysUpdate.ts index b41d43b0..96abbe66 100644 --- a/src/funcs/apiKeysUpdate.ts +++ b/src/funcs/apiKeysUpdate.ts @@ -3,28 +3,30 @@ * @generated-id: 05700884934b */ -import { OpenRouterCore } from "../core.js"; -import { encodeJSON, encodeSimple } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeJSON, encodeSimple } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Update an API key @@ -51,11 +53,7 @@ export function apiKeysUpdate( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -86,75 +84,122 @@ async function $do( const parsed = safeParse( request, (value) => operations.UpdateKeysRequest$outboundSchema.parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; - const body = encodeJSON("body", payload.RequestBody, { explode: true }); + const body = encodeJSON('body', payload.RequestBody, { + explode: true, + }); const pathParams = { - hash: encodeSimple("hash", payload.hash, { + hash: encodeSimple('hash', payload.hash, { explode: false, - charEncoding: "percent", + charEncoding: 'percent', }), }; - const path = pathToFunc("/keys/{hash}")(pathParams); + const path = pathToFunc('/keys/{hash}')(pathParams); - const headers = new Headers(compactMap({ - "Content-Type": "application/json", - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + 'Content-Type': 'application/json', + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "updateKeys", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'updateKeys', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "PATCH", - baseURL: options?.serverURL, - path: path, - headers: headers, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'PATCH', + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["400", "401", "404", "429", "4XX", "500", "5XX"], + errorCodes: [ + '400', + '401', + '404', + '429', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -179,12 +224,28 @@ async function $do( M.jsonErr(404, errors.NotFoundResponseError$inboundSchema), M.jsonErr(429, errors.TooManyRequestsResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/betaResponsesSend.ts b/src/funcs/betaResponsesSend.ts index 3f63d38e..6795e140 100644 --- a/src/funcs/betaResponsesSend.ts +++ b/src/funcs/betaResponsesSend.ts @@ -3,30 +3,32 @@ * @generated-id: c5c4ab0c3f76 */ -import { OpenRouterCore } from "../core.js"; -import { encodeJSON } from "../lib/encodings.js"; -import { EventStream } from "../lib/event-streams.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { EventStream } from '../lib/event-streams.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as models from "../models/index.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeJSON } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as models from '../models/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Create a response @@ -36,7 +38,9 @@ import { Result } from "../types/fp.js"; */ export function betaResponsesSend( client: OpenRouterCore, - request: models.OpenResponsesRequest & { stream?: false }, + request: models.OpenResponsesRequest & { + stream?: false; + }, options?: RequestOptions, ): APIPromise< Result< @@ -66,7 +70,9 @@ export function betaResponsesSend( >; export function betaResponsesSend( client: OpenRouterCore, - request: models.OpenResponsesRequest & { stream: true }, + request: models.OpenResponsesRequest & { + stream: true; + }, options?: RequestOptions, ): APIPromise< Result< @@ -154,11 +160,7 @@ export function betaResponsesSend( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -197,84 +199,123 @@ async function $do( const parsed = safeParse( request, (value) => models.OpenResponsesRequest$outboundSchema.parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; - const body = encodeJSON("body", payload, { explode: true }); + const body = encodeJSON('body', payload, { + explode: true, + }); - const path = pathToFunc("/responses")(); + const path = pathToFunc('/responses')(); - const headers = new Headers(compactMap({ - "Content-Type": "application/json", - Accept: request?.stream ? "text/event-stream" : "application/json", - })); + const headers = new Headers( + compactMap({ + 'Content-Type': 'application/json', + Accept: request?.stream ? 'text/event-stream' : 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "createResponses", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'createResponses', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "POST", - baseURL: options?.serverURL, - path: path, - headers: headers, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'POST', + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, errorCodes: [ - "400", - "401", - "402", - "404", - "408", - "413", - "422", - "429", - "4XX", - "500", - "502", - "503", - "524", - "529", - "5XX", + '400', + '401', + '402', + '404', + '408', + '413', + '422', + '429', + '4XX', + '500', + '502', + '503', + '524', + '529', + '5XX', ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -316,12 +357,28 @@ async function $do( M.jsonErr(503, errors.ServiceUnavailableResponseError$inboundSchema), M.jsonErr(524, errors.EdgeNetworkTimeoutResponseError$inboundSchema), M.jsonErr(529, errors.ProviderOverloadedResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/chatSend.ts b/src/funcs/chatSend.ts index 3054ce2a..cdf129c2 100644 --- a/src/funcs/chatSend.ts +++ b/src/funcs/chatSend.ts @@ -3,30 +3,32 @@ * @generated-id: 8c3aa3c963bf */ -import { OpenRouterCore } from "../core.js"; -import { encodeJSON } from "../lib/encodings.js"; -import { EventStream } from "../lib/event-streams.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { EventStream } from '../lib/event-streams.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as models from "../models/index.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeJSON } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as models from '../models/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Create a chat completion @@ -36,7 +38,9 @@ import { Result } from "../types/fp.js"; */ export function chatSend( client: OpenRouterCore, - request: models.ChatGenerationParams & { stream?: false }, + request: models.ChatGenerationParams & { + stream?: false; + }, options?: RequestOptions, ): APIPromise< Result< @@ -54,7 +58,9 @@ export function chatSend( >; export function chatSend( client: OpenRouterCore, - request: models.ChatGenerationParams & { stream: true }, + request: models.ChatGenerationParams & { + stream: true; + }, options?: RequestOptions, ): APIPromise< Result< @@ -106,11 +112,7 @@ export function chatSend( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -137,68 +139,114 @@ async function $do( const parsed = safeParse( request, (value) => models.ChatGenerationParams$outboundSchema.parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; - const body = encodeJSON("body", payload, { explode: true }); + const body = encodeJSON('body', payload, { + explode: true, + }); - const path = pathToFunc("/chat/completions")(); + const path = pathToFunc('/chat/completions')(); - const headers = new Headers(compactMap({ - "Content-Type": "application/json", - Accept: request?.stream ? "text/event-stream" : "application/json", - })); + const headers = new Headers( + compactMap({ + 'Content-Type': 'application/json', + Accept: request?.stream ? 'text/event-stream' : 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "sendChatCompletionRequest", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'sendChatCompletionRequest', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "POST", - baseURL: options?.serverURL, - path: path, - headers: headers, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'POST', + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["400", "401", "429", "4XX", "500", "5XX"], + errorCodes: [ + '400', + '401', + '429', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -215,14 +263,37 @@ async function $do( >( M.json(200, operations.SendChatCompletionRequestResponse$inboundSchema), M.sse(200, operations.SendChatCompletionRequestResponse$inboundSchema), - M.jsonErr([400, 401, 429], errors.ChatError$inboundSchema), + M.jsonErr( + [ + 400, + 401, + 429, + ], + errors.ChatError$inboundSchema, + ), M.jsonErr(500, errors.ChatError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/completionsGenerate.ts b/src/funcs/completionsGenerate.ts index 90f94a93..f34cbb46 100644 --- a/src/funcs/completionsGenerate.ts +++ b/src/funcs/completionsGenerate.ts @@ -3,28 +3,30 @@ * @generated-id: 54a6e7c9b712 */ -import { OpenRouterCore } from "../core.js"; -import { encodeJSON } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as models from "../models/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeJSON } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as models from '../models/index.js'; +import { APIPromise } from '../types/async.js'; /** * Create a completion @@ -50,11 +52,7 @@ export function completionsGenerate( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -81,68 +79,114 @@ async function $do( const parsed = safeParse( request, (value) => models.CompletionCreateParams$outboundSchema.parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; - const body = encodeJSON("body", payload, { explode: true }); + const body = encodeJSON('body', payload, { + explode: true, + }); - const path = pathToFunc("/completions")(); + const path = pathToFunc('/completions')(); - const headers = new Headers(compactMap({ - "Content-Type": "application/json", - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + 'Content-Type': 'application/json', + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "createCompletions", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'createCompletions', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "POST", - baseURL: options?.serverURL, - path: path, - headers: headers, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'POST', + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["400", "401", "429", "4XX", "500", "5XX"], + errorCodes: [ + '400', + '401', + '429', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -158,14 +202,37 @@ async function $do( | SDKValidationError >( M.json(200, models.CompletionResponse$inboundSchema), - M.jsonErr([400, 401, 429], errors.ChatError$inboundSchema), + M.jsonErr( + [ + 400, + 401, + 429, + ], + errors.ChatError$inboundSchema, + ), M.jsonErr(500, errors.ChatError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/creditsCreateCoinbaseCharge.ts b/src/funcs/creditsCreateCoinbaseCharge.ts index 0acd1929..2de8fa78 100644 --- a/src/funcs/creditsCreateCoinbaseCharge.ts +++ b/src/funcs/creditsCreateCoinbaseCharge.ts @@ -3,29 +3,31 @@ * @generated-id: e07ee6831da3 */ -import { OpenRouterCore } from "../core.js"; -import { encodeJSON } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { resolveSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as models from "../models/index.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeJSON } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { resolveSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as models from '../models/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Create a Coinbase charge for crypto payment @@ -55,12 +57,7 @@ export function creditsCreateCoinbaseCharge( | SDKValidationError > > { - return new APIPromise($do( - client, - security, - request, - options, - )); + return new APIPromise($do(client, security, request, options)); } async function $do( @@ -91,74 +88,113 @@ async function $do( const parsed = safeParse( request, (value) => models.CreateChargeRequest$outboundSchema.parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; - const body = encodeJSON("body", payload, { explode: true }); - - const path = pathToFunc("/credits/coinbase")(); + const body = encodeJSON('body', payload, { + explode: true, + }); - const headers = new Headers(compactMap({ - "Content-Type": "application/json", - Accept: "application/json", - })); + const path = pathToFunc('/credits/coinbase')(); - const requestSecurity = resolveSecurity( - [ - { - fieldName: "Authorization", - type: "http:bearer", - value: security?.bearer, - }, - ], + const headers = new Headers( + compactMap({ + 'Content-Type': 'application/json', + Accept: 'application/json', + }), ); + const requestSecurity = resolveSecurity([ + { + fieldName: 'Authorization', + type: 'http:bearer', + value: security?.bearer, + }, + ]); + const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "createCoinbaseCharge", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'createCoinbaseCharge', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: security, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "POST", - baseURL: options?.serverURL, - path: path, - headers: headers, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'POST', + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["400", "401", "429", "4XX", "500", "5XX"], + errorCodes: [ + '400', + '401', + '429', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -181,12 +217,28 @@ async function $do( M.jsonErr(401, errors.UnauthorizedResponseError$inboundSchema), M.jsonErr(429, errors.TooManyRequestsResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/creditsGetCredits.ts b/src/funcs/creditsGetCredits.ts index 63149dce..b7cb4f2f 100644 --- a/src/funcs/creditsGetCredits.ts +++ b/src/funcs/creditsGetCredits.ts @@ -3,26 +3,28 @@ * @generated-id: 88fdc1315137 */ -import { OpenRouterCore } from "../core.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Get remaining credits @@ -49,10 +51,7 @@ export function creditsGetCredits( | SDKValidationError > > { - return new APIPromise($do( - client, - options, - )); + return new APIPromise($do(client, options)); } async function $do( @@ -77,58 +76,96 @@ async function $do( APICall, ] > { - const path = pathToFunc("/credits")(); + const path = pathToFunc('/credits')(); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "getCredits", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'getCredits', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["401", "403", "4XX", "500", "5XX"], + errorCodes: [ + '401', + '403', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -149,12 +186,28 @@ async function $do( M.jsonErr(401, errors.UnauthorizedResponseError$inboundSchema), M.jsonErr(403, errors.ForbiddenResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/embeddingsGenerate.ts b/src/funcs/embeddingsGenerate.ts index 80464839..f1588c61 100644 --- a/src/funcs/embeddingsGenerate.ts +++ b/src/funcs/embeddingsGenerate.ts @@ -3,28 +3,30 @@ * @generated-id: f6455fcfe2c8 */ -import { OpenRouterCore } from "../core.js"; -import { encodeJSON } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeJSON } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Submit an embedding request @@ -59,11 +61,7 @@ export function embeddingsGenerate( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -99,81 +97,120 @@ async function $do( const parsed = safeParse( request, (value) => operations.CreateEmbeddingsRequest$outboundSchema.parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; - const body = encodeJSON("body", payload, { explode: true }); + const body = encodeJSON('body', payload, { + explode: true, + }); - const path = pathToFunc("/embeddings")(); + const path = pathToFunc('/embeddings')(); - const headers = new Headers(compactMap({ - "Content-Type": "application/json", - Accept: "application/json;q=1, text/event-stream;q=0", - })); + const headers = new Headers( + compactMap({ + 'Content-Type': 'application/json', + Accept: 'application/json;q=1, text/event-stream;q=0', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "createEmbeddings", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'createEmbeddings', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "POST", - baseURL: options?.serverURL, - path: path, - headers: headers, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'POST', + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, errorCodes: [ - "400", - "401", - "402", - "404", - "429", - "4XX", - "500", - "502", - "503", - "524", - "529", - "5XX", + '400', + '401', + '402', + '404', + '429', + '4XX', + '500', + '502', + '503', + '524', + '529', + '5XX', ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -199,7 +236,7 @@ async function $do( >( M.json(200, operations.CreateEmbeddingsResponse$inboundSchema), M.text(200, operations.CreateEmbeddingsResponse$inboundSchema, { - ctype: "text/event-stream", + ctype: 'text/event-stream', }), M.jsonErr(400, errors.BadRequestResponseError$inboundSchema), M.jsonErr(401, errors.UnauthorizedResponseError$inboundSchema), @@ -211,12 +248,28 @@ async function $do( M.jsonErr(503, errors.ServiceUnavailableResponseError$inboundSchema), M.jsonErr(524, errors.EdgeNetworkTimeoutResponseError$inboundSchema), M.jsonErr(529, errors.ProviderOverloadedResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/embeddingsListModels.ts b/src/funcs/embeddingsListModels.ts index 95d734bb..eced520f 100644 --- a/src/funcs/embeddingsListModels.ts +++ b/src/funcs/embeddingsListModels.ts @@ -3,26 +3,28 @@ * @generated-id: dbe9751f8369 */ -import { OpenRouterCore } from "../core.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as models from "../models/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as models from '../models/index.js'; +import { APIPromise } from '../types/async.js'; /** * List all embeddings models @@ -48,10 +50,7 @@ export function embeddingsListModels( | SDKValidationError > > { - return new APIPromise($do( - client, - options, - )); + return new APIPromise($do(client, options)); } async function $do( @@ -75,58 +74,95 @@ async function $do( APICall, ] > { - const path = pathToFunc("/embeddings/models")(); + const path = pathToFunc('/embeddings/models')(); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "listEmbeddingsModels", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'listEmbeddingsModels', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["400", "4XX", "500", "5XX"], + errorCodes: [ + '400', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -145,12 +181,28 @@ async function $do( M.json(200, models.ModelsListResponse$inboundSchema), M.jsonErr(400, errors.BadRequestResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/endpointsList.ts b/src/funcs/endpointsList.ts index 031c9fe2..64462faa 100644 --- a/src/funcs/endpointsList.ts +++ b/src/funcs/endpointsList.ts @@ -3,28 +3,30 @@ * @generated-id: ea932ec09987 */ -import { OpenRouterCore } from "../core.js"; -import { encodeSimple } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeSimple } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * List all endpoints for a model @@ -48,11 +50,7 @@ export function endpointsList( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -80,78 +78,120 @@ async function $do( const parsed = safeParse( request, (value) => operations.ListEndpointsRequest$outboundSchema.parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; const body = null; const pathParams = { - author: encodeSimple("author", payload.author, { + author: encodeSimple('author', payload.author, { explode: false, - charEncoding: "percent", + charEncoding: 'percent', }), - slug: encodeSimple("slug", payload.slug, { + slug: encodeSimple('slug', payload.slug, { explode: false, - charEncoding: "percent", + charEncoding: 'percent', }), }; - const path = pathToFunc("/models/{author}/{slug}/endpoints")(pathParams); + const path = pathToFunc('/models/{author}/{slug}/endpoints')(pathParams); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "listEndpoints", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'listEndpoints', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["404", "4XX", "500", "5XX"], + errorCodes: [ + '404', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -170,12 +210,28 @@ async function $do( M.json(200, operations.ListEndpointsResponse$inboundSchema), M.jsonErr(404, errors.NotFoundResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/endpointsListZdrEndpoints.ts b/src/funcs/endpointsListZdrEndpoints.ts index 5aaad366..66ff2027 100644 --- a/src/funcs/endpointsListZdrEndpoints.ts +++ b/src/funcs/endpointsListZdrEndpoints.ts @@ -3,26 +3,28 @@ * @generated-id: 4efb7ea3e48f */ -import { OpenRouterCore } from "../core.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Preview the impact of ZDR on the available endpoints @@ -44,10 +46,7 @@ export function endpointsListZdrEndpoints( | SDKValidationError > > { - return new APIPromise($do( - client, - options, - )); + return new APIPromise($do(client, options)); } async function $do( @@ -70,58 +69,94 @@ async function $do( APICall, ] > { - const path = pathToFunc("/endpoints/zdr")(); + const path = pathToFunc('/endpoints/zdr')(); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "listEndpointsZdr", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'listEndpointsZdr', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["4XX", "500", "5XX"], + errorCodes: [ + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -138,12 +173,28 @@ async function $do( >( M.json(200, operations.ListEndpointsZdrResponse$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/generationsGetGeneration.ts b/src/funcs/generationsGetGeneration.ts index b8418b55..c816f62f 100644 --- a/src/funcs/generationsGetGeneration.ts +++ b/src/funcs/generationsGetGeneration.ts @@ -3,28 +3,30 @@ * @generated-id: dac2d205a08d */ -import { OpenRouterCore } from "../core.js"; -import { encodeFormQuery } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeFormQuery } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Get request & usage metadata for a generation @@ -54,11 +56,7 @@ export function generationsGetGeneration( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -92,83 +90,120 @@ async function $do( const parsed = safeParse( request, (value) => operations.GetGenerationRequest$outboundSchema.parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; const body = null; - const path = pathToFunc("/generation")(); + const path = pathToFunc('/generation')(); const query = encodeFormQuery({ - "id": payload.id, + id: payload.id, }); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "getGeneration", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'getGeneration', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - query: query, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, errorCodes: [ - "401", - "402", - "404", - "429", - "4XX", - "500", - "502", - "524", - "529", - "5XX", + '401', + '402', + '404', + '429', + '4XX', + '500', + '502', + '524', + '529', + '5XX', ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -199,12 +234,28 @@ async function $do( M.jsonErr(502, errors.BadGatewayResponseError$inboundSchema), M.jsonErr(524, errors.EdgeNetworkTimeoutResponseError$inboundSchema), M.jsonErr(529, errors.ProviderOverloadedResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/modelsCount.ts b/src/funcs/modelsCount.ts index 1425d911..fc700431 100644 --- a/src/funcs/modelsCount.ts +++ b/src/funcs/modelsCount.ts @@ -3,26 +3,28 @@ * @generated-id: 371adfc67b48 */ -import { OpenRouterCore } from "../core.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as models from "../models/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as models from '../models/index.js'; +import { APIPromise } from '../types/async.js'; /** * Get total count of available models @@ -44,10 +46,7 @@ export function modelsCount( | SDKValidationError > > { - return new APIPromise($do( - client, - options, - )); + return new APIPromise($do(client, options)); } async function $do( @@ -70,58 +69,94 @@ async function $do( APICall, ] > { - const path = pathToFunc("/models/count")(); + const path = pathToFunc('/models/count')(); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "listModelsCount", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'listModelsCount', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["4XX", "500", "5XX"], + errorCodes: [ + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -138,12 +173,28 @@ async function $do( >( M.json(200, models.ModelsCountResponse$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/modelsList.ts b/src/funcs/modelsList.ts index 18f86201..94ea9705 100644 --- a/src/funcs/modelsList.ts +++ b/src/funcs/modelsList.ts @@ -3,29 +3,31 @@ * @generated-id: deff050b46c5 */ -import { OpenRouterCore } from "../core.js"; -import { encodeFormQuery } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as models from "../models/index.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeFormQuery } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as models from '../models/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * List all models and their properties @@ -49,11 +51,7 @@ export function modelsList( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -80,75 +78,116 @@ async function $do( > { const parsed = safeParse( request, - (value) => - operations.GetModelsRequest$outboundSchema.optional().parse(value), - "Input validation failed", + (value) => operations.GetModelsRequest$outboundSchema.optional().parse(value), + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; const body = null; - const path = pathToFunc("/models")(); + const path = pathToFunc('/models')(); const query = encodeFormQuery({ - "category": payload?.category, - "supported_parameters": payload?.supported_parameters, + category: payload?.category, + supported_parameters: payload?.supported_parameters, }); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "getModels", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'getModels', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - query: query, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["400", "4XX", "500", "5XX"], + errorCodes: [ + '400', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -167,12 +206,28 @@ async function $do( M.json(200, models.ModelsListResponse$inboundSchema), M.jsonErr(400, errors.BadRequestResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/modelsListForUser.ts b/src/funcs/modelsListForUser.ts index e0877a54..bc74f936 100644 --- a/src/funcs/modelsListForUser.ts +++ b/src/funcs/modelsListForUser.ts @@ -3,27 +3,29 @@ * @generated-id: db628dd3c179 */ -import { OpenRouterCore } from "../core.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { resolveSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as models from "../models/index.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type * as operations from '../models/operations/index.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { resolveSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as models from '../models/index.js'; +import { APIPromise } from '../types/async.js'; /** * List models filtered by user provider preferences @@ -47,11 +49,7 @@ export function modelsListForUser( | SDKValidationError > > { - return new APIPromise($do( - client, - security, - options, - )); + return new APIPromise($do(client, security, options)); } async function $do( @@ -76,64 +74,94 @@ async function $do( APICall, ] > { - const path = pathToFunc("/models/user")(); - - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const path = pathToFunc('/models/user')(); - const requestSecurity = resolveSecurity( - [ - { - fieldName: "Authorization", - type: "http:bearer", - value: security?.bearer, - }, - ], + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), ); + const requestSecurity = resolveSecurity([ + { + fieldName: 'Authorization', + type: 'http:bearer', + value: security?.bearer, + }, + ]); + const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "listModelsUser", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'listModelsUser', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: security, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["401", "4XX", "500", "5XX"], + errorCodes: [ + '401', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -152,12 +180,28 @@ async function $do( M.json(200, models.ModelsListResponse$inboundSchema), M.jsonErr(401, errors.UnauthorizedResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/oAuthCreateAuthCode.ts b/src/funcs/oAuthCreateAuthCode.ts index 227561e9..933c38ac 100644 --- a/src/funcs/oAuthCreateAuthCode.ts +++ b/src/funcs/oAuthCreateAuthCode.ts @@ -3,28 +3,30 @@ * @generated-id: 8a79f27722c0 */ -import { OpenRouterCore } from "../core.js"; -import { encodeJSON } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeJSON } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Create authorization code @@ -52,11 +54,7 @@ export function oAuthCreateAuthCode( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -85,68 +83,113 @@ async function $do( const parsed = safeParse( request, (value) => operations.CreateAuthKeysCodeRequest$outboundSchema.parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; - const body = encodeJSON("body", payload, { explode: true }); + const body = encodeJSON('body', payload, { + explode: true, + }); - const path = pathToFunc("/auth/keys/code")(); + const path = pathToFunc('/auth/keys/code')(); - const headers = new Headers(compactMap({ - "Content-Type": "application/json", - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + 'Content-Type': 'application/json', + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "createAuthKeysCode", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'createAuthKeysCode', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "POST", - baseURL: options?.serverURL, - path: path, - headers: headers, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'POST', + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["400", "401", "4XX", "500", "5XX"], + errorCodes: [ + '400', + '401', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -167,12 +210,28 @@ async function $do( M.jsonErr(400, errors.BadRequestResponseError$inboundSchema), M.jsonErr(401, errors.UnauthorizedResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/oAuthExchangeAuthCodeForAPIKey.ts b/src/funcs/oAuthExchangeAuthCodeForAPIKey.ts index 22eb8cd4..fa19bde5 100644 --- a/src/funcs/oAuthExchangeAuthCodeForAPIKey.ts +++ b/src/funcs/oAuthExchangeAuthCodeForAPIKey.ts @@ -3,28 +3,30 @@ * @generated-id: 3386ec12d934 */ -import { OpenRouterCore } from "../core.js"; -import { encodeJSON } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeJSON } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Exchange authorization code for API key @@ -52,11 +54,7 @@ export function oAuthExchangeAuthCodeForAPIKey( | SDKValidationError > > { - return new APIPromise($do( - client, - request, - options, - )); + return new APIPromise($do(client, request, options)); } async function $do( @@ -84,70 +82,114 @@ async function $do( > { const parsed = safeParse( request, - (value) => - operations.ExchangeAuthCodeForAPIKeyRequest$outboundSchema.parse(value), - "Input validation failed", + (value) => operations.ExchangeAuthCodeForAPIKeyRequest$outboundSchema.parse(value), + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; - const body = encodeJSON("body", payload, { explode: true }); + const body = encodeJSON('body', payload, { + explode: true, + }); - const path = pathToFunc("/auth/keys")(); + const path = pathToFunc('/auth/keys')(); - const headers = new Headers(compactMap({ - "Content-Type": "application/json", - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + 'Content-Type': 'application/json', + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "exchangeAuthCodeForAPIKey", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'exchangeAuthCodeForAPIKey', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "POST", - baseURL: options?.serverURL, - path: path, - headers: headers, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'POST', + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["400", "403", "4XX", "500", "5XX"], + errorCodes: [ + '400', + '403', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -168,12 +210,28 @@ async function $do( M.jsonErr(400, errors.BadRequestResponseError$inboundSchema), M.jsonErr(403, errors.ForbiddenResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/parametersGetParameters.ts b/src/funcs/parametersGetParameters.ts index fe89f6f5..823ca3cf 100644 --- a/src/funcs/parametersGetParameters.ts +++ b/src/funcs/parametersGetParameters.ts @@ -3,28 +3,30 @@ * @generated-id: 565ce9801e34 */ -import { OpenRouterCore } from "../core.js"; -import { encodeFormQuery, encodeSimple } from "../lib/encodings.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { resolveSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import { encodeFormQuery, encodeSimple } from '../lib/encodings.js'; +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { resolveSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * Get a model's supported parameters and data about which are most popular @@ -50,12 +52,7 @@ export function parametersGetParameters( | SDKValidationError > > { - return new APIPromise($do( - client, - security, - request, - options, - )); + return new APIPromise($do(client, security, request, options)); } async function $do( @@ -85,89 +82,125 @@ async function $do( const parsed = safeParse( request, (value) => operations.GetParametersRequest$outboundSchema.parse(value), - "Input validation failed", + 'Input validation failed', ); if (!parsed.ok) { - return [parsed, { status: "invalid" }]; + return [ + parsed, + { + status: 'invalid', + }, + ]; } const payload = parsed.value; const body = null; const pathParams = { - author: encodeSimple("author", payload.author, { + author: encodeSimple('author', payload.author, { explode: false, - charEncoding: "percent", + charEncoding: 'percent', }), - slug: encodeSimple("slug", payload.slug, { + slug: encodeSimple('slug', payload.slug, { explode: false, - charEncoding: "percent", + charEncoding: 'percent', }), }; - const path = pathToFunc("/parameters/{author}/{slug}")(pathParams); + const path = pathToFunc('/parameters/{author}/{slug}')(pathParams); const query = encodeFormQuery({ - "provider": payload.provider, + provider: payload.provider, }); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); - - const requestSecurity = resolveSecurity( - [ - { - fieldName: "Authorization", - type: "http:bearer", - value: security?.bearer, - }, - ], + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), ); + const requestSecurity = resolveSecurity([ + { + fieldName: 'Authorization', + type: 'http:bearer', + value: security?.bearer, + }, + ]); + const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "getParameters", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'getParameters', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: security, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - query: query, - body: body, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["401", "404", "4XX", "500", "5XX"], + errorCodes: [ + '401', + '404', + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -188,12 +221,28 @@ async function $do( M.jsonErr(401, errors.UnauthorizedResponseError$inboundSchema), M.jsonErr(404, errors.NotFoundResponseError$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/funcs/providersList.ts b/src/funcs/providersList.ts index 790ffbf9..2e99dcda 100644 --- a/src/funcs/providersList.ts +++ b/src/funcs/providersList.ts @@ -3,26 +3,28 @@ * @generated-id: 8ad87e7210ae */ -import { OpenRouterCore } from "../core.js"; -import * as M from "../lib/matchers.js"; -import { compactMap } from "../lib/primitives.js"; -import { RequestOptions } from "../lib/sdks.js"; -import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; -import { +import type { OpenRouterCore } from '../core.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import * as errors from "../models/errors/index.js"; -import { OpenRouterError } from "../models/errors/openroutererror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import * as operations from "../models/operations/index.js"; -import { APICall, APIPromise } from "../types/async.js"; -import { Result } from "../types/fp.js"; +} from '../models/errors/httpclienterrors.js'; +import type { OpenRouterError } from '../models/errors/openroutererror.js'; +import type { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import type { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import type { APICall } from '../types/async.js'; +import type { Result } from '../types/fp.js'; + +import * as M from '../lib/matchers.js'; +import { compactMap } from '../lib/primitives.js'; +import { extractSecurity, resolveGlobalSecurity } from '../lib/security.js'; +import { pathToFunc } from '../lib/url.js'; +import * as errors from '../models/errors/index.js'; +import * as operations from '../models/operations/index.js'; +import { APIPromise } from '../types/async.js'; /** * List all providers @@ -44,10 +46,7 @@ export function providersList( | SDKValidationError > > { - return new APIPromise($do( - client, - options, - )); + return new APIPromise($do(client, options)); } async function $do( @@ -70,58 +69,94 @@ async function $do( APICall, ] > { - const path = pathToFunc("/providers")(); + const path = pathToFunc('/providers')(); - const headers = new Headers(compactMap({ - Accept: "application/json", - })); + const headers = new Headers( + compactMap({ + Accept: 'application/json', + }), + ); const secConfig = await extractSecurity(client._options.apiKey); - const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const securityInput = + secConfig == null + ? {} + : { + apiKey: secConfig, + }; const requestSecurity = resolveGlobalSecurity(securityInput); const context = { options: client._options, - baseURL: options?.serverURL ?? client._baseURL ?? "", - operationID: "listProviders", + baseURL: options?.serverURL ?? client._baseURL ?? '', + operationID: 'listProviders', oAuth2Scopes: null, resolvedSecurity: requestSecurity, securitySource: client._options.apiKey, - retryConfig: options?.retries - || client._options.retryConfig - || { strategy: "none" }, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + retryConfig: options?.retries || + client._options.retryConfig || { + strategy: 'none', + }, + retryCodes: options?.retryCodes || [ + '429', + '500', + '502', + '503', + '504', + ], }; - const requestRes = client._createRequest(context, { - security: requestSecurity, - method: "GET", - baseURL: options?.serverURL, - path: path, - headers: headers, - userAgent: client._options.userAgent, - timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, - }, options); + const requestRes = client._createRequest( + context, + { + security: requestSecurity, + method: 'GET', + baseURL: options?.serverURL, + path: path, + headers: headers, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, + options, + ); if (!requestRes.ok) { - return [requestRes, { status: "invalid" }]; + return [ + requestRes, + { + status: 'invalid', + }, + ]; } const req = requestRes.value; const doResult = await client._do(req, { context, - errorCodes: ["4XX", "500", "5XX"], + errorCodes: [ + '4XX', + '500', + '5XX', + ], retryConfig: context.retryConfig, retryCodes: context.retryCodes, }); if (!doResult.ok) { - return [doResult, { status: "request-error", request: req }]; + return [ + doResult, + { + status: 'request-error', + request: req, + }, + ]; } const response = doResult.value; const responseFields = { - HttpMeta: { Response: response, Request: req }, + HttpMeta: { + Response: response, + Request: req, + }, }; const [result] = await M.match< @@ -138,12 +173,28 @@ async function $do( >( M.json(200, operations.ListProvidersResponse$inboundSchema), M.jsonErr(500, errors.InternalServerResponseError$inboundSchema), - M.fail("4XX"), - M.fail("5XX"), - )(response, req, { extraFields: responseFields }); + M.fail('4XX'), + M.fail('5XX'), + )(response, req, { + extraFields: responseFields, + }); if (!result.ok) { - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } - return [result, { status: "complete", request: req, response }]; + return [ + result, + { + status: 'complete', + request: req, + response, + }, + ]; } diff --git a/src/hooks/hooks.ts b/src/hooks/hooks.ts index ebc4ecc4..1bdd4018 100644 --- a/src/hooks/hooks.ts +++ b/src/hooks/hooks.ts @@ -3,9 +3,9 @@ * @generated-id: a2463fc6f69b */ -import { SDKOptions } from "../lib/config.js"; -import { RequestInput } from "../lib/http.js"; -import { +import type { SDKOptions } from '../lib/config.js'; +import type { RequestInput } from '../lib/http.js'; +import type { AfterErrorContext, AfterErrorHook, AfterSuccessContext, @@ -17,9 +17,9 @@ import { Hook, Hooks, SDKInitHook, -} from "./types.js"; +} from './types.js'; -import { initHooks } from "./registration.js"; +import { initHooks } from './registration.js'; export class SDKHooks implements Hooks { sdkInitHooks: SDKInitHook[] = []; @@ -32,19 +32,19 @@ export class SDKHooks implements Hooks { const presetHooks: Array = []; for (const hook of presetHooks) { - if ("sdkInit" in hook) { + if ('sdkInit' in hook) { this.registerSDKInitHook(hook); } - if ("beforeCreateRequest" in hook) { + if ('beforeCreateRequest' in hook) { this.registerBeforeCreateRequestHook(hook); } - if ("beforeRequest" in hook) { + if ('beforeRequest' in hook) { this.registerBeforeRequestHook(hook); } - if ("afterSuccess" in hook) { + if ('afterSuccess' in hook) { this.registerAfterSuccessHook(hook); } - if ("afterError" in hook) { + if ('afterError' in hook) { this.registerAfterErrorHook(hook); } } @@ -75,10 +75,7 @@ export class SDKHooks implements Hooks { return this.sdkInitHooks.reduce((opts, hook) => hook.sdkInit(opts), opts); } - beforeCreateRequest( - hookCtx: BeforeCreateRequestContext, - input: RequestInput, - ): RequestInput { + beforeCreateRequest(hookCtx: BeforeCreateRequestContext, input: RequestInput): RequestInput { let inp = input; for (const hook of this.beforeCreateRequestHooks) { @@ -88,10 +85,7 @@ export class SDKHooks implements Hooks { return inp; } - async beforeRequest( - hookCtx: BeforeRequestContext, - request: Request, - ): Promise { + async beforeRequest(hookCtx: BeforeRequestContext, request: Request): Promise { let req = request; for (const hook of this.beforeRequestHooks) { @@ -101,10 +95,7 @@ export class SDKHooks implements Hooks { return req; } - async afterSuccess( - hookCtx: AfterSuccessContext, - response: Response, - ): Promise { + async afterSuccess(hookCtx: AfterSuccessContext, response: Response): Promise { let res = response; for (const hook of this.afterSuccessHooks) { @@ -118,7 +109,10 @@ export class SDKHooks implements Hooks { hookCtx: AfterErrorContext, response: Response | null, error: unknown, - ): Promise<{ response: Response | null; error: unknown }> { + ): Promise<{ + response: Response | null; + error: unknown; + }> { let res = response; let err = error; @@ -128,6 +122,9 @@ export class SDKHooks implements Hooks { err = result.error; } - return { response: res, error: err }; + return { + response: res, + error: err, + }; } } diff --git a/src/hooks/index.ts b/src/hooks/index.ts index 9345e1ad..8831ed40 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -3,5 +3,5 @@ * @generated-id: 5f2dab62b520 */ -export * from "./hooks.js"; -export * from "./types.js"; +export * from './hooks.js'; +export * from './types.js'; diff --git a/src/hooks/types.ts b/src/hooks/types.ts index ccd5e5d8..7e7cbb8c 100644 --- a/src/hooks/types.ts +++ b/src/hooks/types.ts @@ -3,10 +3,10 @@ * @generated-id: 2a02d86ec24f */ -import { SDKOptions } from "../lib/config.js"; -import { RequestInput } from "../lib/http.js"; -import { RetryConfig } from "../lib/retries.js"; -import { SecurityState } from "../lib/security.js"; +import type { SDKOptions } from '../lib/config.js'; +import type { RequestInput } from '../lib/http.js'; +import type { RetryConfig } from '../lib/retries.js'; +import type { SecurityState } from '../lib/security.js'; export type HookContext = { baseURL: string | URL; @@ -39,10 +39,7 @@ export interface BeforeCreateRequestHook { * can modify how a request is constructed since certain modifications, like * changing the request URL, cannot be done on a request object directly. */ - beforeCreateRequest: ( - hookCtx: BeforeCreateRequestContext, - input: RequestInput, - ) => RequestInput; + beforeCreateRequest: (hookCtx: BeforeCreateRequestContext, input: RequestInput) => RequestInput; } export interface BeforeRequestHook { @@ -52,10 +49,7 @@ export interface BeforeRequestHook { * replace the request before it is sent or throw an error to stop the * request from being sent. */ - beforeRequest: ( - hookCtx: BeforeRequestContext, - request: Request, - ) => Awaitable; + beforeRequest: (hookCtx: BeforeRequestContext, request: Request) => Awaitable; } export interface AfterSuccessHook { @@ -65,10 +59,7 @@ export interface AfterSuccessHook { * modify the response before it is handled or throw an error to stop the * response from being handled. */ - afterSuccess: ( - hookCtx: AfterSuccessContext, - response: Response, - ) => Awaitable; + afterSuccess: (hookCtx: AfterSuccessContext, response: Response) => Awaitable; } export interface AfterErrorHook { diff --git a/src/index.ts b/src/index.ts index e07ef423..e40e2024 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,71 +2,71 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -export * from "./lib/config.js"; -export * as files from "./lib/files.js"; -export { HTTPClient } from "./lib/http.js"; -export type { Fetcher, HTTPClientOptions } from "./lib/http.js"; -export * from "./sdk/sdk.js"; - -// Message format compatibility helpers -export { fromClaudeMessages, toClaudeMessage } from "./lib/anthropic-compat.js"; -export { fromChatMessages, toChatMessage } from "./lib/chat-compat.js"; -export { extractUnsupportedContent, hasUnsupportedContent, getUnsupportedContentSummary } from "./lib/stream-transformers.js"; - +export type { Fetcher, HTTPClientOptions } from './lib/http.js'; +// Tool types +export type { + ChatStreamEvent, + EnhancedResponseStreamEvent, + InferToolEvent, + InferToolEventsUnion, + InferToolInput, + InferToolOutput, + ManualTool, + Tool, + ToolPreliminaryResultEvent, + ToolStreamEvent, + ToolWithExecute, + ToolWithGenerator, + TurnContext, + TypedToolCall, + TypedToolCallUnion, +} from './lib/tool-types.js'; // Claude message types export type { - ClaudeMessage, - ClaudeMessageParam, + ClaudeBase64ImageSource, + ClaudeCacheControl, + ClaudeCitationCharLocation, + ClaudeCitationContentBlockLocation, + ClaudeCitationPageLocation, + ClaudeCitationSearchResultLocation, + ClaudeCitationWebSearchResultLocation, ClaudeContentBlock, ClaudeContentBlockParam, - ClaudeTextBlock, - ClaudeThinkingBlock, + ClaudeImageBlockParam, + ClaudeMessage, + ClaudeMessageParam, ClaudeRedactedThinkingBlock, - ClaudeToolUseBlock, ClaudeServerToolUseBlock, - ClaudeTextBlockParam, - ClaudeImageBlockParam, - ClaudeToolUseBlockParam, - ClaudeToolResultBlockParam, ClaudeStopReason, - ClaudeUsage, - ClaudeCacheControl, + ClaudeTextBlock, + ClaudeTextBlockParam, ClaudeTextCitation, - ClaudeCitationCharLocation, - ClaudeCitationPageLocation, - ClaudeCitationContentBlockLocation, - ClaudeCitationWebSearchResultLocation, - ClaudeCitationSearchResultLocation, - ClaudeBase64ImageSource, + ClaudeThinkingBlock, + ClaudeToolResultBlockParam, + ClaudeToolUseBlock, + ClaudeToolUseBlockParam, ClaudeURLImageSource, -} from "./models/claude-message.js"; + ClaudeUsage, +} from './models/claude-message.js'; +// Message format compatibility helpers +export { fromClaudeMessages, toClaudeMessage } from './lib/anthropic-compat.js'; +export { fromChatMessages, toChatMessage } from './lib/chat-compat.js'; +export * from './lib/config.js'; +export * as files from './lib/files.js'; +export { HTTPClient } from './lib/http.js'; +export { + extractUnsupportedContent, + getUnsupportedContentSummary, + hasUnsupportedContent, +} from './lib/stream-transformers.js'; // Tool creation helpers -export { tool } from "./lib/tool.js"; - -// Tool types -export type { - Tool, - ToolWithExecute, - ToolWithGenerator, - ManualTool, - TurnContext, - InferToolInput, - InferToolOutput, - InferToolEvent, - InferToolEventsUnion, - TypedToolCall, - TypedToolCallUnion, - ToolStreamEvent, - ChatStreamEvent, - EnhancedResponseStreamEvent, - ToolPreliminaryResultEvent, -} from "./lib/tool-types.js"; - +export { tool } from './lib/tool.js'; export { - ToolType, hasExecuteFunction, isGeneratorTool, isRegularExecuteTool, isToolPreliminaryResultEvent, -} from "./lib/tool-types.js"; + ToolType, +} from './lib/tool-types.js'; +export * from './sdk/sdk.js'; diff --git a/src/lib/anthropic-compat.test.ts b/src/lib/anthropic-compat.test.ts index 10ebfcb3..0b78aff2 100644 --- a/src/lib/anthropic-compat.test.ts +++ b/src/lib/anthropic-compat.test.ts @@ -1,6 +1,7 @@ -import { describe, expect, it } from "vitest"; -import { fromClaudeMessages, toClaudeMessage } from "./anthropic-compat.js"; -import type * as models from "../models/index.js"; +import type * as models from '../models/index.js'; + +import { describe, expect, it } from 'vitest'; +import { fromClaudeMessages, toClaudeMessage } from './anthropic-compat.js'; /** * Creates a properly typed mock OpenResponsesNonStreamingResponse for testing. @@ -8,93 +9,137 @@ import type * as models from "../models/index.js"; */ function createMockResponse( overrides: Partial & { - output: models.OpenResponsesNonStreamingResponse["output"]; - } + output: models.OpenResponsesNonStreamingResponse['output']; + }, ): models.OpenResponsesNonStreamingResponse { return { - id: "resp_test", - object: "response", + id: 'resp_test', + object: 'response', createdAt: Date.now(), - model: "openai/gpt-4", - status: "completed", + model: 'openai/gpt-4', + status: 'completed', error: null, incompleteDetails: null, temperature: null, topP: null, metadata: null, tools: [], - toolChoice: "auto", + toolChoice: 'auto', parallelToolCalls: false, ...overrides, }; } -describe("fromClaudeMessages", () => { - describe("basic message conversion", () => { - it("converts user message with string content", () => { +describe('fromClaudeMessages', () => { + describe('basic message conversion', () => { + it('converts user message with string content', () => { const claudeMessages: models.ClaudeMessageParam[] = [ - { role: "user", content: "Hello, how are you?" }, + { + role: 'user', + content: 'Hello, how are you?', + }, ]; const result = fromClaudeMessages(claudeMessages); expect(result).toEqual([ - { role: "user", content: "Hello, how are you?" }, + { + role: 'user', + content: 'Hello, how are you?', + }, ]); }); - it("converts assistant message with string content", () => { + it('converts assistant message with string content', () => { const claudeMessages: models.ClaudeMessageParam[] = [ - { role: "assistant", content: "I am doing well, thank you!" }, + { + role: 'assistant', + content: 'I am doing well, thank you!', + }, ]; const result = fromClaudeMessages(claudeMessages); expect(result).toEqual([ - { role: "assistant", content: "I am doing well, thank you!" }, + { + role: 'assistant', + content: 'I am doing well, thank you!', + }, ]); }); - it("converts multiple messages in conversation", () => { + it('converts multiple messages in conversation', () => { const claudeMessages: models.ClaudeMessageParam[] = [ - { role: "user", content: "Hi" }, - { role: "assistant", content: "Hello!" }, - { role: "user", content: "How are you?" }, + { + role: 'user', + content: 'Hi', + }, + { + role: 'assistant', + content: 'Hello!', + }, + { + role: 'user', + content: 'How are you?', + }, ]; const result = fromClaudeMessages(claudeMessages); expect(result).toEqual([ - { role: "user", content: "Hi" }, - { role: "assistant", content: "Hello!" }, - { role: "user", content: "How are you?" }, + { + role: 'user', + content: 'Hi', + }, + { + role: 'assistant', + content: 'Hello!', + }, + { + role: 'user', + content: 'How are you?', + }, ]); }); }); - describe("text block content conversion", () => { - it("converts user message with text block array", () => { + describe('text block content conversion', () => { + it('converts user message with text block array', () => { const claudeMessages: models.ClaudeMessageParam[] = [ { - role: "user", - content: [{ type: "text", text: "Hello from text block" }], + role: 'user', + content: [ + { + type: 'text', + text: 'Hello from text block', + }, + ], }, ]; const result = fromClaudeMessages(claudeMessages); expect(result).toEqual([ - { role: "user", content: "Hello from text block" }, + { + role: 'user', + content: 'Hello from text block', + }, ]); }); - it("combines multiple text blocks into single content string", () => { + it('combines multiple text blocks into single content string', () => { const claudeMessages: models.ClaudeMessageParam[] = [ { - role: "user", + role: 'user', content: [ - { type: "text", text: "First part. " }, - { type: "text", text: "Second part." }, + { + type: 'text', + text: 'First part. ', + }, + { + type: 'text', + text: 'Second part.', + }, ], }, ]; @@ -102,21 +147,24 @@ describe("fromClaudeMessages", () => { const result = fromClaudeMessages(claudeMessages); expect(result).toEqual([ - { role: "user", content: "First part. Second part." }, + { + role: 'user', + content: 'First part. Second part.', + }, ]); }); }); - describe("tool_result block conversion", () => { - it("converts tool_result with string content to function_call_output", () => { + describe('tool_result block conversion', () => { + it('converts tool_result with string content to function_call_output', () => { const claudeMessages: models.ClaudeMessageParam[] = [ { - role: "user", + role: 'user', content: [ { - type: "tool_result", - tool_use_id: "tool_123", - content: "Tool execution result", + type: 'tool_result', + tool_use_id: 'tool_123', + content: 'Tool execution result', }, ], }, @@ -126,24 +174,30 @@ describe("fromClaudeMessages", () => { expect(result).toEqual([ { - type: "function_call_output", - callId: "tool_123", - output: "Tool execution result", + type: 'function_call_output', + callId: 'tool_123', + output: 'Tool execution result', }, ]); }); - it("converts tool_result with text block array to function_call_output", () => { + it('converts tool_result with text block array to function_call_output', () => { const claudeMessages: models.ClaudeMessageParam[] = [ { - role: "user", + role: 'user', content: [ { - type: "tool_result", - tool_use_id: "tool_456", + type: 'tool_result', + tool_use_id: 'tool_456', content: [ - { type: "text", text: "Result part 1. " }, - { type: "text", text: "Result part 2." }, + { + type: 'text', + text: 'Result part 1. ', + }, + { + type: 'text', + text: 'Result part 2.', + }, ], }, ], @@ -154,25 +208,31 @@ describe("fromClaudeMessages", () => { expect(result).toEqual([ { - type: "function_call_output", - callId: "tool_456", - output: "Result part 1. Result part 2.", + type: 'function_call_output', + callId: 'tool_456', + output: 'Result part 1. Result part 2.', }, ]); }); - it("handles mixed text and tool_result blocks", () => { + it('handles mixed text and tool_result blocks', () => { const claudeMessages: models.ClaudeMessageParam[] = [ { - role: "user", + role: 'user', content: [ - { type: "text", text: "Here is some context. " }, { - type: "tool_result", - tool_use_id: "tool_789", - content: "Tool output", + type: 'text', + text: 'Here is some context. ', + }, + { + type: 'tool_result', + tool_use_id: 'tool_789', + content: 'Tool output', + }, + { + type: 'text', + text: 'And some more text.', }, - { type: "text", text: "And some more text." }, ], }, ]; @@ -182,27 +242,35 @@ describe("fromClaudeMessages", () => { // Should produce both the text message and the function_call_output expect(result).toEqual([ { - type: "function_call_output", - callId: "tool_789", - output: "Tool output", + type: 'function_call_output', + callId: 'tool_789', + output: 'Tool output', + }, + { + role: 'user', + content: 'Here is some context. And some more text.', }, - { role: "user", content: "Here is some context. And some more text." }, ]); }); }); - describe("tool_use blocks (should be skipped)", () => { - it("skips tool_use blocks as they are output from assistant", () => { + describe('tool_use blocks (should be skipped)', () => { + it('skips tool_use blocks as they are output from assistant', () => { const claudeMessages: models.ClaudeMessageParam[] = [ { - role: "assistant", + role: 'assistant', content: [ - { type: "text", text: "Let me help you with that." }, { - type: "tool_use", - id: "tool_abc", - name: "get_weather", - input: { location: "SF" }, + type: 'text', + text: 'Let me help you with that.', + }, + { + type: 'tool_use', + id: 'tool_abc', + name: 'get_weather', + input: { + location: 'SF', + }, }, ], }, @@ -212,24 +280,30 @@ describe("fromClaudeMessages", () => { // Only the text should be captured, tool_use is from previous response expect(result).toEqual([ - { role: "assistant", content: "Let me help you with that." }, + { + role: 'assistant', + content: 'Let me help you with that.', + }, ]); }); }); - describe("image blocks (should be skipped)", () => { - it("skips image blocks", () => { + describe('image blocks (should be skipped)', () => { + it('skips image blocks', () => { const claudeMessages: models.ClaudeMessageParam[] = [ { - role: "user", + role: 'user', content: [ - { type: "text", text: "Look at this image:" }, { - type: "image", + type: 'text', + text: 'Look at this image:', + }, + { + type: 'image', source: { - type: "base64", - media_type: "image/png", - data: "base64data...", + type: 'base64', + media_type: 'image/png', + data: 'base64data...', }, }, ], @@ -240,30 +314,44 @@ describe("fromClaudeMessages", () => { // Only the text should be captured expect(result).toEqual([ - { role: "user", content: "Look at this image:" }, + { + role: 'user', + content: 'Look at this image:', + }, ]); }); }); - describe("empty and edge cases", () => { - it("handles empty messages array", () => { + describe('empty and edge cases', () => { + it('handles empty messages array', () => { const result = fromClaudeMessages([]); expect(result).toEqual([]); }); - it("handles message with empty string content", () => { + it('handles message with empty string content', () => { const claudeMessages: models.ClaudeMessageParam[] = [ - { role: "user", content: "" }, + { + role: 'user', + content: '', + }, ]; const result = fromClaudeMessages(claudeMessages); - expect(result).toEqual([{ role: "user", content: "" }]); + expect(result).toEqual([ + { + role: 'user', + content: '', + }, + ]); }); - it("handles message with empty content array", () => { + it('handles message with empty content array', () => { const claudeMessages: models.ClaudeMessageParam[] = [ - { role: "user", content: [] }, + { + role: 'user', + content: [], + }, ]; const result = fromClaudeMessages(claudeMessages); @@ -274,21 +362,21 @@ describe("fromClaudeMessages", () => { }); }); -describe("toClaudeMessage", () => { - describe("basic message conversion", () => { - it("converts response with text output to ClaudeMessage", () => { +describe('toClaudeMessage', () => { + describe('basic message conversion', () => { + it('converts response with text output to ClaudeMessage', () => { const response = createMockResponse({ - id: "resp_123", + id: 'resp_123', output: [ { - id: "msg_1", - type: "message", - role: "assistant", - status: "completed", + id: 'msg_1', + type: 'message', + role: 'assistant', + status: 'completed', content: [ { - type: "output_text", - text: "Hello! How can I help you?", + type: 'output_text', + text: 'Hello! How can I help you?', annotations: [], }, ], @@ -298,25 +386,29 @@ describe("toClaudeMessage", () => { inputTokens: 10, outputTokens: 20, totalTokens: 30, - inputTokensDetails: { cachedTokens: 0 }, - outputTokensDetails: { reasoningTokens: 0 }, + inputTokensDetails: { + cachedTokens: 0, + }, + outputTokensDetails: { + reasoningTokens: 0, + }, }, }); const result = toClaudeMessage(response); expect(result).toEqual({ - id: "resp_123", - type: "message", - role: "assistant", - model: "openai/gpt-4", + id: 'resp_123', + type: 'message', + role: 'assistant', + model: 'openai/gpt-4', content: [ { - type: "text", - text: "Hello! How can I help you?", + type: 'text', + text: 'Hello! How can I help you?', }, ], - stop_reason: "end_turn", + stop_reason: 'end_turn', stop_sequence: null, usage: { input_tokens: 10, @@ -328,26 +420,30 @@ describe("toClaudeMessage", () => { }); }); - describe("function call conversion", () => { - it("converts function_call output to tool_use block", () => { + describe('function call conversion', () => { + it('converts function_call output to tool_use block', () => { const response = createMockResponse({ - id: "resp_456", + id: 'resp_456', output: [ { - type: "function_call", - callId: "call_abc", - name: "get_weather", + type: 'function_call', + callId: 'call_abc', + name: 'get_weather', arguments: '{"location":"San Francisco"}', - id: "fc_1", - status: "completed", + id: 'fc_1', + status: 'completed', }, ], usage: { inputTokens: 15, outputTokens: 25, totalTokens: 40, - inputTokensDetails: { cachedTokens: 0 }, - outputTokensDetails: { reasoningTokens: 0 }, + inputTokensDetails: { + cachedTokens: 0, + }, + outputTokensDetails: { + reasoningTokens: 0, + }, }, }); @@ -355,41 +451,43 @@ describe("toClaudeMessage", () => { expect(result.content).toEqual([ { - type: "tool_use", - id: "call_abc", - name: "get_weather", - input: { location: "San Francisco" }, + type: 'tool_use', + id: 'call_abc', + name: 'get_weather', + input: { + location: 'San Francisco', + }, }, ]); - expect(result.stop_reason).toBe("tool_use"); + expect(result.stop_reason).toBe('tool_use'); }); }); - describe("reasoning conversion", () => { - it("converts reasoning output to thinking block", () => { + describe('reasoning conversion', () => { + it('converts reasoning output to thinking block', () => { const response = createMockResponse({ - id: "resp_789", - model: "openai/o1", + id: 'resp_789', + model: 'openai/o1', output: [ { - type: "reasoning", - id: "reason_1", + type: 'reasoning', + id: 'reason_1', summary: [ { - type: "summary_text", - text: "I need to think about this carefully...", + type: 'summary_text', + text: 'I need to think about this carefully...', }, ], }, { - id: "msg_2", - type: "message", - role: "assistant", - status: "completed", + id: 'msg_2', + type: 'message', + role: 'assistant', + status: 'completed', content: [ { - type: "output_text", - text: "Here is my answer.", + type: 'output_text', + text: 'Here is my answer.', annotations: [], }, ], @@ -399,8 +497,12 @@ describe("toClaudeMessage", () => { inputTokens: 20, outputTokens: 100, totalTokens: 120, - inputTokensDetails: { cachedTokens: 0 }, - outputTokensDetails: { reasoningTokens: 0 }, + inputTokensDetails: { + cachedTokens: 0, + }, + outputTokensDetails: { + reasoningTokens: 0, + }, }, }); @@ -408,57 +510,73 @@ describe("toClaudeMessage", () => { expect(result.content).toEqual([ { - type: "thinking", - thinking: "I need to think about this carefully...", - signature: "", + type: 'thinking', + thinking: 'I need to think about this carefully...', + signature: '', }, { - type: "text", - text: "Here is my answer.", + type: 'text', + text: 'Here is my answer.', }, ]); }); }); - describe("stop reason mapping", () => { - it("maps completed status to end_turn", () => { + describe('stop reason mapping', () => { + it('maps completed status to end_turn', () => { const response = createMockResponse({ - id: "resp_1", + id: 'resp_1', output: [ { - id: "msg_1", - type: "message", - role: "assistant", - status: "completed", - content: [{ type: "output_text", text: "Done", annotations: [] }], + id: 'msg_1', + type: 'message', + role: 'assistant', + status: 'completed', + content: [ + { + type: 'output_text', + text: 'Done', + annotations: [], + }, + ], }, ], usage: { inputTokens: 5, outputTokens: 5, totalTokens: 10, - inputTokensDetails: { cachedTokens: 0 }, - outputTokensDetails: { reasoningTokens: 0 }, + inputTokensDetails: { + cachedTokens: 0, + }, + outputTokensDetails: { + reasoningTokens: 0, + }, }, }); const result = toClaudeMessage(response); - expect(result.stop_reason).toBe("end_turn"); + expect(result.stop_reason).toBe('end_turn'); }); - it("maps incomplete with max_output_tokens to max_tokens", () => { + it('maps incomplete with max_output_tokens to max_tokens', () => { const response = createMockResponse({ - id: "resp_2", - status: "incomplete", - incompleteDetails: { reason: "max_output_tokens" }, + id: 'resp_2', + status: 'incomplete', + incompleteDetails: { + reason: 'max_output_tokens', + }, output: [ { - id: "msg_1", - type: "message", - role: "assistant", - status: "incomplete", + id: 'msg_1', + type: 'message', + role: 'assistant', + status: 'incomplete', content: [ - { type: "output_text", text: "Partial...", annotations: [] }, + { + type: 'output_text', + text: 'Partial...', + annotations: [], + }, ], }, ], @@ -466,53 +584,67 @@ describe("toClaudeMessage", () => { inputTokens: 5, outputTokens: 100, totalTokens: 105, - inputTokensDetails: { cachedTokens: 0 }, - outputTokensDetails: { reasoningTokens: 0 }, + inputTokensDetails: { + cachedTokens: 0, + }, + outputTokensDetails: { + reasoningTokens: 0, + }, }, }); const result = toClaudeMessage(response); - expect(result.stop_reason).toBe("max_tokens"); + expect(result.stop_reason).toBe('max_tokens'); }); - it("maps response with function calls to tool_use", () => { + it('maps response with function calls to tool_use', () => { const response = createMockResponse({ - id: "resp_3", + id: 'resp_3', output: [ { - type: "function_call", - callId: "call_1", - name: "test_tool", - arguments: "{}", - id: "fc_1", - status: "completed", + type: 'function_call', + callId: 'call_1', + name: 'test_tool', + arguments: '{}', + id: 'fc_1', + status: 'completed', }, ], usage: { inputTokens: 5, outputTokens: 10, totalTokens: 15, - inputTokensDetails: { cachedTokens: 0 }, - outputTokensDetails: { reasoningTokens: 0 }, + inputTokensDetails: { + cachedTokens: 0, + }, + outputTokensDetails: { + reasoningTokens: 0, + }, }, }); const result = toClaudeMessage(response); - expect(result.stop_reason).toBe("tool_use"); + expect(result.stop_reason).toBe('tool_use'); }); }); - describe("usage mapping", () => { - it("maps usage with cached tokens", () => { + describe('usage mapping', () => { + it('maps usage with cached tokens', () => { const response = createMockResponse({ - id: "resp_1", + id: 'resp_1', output: [ { - id: "msg_1", - type: "message", - role: "assistant", - status: "completed", - content: [{ type: "output_text", text: "OK", annotations: [] }], + id: 'msg_1', + type: 'message', + role: 'assistant', + status: 'completed', + content: [ + { + type: 'output_text', + text: 'OK', + annotations: [], + }, + ], }, ], usage: { @@ -522,7 +654,9 @@ describe("toClaudeMessage", () => { inputTokensDetails: { cachedTokens: 80, }, - outputTokensDetails: { reasoningTokens: 0 }, + outputTokensDetails: { + reasoningTokens: 0, + }, }, }); diff --git a/src/lib/anthropic-compat.ts b/src/lib/anthropic-compat.ts index 1fe68c25..df27150d 100644 --- a/src/lib/anthropic-compat.ts +++ b/src/lib/anthropic-compat.ts @@ -5,7 +5,10 @@ import { OpenResponsesEasyInputMessageRoleUser, } from '../models/openresponseseasyinputmessage.js'; import { OpenResponsesFunctionCallOutputType } from '../models/openresponsesfunctioncalloutput.js'; -import { OpenResponsesInputMessageItemRoleUser, OpenResponsesInputMessageItemRoleDeveloper } from '../models/openresponsesinputmessageitem.js'; +import { + OpenResponsesInputMessageItemRoleDeveloper, + OpenResponsesInputMessageItemRoleUser, +} from '../models/openresponsesinputmessageitem.js'; import { convertToClaudeMessage } from './stream-transformers.js'; /** diff --git a/src/lib/base64.ts b/src/lib/base64.ts index a187e587..a0a8c64b 100644 --- a/src/lib/base64.ts +++ b/src/lib/base64.ts @@ -3,7 +3,7 @@ * @generated-id: 598522066688 */ -import * as z from "zod/v4"; +import * as z from 'zod/v4'; export function bytesToBase64(u8arr: Uint8Array): string { return btoa(String.fromCodePoint(...u8arr)); @@ -29,8 +29,10 @@ export function stringFromBase64(b64str: string): string { return stringFromBytes(bytesFromBase64(b64str)); } -export const zodOutbound = z.custom(x => x instanceof Uint8Array) +export const zodOutbound = z + .custom((x) => x instanceof Uint8Array) .or(z.string().transform(stringToBytes)); -export const zodInbound = z.custom(x => x instanceof Uint8Array) +export const zodInbound = z + .custom((x) => x instanceof Uint8Array) .or(z.string().transform(bytesFromBase64)); diff --git a/src/lib/chat-compat.test.ts b/src/lib/chat-compat.test.ts index 7fe73e10..88b11b9c 100644 --- a/src/lib/chat-compat.test.ts +++ b/src/lib/chat-compat.test.ts @@ -1,6 +1,7 @@ -import { describe, expect, it } from "vitest"; -import { fromChatMessages, toChatMessage } from "./chat-compat.js"; -import type * as models from "../models/index.js"; +import type * as models from '../models/index.js'; + +import { describe, expect, it } from 'vitest'; +import { fromChatMessages, toChatMessage } from './chat-compat.js'; /** * Creates a properly typed mock OpenResponsesNonStreamingResponse for testing. @@ -8,103 +9,151 @@ import type * as models from "../models/index.js"; */ function createMockResponse( overrides: Partial & { - output: models.OpenResponsesNonStreamingResponse["output"]; - } + output: models.OpenResponsesNonStreamingResponse['output']; + }, ): models.OpenResponsesNonStreamingResponse { return { - id: "resp_test", - object: "response", + id: 'resp_test', + object: 'response', createdAt: Date.now(), - model: "openai/gpt-4", - status: "completed", + model: 'openai/gpt-4', + status: 'completed', error: null, incompleteDetails: null, temperature: null, topP: null, metadata: null, tools: [], - toolChoice: "auto", + toolChoice: 'auto', parallelToolCalls: false, ...overrides, }; } -describe("fromChatMessages", () => { - describe("basic message conversion", () => { - it("converts user message with string content", () => { +describe('fromChatMessages', () => { + describe('basic message conversion', () => { + it('converts user message with string content', () => { const messages: models.Message[] = [ - { role: "user", content: "Hello, how are you?" }, + { + role: 'user', + content: 'Hello, how are you?', + }, ]; const result = fromChatMessages(messages); expect(result).toEqual([ - { role: "user", content: "Hello, how are you?" }, + { + role: 'user', + content: 'Hello, how are you?', + }, ]); }); - it("converts assistant message with string content", () => { + it('converts assistant message with string content', () => { const messages: models.Message[] = [ - { role: "assistant", content: "I am doing well, thank you!" }, + { + role: 'assistant', + content: 'I am doing well, thank you!', + }, ]; const result = fromChatMessages(messages); expect(result).toEqual([ - { role: "assistant", content: "I am doing well, thank you!" }, + { + role: 'assistant', + content: 'I am doing well, thank you!', + }, ]); }); - it("converts system message with string content", () => { + it('converts system message with string content', () => { const messages: models.Message[] = [ - { role: "system", content: "You are a helpful assistant." }, + { + role: 'system', + content: 'You are a helpful assistant.', + }, ]; const result = fromChatMessages(messages); expect(result).toEqual([ - { role: "system", content: "You are a helpful assistant." }, + { + role: 'system', + content: 'You are a helpful assistant.', + }, ]); }); - it("converts developer message with string content", () => { + it('converts developer message with string content', () => { const messages: models.Message[] = [ - { role: "developer", content: "Developer instructions here." }, + { + role: 'developer', + content: 'Developer instructions here.', + }, ]; const result = fromChatMessages(messages); expect(result).toEqual([ - { role: "developer", content: "Developer instructions here." }, + { + role: 'developer', + content: 'Developer instructions here.', + }, ]); }); - it("converts multiple messages in conversation", () => { + it('converts multiple messages in conversation', () => { const messages: models.Message[] = [ - { role: "system", content: "You are helpful." }, - { role: "user", content: "Hi" }, - { role: "assistant", content: "Hello!" }, - { role: "user", content: "How are you?" }, + { + role: 'system', + content: 'You are helpful.', + }, + { + role: 'user', + content: 'Hi', + }, + { + role: 'assistant', + content: 'Hello!', + }, + { + role: 'user', + content: 'How are you?', + }, ]; const result = fromChatMessages(messages); expect(result).toEqual([ - { role: "system", content: "You are helpful." }, - { role: "user", content: "Hi" }, - { role: "assistant", content: "Hello!" }, - { role: "user", content: "How are you?" }, + { + role: 'system', + content: 'You are helpful.', + }, + { + role: 'user', + content: 'Hi', + }, + { + role: 'assistant', + content: 'Hello!', + }, + { + role: 'user', + content: 'How are you?', + }, ]); }); }); - describe("tool response message conversion", () => { - it("converts tool message to function_call_output", () => { + describe('tool response message conversion', () => { + it('converts tool message to function_call_output', () => { const messages: models.Message[] = [ { - role: "tool", - content: "The weather is sunny and 72F", - toolCallId: "call_abc123", + role: 'tool', + content: 'The weather is sunny and 72F', + toolCallId: 'call_abc123', }, ]; @@ -112,19 +161,24 @@ describe("fromChatMessages", () => { expect(result).toEqual([ { - type: "function_call_output", - callId: "call_abc123", - output: "The weather is sunny and 72F", + type: 'function_call_output', + callId: 'call_abc123', + output: 'The weather is sunny and 72F', }, ]); }); - it("converts tool message with object content by stringifying", () => { + it('converts tool message with object content by stringifying', () => { const messages: models.Message[] = [ { - role: "tool", - content: [{ type: "text", text: "Structured response" }], - toolCallId: "call_def456", + role: 'tool', + content: [ + { + type: 'text', + text: 'Structured response', + }, + ], + toolCallId: 'call_def456', }, ]; @@ -132,20 +186,30 @@ describe("fromChatMessages", () => { expect(result).toEqual([ { - type: "function_call_output", - callId: "call_def456", - output: JSON.stringify([{ type: "text", text: "Structured response" }]), + type: 'function_call_output', + callId: 'call_def456', + output: JSON.stringify([ + { + type: 'text', + text: 'Structured response', + }, + ]), }, ]); }); }); - describe("content array handling", () => { - it("stringifies array content for user messages", () => { + describe('content array handling', () => { + it('stringifies array content for user messages', () => { const messages: models.Message[] = [ { - role: "user", - content: [{ type: "text", text: "Hello from array" }], + role: 'user', + content: [ + { + type: 'text', + text: 'Hello from array', + }, + ], }, ]; @@ -153,17 +217,27 @@ describe("fromChatMessages", () => { expect(result).toEqual([ { - role: "user", - content: JSON.stringify([{ type: "text", text: "Hello from array" }]), + role: 'user', + content: JSON.stringify([ + { + type: 'text', + text: 'Hello from array', + }, + ]), }, ]); }); - it("stringifies array content for assistant messages", () => { + it('stringifies array content for assistant messages', () => { const messages: models.Message[] = [ { - role: "assistant", - content: [{ type: "text", text: "Response in array" }], + role: 'assistant', + content: [ + { + type: 'text', + text: 'Response in array', + }, + ], }, ]; @@ -171,55 +245,77 @@ describe("fromChatMessages", () => { expect(result).toEqual([ { - role: "assistant", - content: JSON.stringify([{ type: "text", text: "Response in array" }]), + role: 'assistant', + content: JSON.stringify([ + { + type: 'text', + text: 'Response in array', + }, + ]), }, ]); }); }); - describe("null and empty content handling", () => { - it("handles null content in assistant message", () => { + describe('null and empty content handling', () => { + it('handles null content in assistant message', () => { const messages: models.Message[] = [ - { role: "assistant", content: null }, + { + role: 'assistant', + content: null, + }, ]; const result = fromChatMessages(messages); - expect(result).toEqual([{ role: "assistant", content: "" }]); + expect(result).toEqual([ + { + role: 'assistant', + content: '', + }, + ]); }); - it("handles empty string content", () => { - const messages: models.Message[] = [{ role: "user", content: "" }]; + it('handles empty string content', () => { + const messages: models.Message[] = [ + { + role: 'user', + content: '', + }, + ]; const result = fromChatMessages(messages); - expect(result).toEqual([{ role: "user", content: "" }]); + expect(result).toEqual([ + { + role: 'user', + content: '', + }, + ]); }); - it("handles empty messages array", () => { + it('handles empty messages array', () => { const result = fromChatMessages([]); expect(result).toEqual([]); }); }); - }); -describe("toChatMessage", () => { - describe("basic message conversion", () => { - it("converts response with text output to AssistantMessage", () => { +describe('toChatMessage', () => { + describe('basic message conversion', () => { + it('converts response with text output to AssistantMessage', () => { const response = createMockResponse({ - id: "resp_123", + id: 'resp_123', output: [ { - id: "msg_1", - type: "message", - role: "assistant", - status: "completed", + id: 'msg_1', + type: 'message', + role: 'assistant', + status: 'completed', content: [ { - type: "output_text", - text: "Hello! How can I help you?", + type: 'output_text', + text: 'Hello! How can I help you?', annotations: [], }, ], @@ -229,31 +325,43 @@ describe("toChatMessage", () => { inputTokens: 10, outputTokens: 20, totalTokens: 30, - inputTokensDetails: { cachedTokens: 0 }, - outputTokensDetails: { reasoningTokens: 0 }, + inputTokensDetails: { + cachedTokens: 0, + }, + outputTokensDetails: { + reasoningTokens: 0, + }, }, }); const result = toChatMessage(response); expect(result).toEqual({ - role: "assistant", - content: "Hello! How can I help you?", + role: 'assistant', + content: 'Hello! How can I help you?', }); }); - it("combines multiple text parts into single content string", () => { + it('combines multiple text parts into single content string', () => { const response = createMockResponse({ - id: "resp_456", + id: 'resp_456', output: [ { - id: "msg_1", - type: "message", - role: "assistant", - status: "completed", + id: 'msg_1', + type: 'message', + role: 'assistant', + status: 'completed', content: [ - { type: "output_text", text: "Part 1. ", annotations: [] }, - { type: "output_text", text: "Part 2.", annotations: [] }, + { + type: 'output_text', + text: 'Part 1. ', + annotations: [], + }, + { + type: 'output_text', + text: 'Part 2.', + annotations: [], + }, ], }, ], @@ -261,28 +369,32 @@ describe("toChatMessage", () => { inputTokens: 5, outputTokens: 10, totalTokens: 15, - inputTokensDetails: { cachedTokens: 0 }, - outputTokensDetails: { reasoningTokens: 0 }, + inputTokensDetails: { + cachedTokens: 0, + }, + outputTokensDetails: { + reasoningTokens: 0, + }, }, }); const result = toChatMessage(response); expect(result).toEqual({ - role: "assistant", - content: "Part 1. Part 2.", + role: 'assistant', + content: 'Part 1. Part 2.', }); }); - it("returns null content when message has no text", () => { + it('returns null content when message has no text', () => { const response = createMockResponse({ - id: "resp_789", + id: 'resp_789', output: [ { - id: "msg_1", - type: "message", - role: "assistant", - status: "completed", + id: 'msg_1', + type: 'message', + role: 'assistant', + status: 'completed', content: [], }, ], @@ -290,46 +402,52 @@ describe("toChatMessage", () => { inputTokens: 5, outputTokens: 0, totalTokens: 5, - inputTokensDetails: { cachedTokens: 0 }, - outputTokensDetails: { reasoningTokens: 0 }, + inputTokensDetails: { + cachedTokens: 0, + }, + outputTokensDetails: { + reasoningTokens: 0, + }, }, }); const result = toChatMessage(response); expect(result).toEqual({ - role: "assistant", + role: 'assistant', content: null, }); }); }); - describe("error handling", () => { - it("throws error when no message found in output", () => { + describe('error handling', () => { + it('throws error when no message found in output', () => { const response = createMockResponse({ - id: "resp_err", + id: 'resp_err', output: [ { - type: "function_call", - callId: "call_1", - name: "test_tool", - arguments: "{}", - id: "fc_1", - status: "completed", + type: 'function_call', + callId: 'call_1', + name: 'test_tool', + arguments: '{}', + id: 'fc_1', + status: 'completed', }, ], usage: { inputTokens: 5, outputTokens: 10, totalTokens: 15, - inputTokensDetails: { cachedTokens: 0 }, - outputTokensDetails: { reasoningTokens: 0 }, + inputTokensDetails: { + cachedTokens: 0, + }, + outputTokensDetails: { + reasoningTokens: 0, + }, }, }); - expect(() => toChatMessage(response)).toThrow( - "No message found in response output" - ); + expect(() => toChatMessage(response)).toThrow('No message found in response output'); }); }); }); diff --git a/src/lib/chat-compat.ts b/src/lib/chat-compat.ts index d852b18a..11dda5af 100644 --- a/src/lib/chat-compat.ts +++ b/src/lib/chat-compat.ts @@ -1,45 +1,42 @@ -import type * as models from "../models/index.js"; +import type * as models from '../models/index.js'; + import { - OpenResponsesEasyInputMessageRoleUser, - OpenResponsesEasyInputMessageRoleSystem, OpenResponsesEasyInputMessageRoleAssistant, OpenResponsesEasyInputMessageRoleDeveloper, -} from "../models/openresponseseasyinputmessage.js"; -import { OpenResponsesFunctionCallOutputType } from "../models/openresponsesfunctioncalloutput.js"; -import { extractMessageFromResponse } from "./stream-transformers.js"; + OpenResponsesEasyInputMessageRoleSystem, + OpenResponsesEasyInputMessageRoleUser, +} from '../models/openresponseseasyinputmessage.js'; +import { OpenResponsesFunctionCallOutputType } from '../models/openresponsesfunctioncalloutput.js'; +import { extractMessageFromResponse } from './stream-transformers.js'; /** * Type guard for ToolResponseMessage */ -function isToolResponseMessage( - msg: models.Message -): msg is models.ToolResponseMessage { - return msg.role === "tool"; +function isToolResponseMessage(msg: models.Message): msg is models.ToolResponseMessage { + return msg.role === 'tool'; } /** * Type guard for AssistantMessage */ -function isAssistantMessage( - msg: models.Message -): msg is models.AssistantMessage { - return msg.role === "assistant"; +function isAssistantMessage(msg: models.Message): msg is models.AssistantMessage { + return msg.role === 'assistant'; } /** * Maps chat role strings to OpenResponses role types */ function mapChatRole( - role: "user" | "system" | "assistant" | "developer" + role: 'user' | 'system' | 'assistant' | 'developer', ): models.OpenResponsesEasyInputMessageRoleUnion { switch (role) { - case "user": + case 'user': return OpenResponsesEasyInputMessageRoleUser.User; - case "system": + case 'system': return OpenResponsesEasyInputMessageRoleSystem.System; - case "assistant": + case 'assistant': return OpenResponsesEasyInputMessageRoleAssistant.Assistant; - case "developer": + case 'developer': return OpenResponsesEasyInputMessageRoleDeveloper.Developer; default: { const exhaustiveCheck: never = role; @@ -53,11 +50,11 @@ function mapChatRole( * Handles string, null, undefined, and object content types. */ function contentToString(content: unknown): string { - if (typeof content === "string") { + if (typeof content === 'string') { return content; } if (content === null || content === undefined) { - return ""; + return ''; } return JSON.stringify(content); } @@ -83,15 +80,9 @@ function contentToString(content: unknown): string { * }); * ``` */ -export function fromChatMessages( - messages: models.Message[] -): models.OpenResponsesInput { +export function fromChatMessages(messages: models.Message[]): models.OpenResponsesInput { return messages.map( - ( - msg - ): - | models.OpenResponsesEasyInputMessage - | models.OpenResponsesFunctionCallOutput => { + (msg): models.OpenResponsesEasyInputMessage | models.OpenResponsesFunctionCallOutput => { if (isToolResponseMessage(msg)) { return { type: OpenResponsesFunctionCallOutputType.FunctionCallOutput, @@ -102,7 +93,7 @@ export function fromChatMessages( if (isAssistantMessage(msg)) { return { - role: mapChatRole("assistant"), + role: mapChatRole('assistant'), content: contentToString(msg.content), }; } @@ -112,7 +103,7 @@ export function fromChatMessages( role: mapChatRole(msg.role), content: contentToString(msg.content), }; - } + }, ); } diff --git a/src/lib/claude-constants.ts b/src/lib/claude-constants.ts new file mode 100644 index 00000000..222f430c --- /dev/null +++ b/src/lib/claude-constants.ts @@ -0,0 +1,24 @@ +/** + * Claude content block types used in message content arrays + */ +export const ClaudeContentBlockType = { + Text: 'text', + Image: 'image', + ToolUse: 'tool_use', + ToolResult: 'tool_result', +} as const; + +export type ClaudeContentBlockType = + (typeof ClaudeContentBlockType)[keyof typeof ClaudeContentBlockType]; + +/** + * Message roles that exist in OpenAI/Chat format but NOT in Claude format. + * Used to distinguish between the two message formats. + */ +export const NonClaudeMessageRole = { + System: 'system', + Developer: 'developer', + Tool: 'tool', +} as const; + +export type NonClaudeMessageRole = (typeof NonClaudeMessageRole)[keyof typeof NonClaudeMessageRole]; diff --git a/src/lib/claude-type-guards.ts b/src/lib/claude-type-guards.ts new file mode 100644 index 00000000..f3a9d3f7 --- /dev/null +++ b/src/lib/claude-type-guards.ts @@ -0,0 +1,109 @@ +import type * as models from '../models/index.js'; + +import { ClaudeContentBlockType, NonClaudeMessageRole } from './claude-constants.js'; + +/** + * Type guard: checks if a value is a valid object (not null, not array) + */ +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** + * Type guard: checks if a role is an OpenAI/Chat-specific role (not Claude) + */ +function isNonClaudeRole(role: unknown): boolean { + return ( + role === NonClaudeMessageRole.System || + role === NonClaudeMessageRole.Developer || + role === NonClaudeMessageRole.Tool + ); +} + +/** + * Type guard: checks if a content block is a Claude tool_result block + */ +function isClaudeToolResultBlock(block: unknown): boolean { + if (!isRecord(block)) return false; + return block['type'] === ClaudeContentBlockType.ToolResult; +} + +/** + * Type guard: checks if a content block is a Claude image block with source object + * (Claude uses 'source' object; OpenAI uses 'image_url' structure) + */ +function isClaudeImageBlockWithSource(block: unknown): boolean { + if (!isRecord(block)) return false; + return ( + block['type'] === ClaudeContentBlockType.Image && 'source' in block && isRecord(block['source']) + ); +} + +/** + * Type guard: checks if a content block is a Claude tool_use block with id + * (Claude uses 'tool_use' blocks; OpenAI uses 'tool_calls' array on message) + */ +function isClaudeToolUseBlockWithId(block: unknown): boolean { + if (!isRecord(block)) return false; + return ( + block['type'] === ClaudeContentBlockType.ToolUse && + 'id' in block && + typeof block['id'] === 'string' + ); +} + +/** + * Checks if a message's content array contains Claude-specific blocks + */ +function hasClaudeSpecificBlocks(content: unknown[]): boolean { + for (const block of content) { + if (isClaudeToolResultBlock(block)) return true; + if (isClaudeImageBlockWithSource(block)) return true; + if (isClaudeToolUseBlockWithId(block)) return true; + } + return false; +} + +/** + * Type guard: checks if input is Anthropic Claude-style messages + * + * Claude messages have only 'user' or 'assistant' roles (no 'system', 'tool', 'developer') + * and may contain Claude-specific block types in content arrays. + * + * We check for Claude-ONLY features to distinguish from OpenAI format: + * - 'tool_result' blocks (Claude-specific; OpenAI uses role: 'tool') + * - 'image' blocks with 'source' object (Claude-specific structure) + * - 'tool_use' blocks with 'id' (Claude-specific; OpenAI uses 'tool_calls' array on message) + */ +export function isClaudeStyleMessages(input: unknown): input is models.ClaudeMessageParam[] { + if (!Array.isArray(input) || input.length === 0) { + return false; + } + + for (const msg of input) { + // Skip non-object entries + if (!isRecord(msg)) continue; + + // Must have role property + if (!('role' in msg)) continue; + + // Claude messages don't have top-level 'type' field + if ('type' in msg) continue; + + // OpenAI has 'system', 'developer', 'tool' roles that Claude doesn't have + // If we see these roles, it's definitely NOT Claude format + if (isNonClaudeRole(msg['role'])) { + return false; + } + + // Check for Claude-specific content blocks + const content = msg['content']; + if (Array.isArray(content) && hasClaudeSpecificBlocks(content)) { + return true; + } + } + + // No Claude-specific features found + // Default to NOT Claude (prefer OpenAI chat format as it's more common) + return false; +} diff --git a/src/lib/config.ts b/src/lib/config.ts index 19e037b6..93a26556 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -3,20 +3,22 @@ * @generated-id: 320761608fb3 */ -import { HTTPClient } from "./http.js"; -import { Logger } from "./logger.js"; -import { RetryConfig } from "./retries.js"; -import { Params, pathToFunc } from "./url.js"; +import type { HTTPClient } from './http.js'; +import type { Logger } from './logger.js'; +import type { RetryConfig } from './retries.js'; +import type { Params } from './url.js'; + +import { pathToFunc } from './url.js'; /** * Production server */ -export const ServerProduction = "production"; +export const ServerProduction = 'production'; /** * Contains the list of servers available to the SDK */ export const ServerList = { - [ServerProduction]: "https://openrouter.ai/api/v1", + [ServerProduction]: 'https://openrouter.ai/api/v1', } as const; export type SDKOptions = { @@ -60,7 +62,7 @@ export function serverURLFromOptions(options: SDKOptions): URL | null { if (!serverURL) { const server = options.server ?? ServerProduction; - serverURL = ServerList[server] || ""; + serverURL = ServerList[server] || ''; } const u = pathToFunc(serverURL)(params); @@ -68,9 +70,9 @@ export function serverURLFromOptions(options: SDKOptions): URL | null { } export const SDK_METADATA = { - language: "typescript", - openapiDocVersion: "1.0.0", - sdkVersion: "0.3.7", - genVersion: "2.788.4", - userAgent: "speakeasy-sdk/typescript 0.3.7 2.788.4 1.0.0 @openrouter/sdk", + language: 'typescript', + openapiDocVersion: '1.0.0', + sdkVersion: '0.3.7', + genVersion: '2.788.4', + userAgent: 'speakeasy-sdk/typescript 0.3.7 2.788.4 1.0.0 @openrouter/sdk', } as const; diff --git a/src/lib/dlv.ts b/src/lib/dlv.ts index f4c75aca..29750d2f 100644 --- a/src/lib/dlv.ts +++ b/src/lib/dlv.ts @@ -45,7 +45,7 @@ export function dlv( p?: number, undef?: never, ): T | undefined { - key = Array.isArray(key) ? key : key.split("."); + key = Array.isArray(key) ? key : key.split('.'); for (p = 0; p < key.length; p++) { const k = key[p]; obj = k != null && obj ? obj[k] : undef; diff --git a/src/lib/encodings.ts b/src/lib/encodings.ts index eaa7618d..0fa6c918 100644 --- a/src/lib/encodings.ts +++ b/src/lib/encodings.ts @@ -3,48 +3,60 @@ * @generated-id: 3bd8ead98afd */ -import { bytesToBase64 } from "./base64.js"; -import { isPlainObject } from "./is-plain-object.js"; +import { bytesToBase64 } from './base64.js'; +import { isPlainObject } from './is-plain-object.js'; export class EncodingError extends Error { constructor(message: string) { super(message); - this.name = "EncodingError"; + this.name = 'EncodingError'; } } export function encodeMatrix( key: string, value: unknown, - options?: { explode?: boolean; charEncoding?: "percent" | "none" }, + options?: { + explode?: boolean; + charEncoding?: 'percent' | 'none'; + }, ): string | undefined { - let out = ""; - const pairs: [string, unknown][] = options?.explode + let out = ''; + const pairs: [ + string, + unknown, + ][] = options?.explode ? explode(key, value) - : [[key, value]]; + : [ + [ + key, + value, + ], + ]; if (pairs.every(([_, v]) => v == null)) { return; } const encodeString = (v: string) => { - return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; + return options?.charEncoding === 'percent' ? encodeURIComponent(v) : v; }; const encodeValue = (v: unknown) => encodeString(serializeValue(v)); pairs.forEach(([pk, pv]) => { - let tmp = ""; + let tmp = ''; let encValue: string | null | undefined = null; if (pv == null) { return; - } else if (Array.isArray(pv)) { - encValue = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(","); + } + if (Array.isArray(pv)) { + encValue = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(','); } else if (isPlainObject(pv)) { const mapped = mapDefinedEntries(Object.entries(pv), ([k, v]) => { return `,${encodeString(k)},${encodeValue(v)}`; }); - encValue = mapped?.join("").slice(1); + encValue = mapped?.join('').slice(1); } else { encValue = `${encodeValue(pv)}`; } @@ -74,42 +86,52 @@ export function encodeMatrix( export function encodeLabel( key: string, value: unknown, - options?: { explode?: boolean; charEncoding?: "percent" | "none" }, + options?: { + explode?: boolean; + charEncoding?: 'percent' | 'none'; + }, ): string | undefined { - let out = ""; - const pairs: [string, unknown][] = options?.explode + let out = ''; + const pairs: [ + string, + unknown, + ][] = options?.explode ? explode(key, value) - : [[key, value]]; + : [ + [ + key, + value, + ], + ]; if (pairs.every(([_, v]) => v == null)) { return; } const encodeString = (v: string) => { - return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; + return options?.charEncoding === 'percent' ? encodeURIComponent(v) : v; }; const encodeValue = (v: unknown) => encodeString(serializeValue(v)); pairs.forEach(([pk, pv]) => { - let encValue: string | null | undefined = ""; + let encValue: string | null | undefined = ''; if (pv == null) { return; - } else if (Array.isArray(pv)) { - encValue = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join("."); + } + if (Array.isArray(pv)) { + encValue = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join('.'); } else if (isPlainObject(pv)) { const mapped = mapDefinedEntries(Object.entries(pv), ([k, v]) => { return `.${encodeString(k)}.${encodeValue(v)}`; }); - encValue = mapped?.join("").slice(1); + encValue = mapped?.join('').slice(1); } else { - const k = options?.explode && isPlainObject(value) - ? `${encodeString(pk)}=` - : ""; + const k = options?.explode && isPlainObject(value) ? `${encodeString(pk)}=` : ''; encValue = `${k}${encodeValue(pv)}`; } - out += encValue == null ? "" : `.${encValue}`; + out += encValue == null ? '' : `.${encValue}`; }); return out; @@ -118,26 +140,40 @@ export function encodeLabel( type FormEncoder = ( key: string, value: unknown, - options?: { explode?: boolean; charEncoding?: "percent" | "none" }, + options?: { + explode?: boolean; + charEncoding?: 'percent' | 'none'; + }, ) => string | undefined; function formEncoder(sep: string): FormEncoder { return ( key: string, value: unknown, - options?: { explode?: boolean; charEncoding?: "percent" | "none" }, + options?: { + explode?: boolean; + charEncoding?: 'percent' | 'none'; + }, ) => { - let out = ""; - const pairs: [string, unknown][] = options?.explode + let out = ''; + const pairs: [ + string, + unknown, + ][] = options?.explode ? explode(key, value) - : [[key, value]]; + : [ + [ + key, + value, + ], + ]; if (pairs.every(([_, v]) => v == null)) { return; } const encodeString = (v: string) => { - return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; + return options?.charEncoding === 'percent' ? encodeURIComponent(v) : v; }; const encodeValue = (v: unknown) => encodeString(serializeValue(v)); @@ -145,12 +181,13 @@ function formEncoder(sep: string): FormEncoder { const encodedSep = encodeString(sep); pairs.forEach(([pk, pv]) => { - let tmp = ""; + let tmp = ''; let encValue: string | null | undefined = null; if (pv == null) { return; - } else if (Array.isArray(pv)) { + } + if (Array.isArray(pv)) { encValue = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(encodedSep); } else if (isPlainObject(pv)) { encValue = mapDefinedEntries(Object.entries(pv), ([k, v]) => { @@ -167,7 +204,7 @@ function formEncoder(sep: string): FormEncoder { tmp = `${encodeString(pk)}=${encValue}`; // If we end up with the nothing then skip forward - if (!tmp || tmp === "=") { + if (!tmp || tmp === '=') { return; } @@ -178,33 +215,45 @@ function formEncoder(sep: string): FormEncoder { }; } -export const encodeForm = formEncoder(","); -export const encodeSpaceDelimited = formEncoder(" "); -export const encodePipeDelimited = formEncoder("|"); +export const encodeForm = formEncoder(','); +export const encodeSpaceDelimited = formEncoder(' '); +export const encodePipeDelimited = formEncoder('|'); export function encodeBodyForm( key: string, value: unknown, - options?: { explode?: boolean; charEncoding?: "percent" | "none" }, + options?: { + explode?: boolean; + charEncoding?: 'percent' | 'none'; + }, ): string { - let out = ""; - const pairs: [string, unknown][] = options?.explode + let out = ''; + const pairs: [ + string, + unknown, + ][] = options?.explode ? explode(key, value) - : [[key, value]]; + : [ + [ + key, + value, + ], + ]; const encodeString = (v: string) => { - return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; + return options?.charEncoding === 'percent' ? encodeURIComponent(v) : v; }; const encodeValue = (v: unknown) => encodeString(serializeValue(v)); pairs.forEach(([pk, pv]) => { - let tmp = ""; - let encValue = ""; + let tmp = ''; + let encValue = ''; if (pv == null) { return; - } else if (Array.isArray(pv)) { + } + if (Array.isArray(pv)) { encValue = JSON.stringify(pv, jsonReplacer); } else if (isPlainObject(pv)) { encValue = JSON.stringify(pv, jsonReplacer); @@ -215,7 +264,7 @@ export function encodeBodyForm( tmp = `${encodeString(pk)}=${encValue}`; // If we end up with the nothing then skip forward - if (!tmp || tmp === "=") { + if (!tmp || tmp === '=') { return; } @@ -228,7 +277,9 @@ export function encodeBodyForm( export function encodeDeepObject( key: string, value: unknown, - options?: { charEncoding?: "percent" | "none" }, + options?: { + charEncoding?: 'percent' | 'none'; + }, ): string | undefined { if (value == null) { return; @@ -246,16 +297,18 @@ export function encodeDeepObject( export function encodeDeepObjectObject( key: string, value: unknown, - options?: { charEncoding?: "percent" | "none" }, + options?: { + charEncoding?: 'percent' | 'none'; + }, ): string | undefined { if (value == null) { return; } - let out = ""; + let out = ''; const encodeString = (v: string) => { - return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; + return options?.charEncoding === 'percent' ? encodeURIComponent(v) : v; }; if (!isPlainObject(value)) { @@ -272,17 +325,21 @@ export function encodeDeepObjectObject( if (isPlainObject(cv)) { const objOut = encodeDeepObjectObject(pk, cv, options); - out += objOut == null ? "" : `&${objOut}`; + out += objOut == null ? '' : `&${objOut}`; return; } - const pairs: unknown[] = Array.isArray(cv) ? cv : [cv]; + const pairs: unknown[] = Array.isArray(cv) + ? cv + : [ + cv, + ]; const encoded = mapDefined(pairs, (v) => { return `${encodeString(pk)}=${encodeString(serializeValue(v))}`; - })?.join("&"); + })?.join('&'); - out += encoded == null ? "" : `&${encoded}`; + out += encoded == null ? '' : `&${encoded}`; }); return out.slice(1); @@ -291,14 +348,17 @@ export function encodeDeepObjectObject( export function encodeJSON( key: string, value: unknown, - options?: { explode?: boolean; charEncoding?: "percent" | "none" }, + options?: { + explode?: boolean; + charEncoding?: 'percent' | 'none'; + }, ): string | undefined { - if (typeof value === "undefined") { + if (typeof value === 'undefined') { return; } const encodeString = (v: string) => { - return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; + return options?.charEncoding === 'percent' ? encodeURIComponent(v) : v; }; const encVal = encodeString(JSON.stringify(value, jsonReplacer)); @@ -309,64 +369,96 @@ export function encodeJSON( export const encodeSimple = ( key: string, value: unknown, - options?: { explode?: boolean; charEncoding?: "percent" | "none" }, + options?: { + explode?: boolean; + charEncoding?: 'percent' | 'none'; + }, ): string | undefined => { - let out = ""; - const pairs: [string, unknown][] = options?.explode + let out = ''; + const pairs: [ + string, + unknown, + ][] = options?.explode ? explode(key, value) - : [[key, value]]; + : [ + [ + key, + value, + ], + ]; if (pairs.every(([_, v]) => v == null)) { return; } const encodeString = (v: string) => { - return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; + return options?.charEncoding === 'percent' ? encodeURIComponent(v) : v; }; const encodeValue = (v: unknown) => encodeString(serializeValue(v)); pairs.forEach(([pk, pv]) => { - let tmp: string | null | undefined = ""; + let tmp: string | null | undefined = ''; if (pv == null) { return; - } else if (Array.isArray(pv)) { - tmp = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(","); + } + if (Array.isArray(pv)) { + tmp = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(','); } else if (isPlainObject(pv)) { const mapped = mapDefinedEntries(Object.entries(pv), ([k, v]) => { return `,${encodeString(k)},${encodeValue(v)}`; }); - tmp = mapped?.join("").slice(1); + tmp = mapped?.join('').slice(1); } else { - const k = options?.explode && isPlainObject(value) ? `${pk}=` : ""; + const k = options?.explode && isPlainObject(value) ? `${pk}=` : ''; tmp = `${k}${encodeValue(pv)}`; } - out += tmp ? `,${tmp}` : ""; + out += tmp ? `,${tmp}` : ''; }); return out.slice(1); }; -function explode(key: string, value: unknown): [string, unknown][] { +function explode( + key: string, + value: unknown, +): [ + string, + unknown, +][] { if (Array.isArray(value)) { - return value.map((v) => [key, v]); - } else if (isPlainObject(value)) { + return value.map((v) => [ + key, + v, + ]); + } + if (isPlainObject(value)) { const o = value ?? {}; - return Object.entries(o).map(([k, v]) => [k, v]); - } else { - return [[key, value]]; + return Object.entries(o).map(([k, v]) => [ + k, + v, + ]); } + return [ + [ + key, + value, + ], + ]; } function serializeValue(value: unknown): string { if (value == null) { - return ""; - } else if (value instanceof Date) { + return ''; + } + if (value instanceof Date) { return value.toISOString(); - } else if (value instanceof Uint8Array) { + } + if (value instanceof Uint8Array) { return bytesToBase64(value); - } else if (typeof value === "object") { + } + if (typeof value === 'object') { return JSON.stringify(value, jsonReplacer); } @@ -376,9 +468,8 @@ function serializeValue(value: unknown): string { function jsonReplacer(_: string, value: unknown): unknown { if (value instanceof Uint8Array) { return bytesToBase64(value); - } else { - return value; } + return value; } function mapDefined(inp: T[], mapper: (v: T) => R): R[] | null { @@ -401,8 +492,18 @@ function mapDefined(inp: T[], mapper: (v: T) => R): R[] | null { } function mapDefinedEntries( - inp: Iterable<[K, V]>, - mapper: (v: [K, V]) => R, + inp: Iterable< + [ + K, + V, + ] + >, + mapper: ( + v: [ + K, + V, + ], + ) => R, ): R[] | null { const acc: R[] = []; for (const [k, v] of inp) { @@ -410,7 +511,10 @@ function mapDefinedEntries( continue; } - const m = mapper([k, v]); + const m = mapper([ + k, + v, + ]); if (m == null) { continue; } @@ -422,12 +526,12 @@ function mapDefinedEntries( } export function queryJoin(...args: (string | undefined)[]): string { - return args.filter(Boolean).join("&"); + return args.filter(Boolean).join('&'); } type QueryEncoderOptions = { explode?: boolean; - charEncoding?: "percent" | "none"; + charEncoding?: 'percent' | 'none'; allowEmptyValue?: string[]; }; @@ -437,20 +541,14 @@ type QueryEncoder = ( options?: QueryEncoderOptions, ) => string | undefined; -type BulkQueryEncoder = ( - values: Record, - options?: QueryEncoderOptions, -) => string; +type BulkQueryEncoder = (values: Record, options?: QueryEncoderOptions) => string; export function queryEncoder(f: QueryEncoder): BulkQueryEncoder { - const bulkEncode = function( - values: Record, - options?: QueryEncoderOptions, - ): string { + const bulkEncode = (values: Record, options?: QueryEncoderOptions): string => { const opts: QueryEncoderOptions = { ...options, explode: options?.explode ?? true, - charEncoding: options?.charEncoding ?? "percent", + charEncoding: options?.charEncoding ?? 'percent', }; const allowEmptySet = new Set(options?.allowEmptyValue ?? []); @@ -458,10 +556,10 @@ export function queryEncoder(f: QueryEncoder): BulkQueryEncoder { const encoded = Object.entries(values).map(([key, value]) => { if (allowEmptySet.has(key)) { if ( - value === undefined - || value === null - || value === "" - || (Array.isArray(value) && value.length === 0) + value === undefined || + value === null || + value === '' || + (Array.isArray(value) && value.length === 0) ) { return `${encodeURIComponent(key)}=`; } @@ -480,15 +578,11 @@ export const encodeSpaceDelimitedQuery = queryEncoder(encodeSpaceDelimited); export const encodePipeDelimitedQuery = queryEncoder(encodePipeDelimited); export const encodeDeepObjectQuery = queryEncoder(encodeDeepObject); -export function appendForm( - fd: FormData, - key: string, - value: unknown, - fileName?: string, -): void { +export function appendForm(fd: FormData, key: string, value: unknown, fileName?: string): void { if (value == null) { return; - } else if (value instanceof Blob && fileName) { + } + if (value instanceof Blob && fileName) { fd.append(key, value, fileName); } else if (value instanceof Blob) { fd.append(key, value); diff --git a/src/lib/env.ts b/src/lib/env.ts index 88ff8a65..1b97f509 100644 --- a/src/lib/env.ts +++ b/src/lib/env.ts @@ -3,9 +3,10 @@ * @generated-id: c52972a3b198 */ -import * as z from "zod/v4"; -import { SDKOptions } from "./config.js"; -import { dlv } from "./dlv.js"; +import type { SDKOptions } from './config.js'; + +import * as z from 'zod/v4'; +import { dlv } from './dlv.js'; export interface Env { OPENROUTER_API_KEY?: string | undefined; @@ -37,14 +38,14 @@ export const envSchema: z.ZodType = z.object({ * @returns {boolean} True if the runtime is Deno, false otherwise. */ function isDeno() { - if ("Deno" in globalThis) { + if ('Deno' in globalThis) { return true; } return false; } -let envMemo: Env | undefined = undefined; +let envMemo: Env | undefined; /** * Reads and validates environment variables. */ @@ -57,7 +58,7 @@ export function env(): Env { if (isDeno()) { envObject = (globalThis as any).Deno?.env?.toObject?.() ?? {}; } else { - envObject = dlv(globalThis, "process.env") ?? {}; + envObject = dlv(globalThis, 'process.env') ?? {}; } envMemo = envSchema.parse(envObject); @@ -75,14 +76,16 @@ export function resetEnv() { * Populates global parameters with environment variables. */ export function fillGlobals(options: SDKOptions): SDKOptions { - const clone = { ...options }; + const clone = { + ...options, + }; const envVars = env(); - if (typeof envVars.OPENROUTER_HTTP_REFERER !== "undefined") { + if (typeof envVars.OPENROUTER_HTTP_REFERER !== 'undefined') { clone.httpReferer ??= envVars.OPENROUTER_HTTP_REFERER; } - if (typeof envVars.OPENROUTER_X_TITLE !== "undefined") { + if (typeof envVars.OPENROUTER_X_TITLE !== 'undefined') { clone.xTitle ??= envVars.OPENROUTER_X_TITLE; } diff --git a/src/lib/event-streams.ts b/src/lib/event-streams.ts index d649d979..e1c627b2 100644 --- a/src/lib/event-streams.ts +++ b/src/lib/event-streams.ts @@ -32,7 +32,7 @@ export class EventStream extends ReadableStream { const item = parseMessage(message, parse); if (item && !item.done) return downstream.enqueue(item.value); if (item?.done) { - await upstream.cancel("done"); + await upstream.cancel('done'); return downstream.close(); } } @@ -41,33 +41,45 @@ export class EventStream extends ReadableStream { await upstream.cancel(e); } }, - cancel: reason => upstream.cancel(reason), + cancel: (reason) => upstream.cancel(reason), }); } // Polyfill for older browsers [Symbol.asyncIterator](): AsyncIterableIterator { const fn = (ReadableStream.prototype as any)[Symbol.asyncIterator]; - if (typeof fn === "function") return fn.call(this); + if (typeof fn === 'function') return fn.call(this); const reader = this.getReader(); return { next: async () => { const r = await reader.read(); if (r.done) { reader.releaseLock(); - return { done: true, value: undefined }; + return { + done: true, + value: undefined, + }; } - return { done: false, value: r.value }; + return { + done: false, + value: r.value, + }; }, throw: async (e) => { await reader.cancel(e); reader.releaseLock(); - return { done: true, value: undefined }; + return { + done: true, + value: undefined, + }; }, return: async () => { - await reader.cancel("done"); + await reader.cancel('done'); reader.releaseLock(); - return { done: true, value: undefined }; + return { + done: true, + value: undefined, + }; }, [Symbol.asyncIterator]() { return this; @@ -84,23 +96,35 @@ function concatBuffer(a: Uint8Array, b: Uint8Array): Uint8Array { } /** Finds the first (CR,LF,CR,LF) or (CR,CR) or (LF,LF) */ -function findBoundary( - buf: Uint8Array, -): { index: number; length: number } | null { +function findBoundary(buf: Uint8Array): { + index: number; + length: number; +} | null { const len = buf.length; for (let i = 0; i < len; i++) { if ( - i <= len - 4 - && buf[i] === 13 && buf[i + 1] === 10 && buf[i + 2] === 13 - && buf[i + 3] === 10 + i <= len - 4 && + buf[i] === 13 && + buf[i + 1] === 10 && + buf[i + 2] === 13 && + buf[i + 3] === 10 ) { - return { index: i, length: 4 }; + return { + index: i, + length: 4, + }; } if (i <= len - 2 && buf[i] === 13 && buf[i + 1] === 13) { - return { index: i, length: 2 }; + return { + index: i, + length: 2, + }; } if (i <= len - 2 && buf[i] === 10 && buf[i + 1] === 10) { - return { index: i, length: 2 }; + return { + index: i, + length: 2, + }; } } return null; @@ -115,20 +139,20 @@ function parseMessage( const ret: SseMessage = {}; let ignore = true; for (const line of lines) { - if (!line || line.startsWith(":")) continue; + if (!line || line.startsWith(':')) continue; ignore = false; - const i = line.indexOf(":"); + const i = line.indexOf(':'); const field = line.slice(0, i); - const value = line[i + 1] === " " ? line.slice(i + 2) : line.slice(i + 1); - if (field === "data") dataLines.push(value); - else if (field === "event") ret.event = value; - else if (field === "id") ret.id = value; - else if (field === "retry") { + const value = line[i + 1] === ' ' ? line.slice(i + 2) : line.slice(i + 1); + if (field === 'data') dataLines.push(value); + else if (field === 'event') ret.event = value; + else if (field === 'id') ret.id = value; + else if (field === 'retry') { const n = Number(value); if (!isNaN(n)) ret.retry = n; } } if (ignore) return; - if (dataLines.length) ret.data = dataLines.join("\n"); + if (dataLines.length) ret.data = dataLines.join('\n'); return parse(ret); } diff --git a/src/lib/files.ts b/src/lib/files.ts index 457f4ced..7d50ad0a 100644 --- a/src/lib/files.ts +++ b/src/lib/files.ts @@ -47,36 +47,36 @@ export async function readableStreamToArrayBuffer( export function getContentTypeFromFileName(fileName: string): string | null { if (!fileName) return null; - const ext = fileName.toLowerCase().split(".").pop(); + const ext = fileName.toLowerCase().split('.').pop(); if (!ext) return null; const mimeTypes: Record = { - json: "application/json", - xml: "application/xml", - html: "text/html", - htm: "text/html", - txt: "text/plain", - csv: "text/csv", - pdf: "application/pdf", - png: "image/png", - jpg: "image/jpeg", - jpeg: "image/jpeg", - gif: "image/gif", - svg: "image/svg+xml", - js: "application/javascript", - css: "text/css", - zip: "application/zip", - tar: "application/x-tar", - gz: "application/gzip", - mp4: "video/mp4", - mp3: "audio/mpeg", - wav: "audio/wav", - webp: "image/webp", - ico: "image/x-icon", - woff: "font/woff", - woff2: "font/woff2", - ttf: "font/ttf", - otf: "font/otf", + json: 'application/json', + xml: 'application/xml', + html: 'text/html', + htm: 'text/html', + txt: 'text/plain', + csv: 'text/csv', + pdf: 'application/pdf', + png: 'image/png', + jpg: 'image/jpeg', + jpeg: 'image/jpeg', + gif: 'image/gif', + svg: 'image/svg+xml', + js: 'application/javascript', + css: 'text/css', + zip: 'application/zip', + tar: 'application/x-tar', + gz: 'application/gzip', + mp4: 'video/mp4', + mp3: 'audio/mpeg', + wav: 'audio/wav', + webp: 'image/webp', + ico: 'image/x-icon', + woff: 'font/woff', + woff2: 'font/woff2', + ttf: 'font/ttf', + otf: 'font/otf', }; return mimeTypes[ext] || null; diff --git a/src/lib/http.ts b/src/lib/http.ts index 326ee1a0..384c937e 100644 --- a/src/lib/http.ts +++ b/src/lib/http.ts @@ -3,10 +3,7 @@ * @generated-id: 63a80782d37e */ -export type Fetcher = ( - input: RequestInfo | URL, - init?: RequestInit, -) => Promise; +export type Fetcher = (input: RequestInfo | URL, init?: RequestInit) => Promise; export type Awaitable = T | Promise; @@ -17,9 +14,8 @@ const DEFAULT_FETCHER: Fetcher = (input, init) => { // therefore needed for interop with Bun. if (init == null) { return fetch(input); - } else { - return fetch(input, init); } + return fetch(input, init); }; export type RequestInput = { @@ -82,28 +78,37 @@ export class HTTPClient { * can mutate the request or return a new request. This may be useful to add * additional information to request such as request IDs and tracing headers. */ - addHook(hook: "beforeRequest", fn: BeforeRequestHook): this; + addHook(hook: 'beforeRequest', fn: BeforeRequestHook): this; /** * Registers a hook that is called when a request cannot be made due to a * network error. */ - addHook(hook: "requestError", fn: RequestErrorHook): this; + addHook(hook: 'requestError', fn: RequestErrorHook): this; /** * Registers a hook that is called when a response has been received from the * server. */ - addHook(hook: "response", fn: ResponseHook): this; + addHook(hook: 'response', fn: ResponseHook): this; addHook( ...args: - | [hook: "beforeRequest", fn: BeforeRequestHook] - | [hook: "requestError", fn: RequestErrorHook] - | [hook: "response", fn: ResponseHook] + | [ + hook: 'beforeRequest', + fn: BeforeRequestHook, + ] + | [ + hook: 'requestError', + fn: RequestErrorHook, + ] + | [ + hook: 'response', + fn: ResponseHook, + ] ) { - if (args[0] === "beforeRequest") { + if (args[0] === 'beforeRequest') { this.requestHooks.push(args[1]); - } else if (args[0] === "requestError") { + } else if (args[0] === 'requestError') { this.requestErrorHooks.push(args[1]); - } else if (args[0] === "response") { + } else if (args[0] === 'response') { this.responseHooks.push(args[1]); } else { throw new Error(`Invalid hook type: ${args[0]}`); @@ -112,23 +117,32 @@ export class HTTPClient { } /** Removes a hook that was previously registered with `addHook`. */ - removeHook(hook: "beforeRequest", fn: BeforeRequestHook): this; + removeHook(hook: 'beforeRequest', fn: BeforeRequestHook): this; /** Removes a hook that was previously registered with `addHook`. */ - removeHook(hook: "requestError", fn: RequestErrorHook): this; + removeHook(hook: 'requestError', fn: RequestErrorHook): this; /** Removes a hook that was previously registered with `addHook`. */ - removeHook(hook: "response", fn: ResponseHook): this; + removeHook(hook: 'response', fn: ResponseHook): this; removeHook( ...args: - | [hook: "beforeRequest", fn: BeforeRequestHook] - | [hook: "requestError", fn: RequestErrorHook] - | [hook: "response", fn: ResponseHook] + | [ + hook: 'beforeRequest', + fn: BeforeRequestHook, + ] + | [ + hook: 'requestError', + fn: RequestErrorHook, + ] + | [ + hook: 'response', + fn: ResponseHook, + ] ): this { let target: unknown[]; - if (args[0] === "beforeRequest") { + if (args[0] === 'beforeRequest') { target = this.requestHooks; - } else if (args[0] === "requestError") { + } else if (args[0] === 'requestError') { target = this.requestErrorHooks; - } else if (args[0] === "response") { + } else if (args[0] === 'response') { target = this.responseHooks; } else { throw new Error(`Invalid hook type: ${args[0]}`); @@ -160,31 +174,30 @@ const mediaParamSeparator = /\s*;\s*/g; export function matchContentType(response: Response, pattern: string): boolean { // `*` is a special case which means anything is acceptable. - if (pattern === "*") { + if (pattern === '*') { return true; } - let contentType = - response.headers.get("content-type")?.trim() || "application/octet-stream"; + let contentType = response.headers.get('content-type')?.trim() || 'application/octet-stream'; contentType = contentType.toLowerCase(); const wantParts = pattern.toLowerCase().trim().split(mediaParamSeparator); - const [wantType = "", ...wantParams] = wantParts; + const [wantType = '', ...wantParams] = wantParts; - if (wantType.split("/").length !== 2) { + if (wantType.split('/').length !== 2) { return false; } const gotParts = contentType.split(mediaParamSeparator); - const [gotType = "", ...gotParams] = gotParts; + const [gotType = '', ...gotParams] = gotParts; - const [type = "", subtype = ""] = gotType.split("/"); + const [type = '', subtype = ''] = gotType.split('/'); if (!type || !subtype) { return false; } if ( - wantType !== "*/*" && + wantType !== '*/*' && gotType !== wantType && `${type}/*` !== wantType && `*/${subtype}` !== wantType @@ -206,14 +219,15 @@ export function matchContentType(response: Response, pattern: string): boolean { return true; } -const codeRangeRE = new RegExp("^[0-9]xx$", "i"); +const codeRangeRE = /^[0-9]xx$/i; -export function matchStatusCode( - response: Response, - codes: StatusCodePredicate, -): boolean { +export function matchStatusCode(response: Response, codes: StatusCodePredicate): boolean { const actual = `${response.status}`; - const expectedCodes = Array.isArray(codes) ? codes : [codes]; + const expectedCodes = Array.isArray(codes) + ? codes + : [ + codes, + ]; if (!expectedCodes.length) { return false; } @@ -221,7 +235,7 @@ export function matchStatusCode( return expectedCodes.some((ec) => { const code = `${ec}`; - if (code === "default") { + if (code === 'default') { return true; } @@ -231,7 +245,7 @@ export function matchStatusCode( const expectFamily = code.charAt(0); if (!expectFamily) { - throw new Error("Invalid status code range"); + throw new Error('Invalid status code range'); } const actualFamily = actual.charAt(0); @@ -248,35 +262,28 @@ export function matchResponse( code: StatusCodePredicate, contentTypePattern: string, ): boolean { - return ( - matchStatusCode(response, code) && - matchContentType(response, contentTypePattern) - ); + return matchStatusCode(response, code) && matchContentType(response, contentTypePattern); } /** * Uses various heurisitics to determine if an error is a connection error. */ export function isConnectionError(err: unknown): boolean { - if (typeof err !== "object" || err == null) { + if (typeof err !== 'object' || err == null) { return false; } // Covers fetch in Deno as well const isBrowserErr = - err instanceof TypeError && - err.message.toLowerCase().startsWith("failed to fetch"); + err instanceof TypeError && err.message.toLowerCase().startsWith('failed to fetch'); const isNodeErr = - err instanceof TypeError && - err.message.toLowerCase().startsWith("fetch failed"); + err instanceof TypeError && err.message.toLowerCase().startsWith('fetch failed'); - const isBunErr = "name" in err && err.name === "ConnectionError"; + const isBunErr = 'name' in err && err.name === 'ConnectionError'; const isGenericErr = - "code" in err && - typeof err.code === "string" && - err.code.toLowerCase() === "econnreset"; + 'code' in err && typeof err.code === 'string' && err.code.toLowerCase() === 'econnreset'; return isBrowserErr || isNodeErr || isGenericErr || isBunErr; } @@ -285,19 +292,17 @@ export function isConnectionError(err: unknown): boolean { * Uses various heurisitics to determine if an error is a timeout error. */ export function isTimeoutError(err: unknown): boolean { - if (typeof err !== "object" || err == null) { + if (typeof err !== 'object' || err == null) { return false; } // Fetch in browser, Node.js, Bun, Deno - const isNative = "name" in err && err.name === "TimeoutError"; - const isLegacyNative = "code" in err && err.code === 23; + const isNative = 'name' in err && err.name === 'TimeoutError'; + const isLegacyNative = 'code' in err && err.code === 23; // Node.js HTTP client and Axios const isGenericErr = - "code" in err && - typeof err.code === "string" && - err.code.toLowerCase() === "econnaborted"; + 'code' in err && typeof err.code === 'string' && err.code.toLowerCase() === 'econnaborted'; return isNative || isLegacyNative || isGenericErr; } @@ -306,19 +311,17 @@ export function isTimeoutError(err: unknown): boolean { * Uses various heurisitics to determine if an error is a abort error. */ export function isAbortError(err: unknown): boolean { - if (typeof err !== "object" || err == null) { + if (typeof err !== 'object' || err == null) { return false; } // Fetch in browser, Node.js, Bun, Deno - const isNative = "name" in err && err.name === "AbortError"; - const isLegacyNative = "code" in err && err.code === 20; + const isNative = 'name' in err && err.name === 'AbortError'; + const isLegacyNative = 'code' in err && err.code === 20; // Node.js HTTP client and Axios const isGenericErr = - "code" in err && - typeof err.code === "string" && - err.code.toLowerCase() === "econnaborted"; + 'code' in err && typeof err.code === 'string' && err.code.toLowerCase() === 'econnaborted'; return isNative || isLegacyNative || isGenericErr; } diff --git a/src/lib/is-plain-object.ts b/src/lib/is-plain-object.ts index 096b49bf..6a188d2a 100644 --- a/src/lib/is-plain-object.ts +++ b/src/lib/is-plain-object.ts @@ -29,7 +29,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // Taken from https://github.com/sindresorhus/is-plain-obj/blob/97f38e8836f86a642cce98fc6ab3058bc36df181/index.js export function isPlainObject(value: unknown): value is object { - if (typeof value !== "object" || value === null) { + if (typeof value !== 'object' || value === null) { return false; } diff --git a/src/lib/matchers.ts b/src/lib/matchers.ts index 8acbcebd..35d02498 100644 --- a/src/lib/matchers.ts +++ b/src/lib/matchers.ts @@ -3,34 +3,31 @@ * @generated-id: d54b2253b719 */ -import { OpenRouterDefaultError } from "../models/errors/openrouterdefaulterror.js"; -import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; -import { ERR, OK, Result } from "../types/fp.js"; -import { matchResponse, matchStatusCode, StatusCodePredicate } from "./http.js"; -import { isPlainObject } from "./is-plain-object.js"; +import type { Result } from '../types/fp.js'; +import type { StatusCodePredicate } from './http.js'; -export type Encoding = - | "jsonl" - | "json" - | "text" - | "bytes" - | "stream" - | "sse" - | "nil" - | "fail"; +import { OpenRouterDefaultError } from '../models/errors/openrouterdefaulterror.js'; +import { ResponseValidationError } from '../models/errors/responsevalidationerror.js'; +import { ERR, OK } from '../types/fp.js'; +import { matchResponse, matchStatusCode } from './http.js'; +import { isPlainObject } from './is-plain-object.js'; + +export type Encoding = 'jsonl' | 'json' | 'text' | 'bytes' | 'stream' | 'sse' | 'nil' | 'fail'; const DEFAULT_CONTENT_TYPES: Record = { - jsonl: "application/jsonl", - json: "application/json", - text: "text/plain", - bytes: "application/octet-stream", - stream: "application/octet-stream", - sse: "text/event-stream", - nil: "*", - fail: "*", + jsonl: 'application/jsonl', + json: 'application/json', + text: 'text/plain', + bytes: 'application/octet-stream', + stream: 'application/octet-stream', + sse: 'text/event-stream', + nil: '*', + fail: '*', }; -type Schema = { parse(raw: unknown): T }; +type Schema = { + parse(raw: unknown): T; +}; type MatchOptions = { ctype?: string; @@ -53,7 +50,7 @@ export type ErrorMatcher = MatchOptions & { }; export type FailMatcher = { - enc: "fail"; + enc: 'fail'; codes: StatusCodePredicate; }; @@ -64,14 +61,25 @@ export function jsonErr( schema: Schema, options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "json", codes, schema }; + return { + ...options, + err: true, + enc: 'json', + codes, + schema, + }; } export function json( codes: StatusCodePredicate, schema: Schema, options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "json", codes, schema }; + return { + ...options, + enc: 'json', + codes, + schema, + }; } export function jsonl( @@ -79,7 +87,12 @@ export function jsonl( schema: Schema, options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "jsonl", codes, schema }; + return { + ...options, + enc: 'jsonl', + codes, + schema, + }; } export function jsonlErr( @@ -87,21 +100,38 @@ export function jsonlErr( schema: Schema, options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "jsonl", codes, schema }; + return { + ...options, + err: true, + enc: 'jsonl', + codes, + schema, + }; } export function textErr( codes: StatusCodePredicate, schema: Schema, options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "text", codes, schema }; + return { + ...options, + err: true, + enc: 'text', + codes, + schema, + }; } export function text( codes: StatusCodePredicate, schema: Schema, options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "text", codes, schema }; + return { + ...options, + enc: 'text', + codes, + schema, + }; } export function bytesErr( @@ -109,14 +139,25 @@ export function bytesErr( schema: Schema, options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "bytes", codes, schema }; + return { + ...options, + err: true, + enc: 'bytes', + codes, + schema, + }; } export function bytes( codes: StatusCodePredicate, schema: Schema, options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "bytes", codes, schema }; + return { + ...options, + enc: 'bytes', + codes, + schema, + }; } export function streamErr( @@ -124,14 +165,25 @@ export function streamErr( schema: Schema, options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "stream", codes, schema }; + return { + ...options, + err: true, + enc: 'stream', + codes, + schema, + }; } export function stream( codes: StatusCodePredicate, schema: Schema, options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "stream", codes, schema }; + return { + ...options, + enc: 'stream', + codes, + schema, + }; } export function sseErr( @@ -139,14 +191,25 @@ export function sseErr( schema: Schema, options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "sse", codes, schema }; + return { + ...options, + err: true, + enc: 'sse', + codes, + schema, + }; } export function sse( codes: StatusCodePredicate, schema: Schema, options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "sse", codes, schema }; + return { + ...options, + enc: 'sse', + codes, + schema, + }; } export function nilErr( @@ -154,31 +217,49 @@ export function nilErr( schema: Schema, options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "nil", codes, schema }; + return { + ...options, + err: true, + enc: 'nil', + codes, + schema, + }; } export function nil( codes: StatusCodePredicate, schema: Schema, options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "nil", codes, schema }; + return { + ...options, + enc: 'nil', + codes, + schema, + }; } export function fail(codes: StatusCodePredicate): FailMatcher { - return { enc: "fail", codes }; + return { + enc: 'fail', + codes, + }; } -export type MatchedValue = Matchers extends Matcher[] - ? T - : never; -export type MatchedError = Matchers extends Matcher[] - ? E - : never; +export type MatchedValue = Matchers extends Matcher[] ? T : never; +export type MatchedError = Matchers extends Matcher[] ? E : never; export type MatchFunc = ( response: Response, request: Request, - options?: { resultKey?: string; extraFields?: Record }, -) => Promise<[result: Result, raw: unknown]>; + options?: { + resultKey?: string; + extraFields?: Record; + }, +) => Promise< + [ + result: Result, + raw: unknown, + ] +>; export function match( ...matchers: Array> @@ -186,7 +267,10 @@ export function match( return async function matchFunc( response: Response, request: Request, - options?: { resultKey?: string; extraFields?: Record }, + options?: { + resultKey?: string; + extraFields?: Record; + }, ): Promise< [ result: Result, @@ -197,57 +281,59 @@ export function match( let matcher: Matcher | undefined; for (const match of matchers) { const { codes } = match; - const ctpattern = "ctype" in match - ? match.ctype - : DEFAULT_CONTENT_TYPES[match.enc]; + const ctpattern = 'ctype' in match ? match.ctype : DEFAULT_CONTENT_TYPES[match.enc]; if (ctpattern && matchResponse(response, codes, ctpattern)) { matcher = match; break; - } else if (!ctpattern && matchStatusCode(response, codes)) { + } + if (!ctpattern && matchStatusCode(response, codes)) { matcher = match; break; } } if (!matcher) { - return [{ - ok: false, - error: new OpenRouterDefaultError("Unexpected Status or Content-Type", { - response, - request, - body: await response.text().catch(() => ""), - }), - }, raw]; + return [ + { + ok: false, + error: new OpenRouterDefaultError('Unexpected Status or Content-Type', { + response, + request, + body: await response.text().catch(() => ''), + }), + }, + raw, + ]; } const encoding = matcher.enc; - let body = ""; + let body = ''; switch (encoding) { - case "json": + case 'json': body = await response.text(); raw = JSON.parse(body); break; - case "jsonl": + case 'jsonl': raw = response.body; break; - case "bytes": + case 'bytes': raw = new Uint8Array(await response.arrayBuffer()); break; - case "stream": + case 'stream': raw = response.body; break; - case "text": + case 'text': body = await response.text(); raw = body; break; - case "sse": + case 'sse': raw = response.body; break; - case "nil": + case 'nil': body = await response.text(); raw = undefined; break; - case "fail": + case 'fail': body = await response.text(); raw = body; break; @@ -256,24 +342,31 @@ export function match( throw new Error(`Unsupported response type: ${encoding}`); } - if (matcher.enc === "fail") { - return [{ - ok: false, - error: new OpenRouterDefaultError("API error occurred", { - request, - response, - body, - }), - }, raw]; + if (matcher.enc === 'fail') { + return [ + { + ok: false, + error: new OpenRouterDefaultError('API error occurred', { + request, + response, + body, + }), + }, + raw, + ]; } const resultKey = matcher.key || options?.resultKey; let data: unknown; - if ("err" in matcher) { + if ('err' in matcher) { data = { ...options?.extraFields, - ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), + ...(matcher.hdrs + ? { + Headers: unpackHeaders(response.headers), + } + : null), ...(isPlainObject(raw) ? raw : null), request$: request, response$: response, @@ -282,38 +375,61 @@ export function match( } else if (resultKey) { data = { ...options?.extraFields, - ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), + ...(matcher.hdrs + ? { + Headers: unpackHeaders(response.headers), + } + : null), [resultKey]: raw, }; } else if (matcher.hdrs) { data = { ...options?.extraFields, - ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), + ...(matcher.hdrs + ? { + Headers: unpackHeaders(response.headers), + } + : null), ...(isPlainObject(raw) ? raw : null), }; } else { data = raw; } - if ("err" in matcher) { + if ('err' in matcher) { const result = safeParseResponse( data, (v: unknown) => matcher.schema.parse(v), - "Response validation failed", - { request, response, body }, + 'Response validation failed', + { + request, + response, + body, + }, ); - return [result.ok ? { ok: false, error: result.value } : result, raw]; - } else { return [ - safeParseResponse( - data, - (v: unknown) => matcher.schema.parse(v), - "Response validation failed", - { request, response, body }, - ), + result.ok + ? { + ok: false, + error: result.value, + } + : result, raw, ]; } + return [ + safeParseResponse( + data, + (v: unknown) => matcher.schema.parse(v), + 'Response validation failed', + { + request, + response, + body, + }, + ), + raw, + ]; }; } @@ -336,7 +452,11 @@ function safeParseResponse( rawValue: Inp, fn: (value: Inp) => Out, errorMessage: string, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ): Result { try { return OK(fn(rawValue)); diff --git a/src/lib/model-result.ts b/src/lib/model-result.ts index 8d19f5a1..f274e6a9 100644 --- a/src/lib/model-result.ts +++ b/src/lib/model-result.ts @@ -1,19 +1,19 @@ -import type { OpenRouterCore } from "../core.js"; -import type * as models from "../models/index.js"; -import type { EventStream } from "./event-streams.js"; -import type { RequestOptions } from "./sdks.js"; +import type { OpenRouterCore } from '../core.js'; +import type * as models from '../models/index.js'; +import type { EventStream } from './event-streams.js'; +import type { RequestOptions } from './sdks.js'; import type { ChatStreamEvent, EnhancedResponseStreamEvent, - Tool, MaxToolRounds, ParsedToolCall, + Tool, ToolStreamEvent, TurnContext, -} from "./tool-types.js"; +} from './tool-types.js'; -import { betaResponsesSend } from "../funcs/betaResponsesSend.js"; -import { ReusableReadableStream } from "./reusable-stream.js"; +import { betaResponsesSend } from '../funcs/betaResponsesSend.js'; +import { ReusableReadableStream } from './reusable-stream.js'; import { buildResponsesMessageStream, buildToolCallStream, @@ -24,22 +24,23 @@ import { extractTextFromResponse, extractToolCallsFromResponse, extractToolDeltas, -} from "./stream-transformers.js"; -import { executeTool } from "./tool-executor.js"; -import { hasExecuteFunction } from "./tool-types.js"; +} from './stream-transformers.js'; +import { executeTool } from './tool-executor.js'; +import { hasExecuteFunction } from './tool-types.js'; /** * Type guard for stream event with toReadableStream method */ -function isEventStream( - value: unknown -): value is EventStream { +function isEventStream(value: unknown): value is EventStream { return ( value !== null && - typeof value === "object" && - "toReadableStream" in value && - typeof (value as { toReadableStream: unknown }).toReadableStream === - "function" + typeof value === 'object' && + 'toReadableStream' in value && + typeof ( + value as { + toReadableStream: unknown; + } + ).toReadableStream === 'function' ); } @@ -47,31 +48,35 @@ function isEventStream( * Type guard for response.output_text.delta events */ function isOutputTextDeltaEvent( - event: models.OpenResponsesStreamEvent + event: models.OpenResponsesStreamEvent, ): event is models.OpenResponsesStreamEventResponseOutputTextDelta { - return "type" in event && event.type === "response.output_text.delta"; + return 'type' in event && event.type === 'response.output_text.delta'; } /** * Type guard for response.completed events */ function isResponseCompletedEvent( - event: models.OpenResponsesStreamEvent + event: models.OpenResponsesStreamEvent, ): event is models.OpenResponsesStreamEventResponseCompleted { - return "type" in event && event.type === "response.completed"; + return 'type' in event && event.type === 'response.completed'; } /** * Type guard for output items with a type property */ -function hasTypeProperty( - item: unknown -): item is { type: string } { +function hasTypeProperty(item: unknown): item is { + type: string; +} { return ( - typeof item === "object" && + typeof item === 'object' && item !== null && - "type" in item && - typeof (item as { type: unknown }).type === "string" + 'type' in item && + typeof ( + item as { + type: unknown; + } + ).type === 'string' ); } @@ -101,11 +106,8 @@ export interface GetResponseOptions { * ReusableReadableStream implementation. */ export class ModelResult { - private reusableStream: ReusableReadableStream | null = - null; - private streamPromise: Promise< - EventStream - > | null = null; + private reusableStream: ReusableReadableStream | null = null; + private streamPromise: Promise> | null = null; private textPromise: Promise | null = null; private options: GetResponseOptions; private initPromise: Promise | null = null; @@ -126,15 +128,15 @@ export class ModelResult { * Type guard to check if a value is a non-streaming response */ private isNonStreamingResponse( - value: unknown + value: unknown, ): value is models.OpenResponsesNonStreamingResponse { return ( value !== null && - typeof value === "object" && - "id" in value && - "object" in value && - "output" in value && - !("toReadableStream" in value) + typeof value === 'object' && + 'id' in value && + 'object' in value && + 'output' in value && + !('toReadableStream' in value) ); } @@ -158,7 +160,7 @@ export class ModelResult { this.streamPromise = betaResponsesSend( this.options.client, request, - this.options.options + this.options.options, ).then((result) => { if (!result.ok) { throw result.error; @@ -187,20 +189,18 @@ export class ModelResult { await this.initStream(); if (!this.reusableStream) { - throw new Error("Stream not initialized"); + throw new Error('Stream not initialized'); } // Get the initial response - const initialResponse = await consumeStreamForCompletion( - this.reusableStream - ); + const initialResponse = await consumeStreamForCompletion(this.reusableStream); // Check if we have tools and if auto-execution is enabled const shouldAutoExecute = this.options.tools && this.options.tools.length > 0 && initialResponse.output.some( - (item) => hasTypeProperty(item) && item.type === "function_call" + (item) => hasTypeProperty(item) && item.type === 'function_call', ); if (!shouldAutoExecute) { @@ -214,9 +214,7 @@ export class ModelResult { // Check if any have execute functions const executableTools = toolCalls.filter((toolCall) => { - const tool = this.options.tools?.find( - (t) => t.function.name === toolCall.name - ); + const tool = this.options.tools?.find((t) => t.function.name === toolCall.name); return tool && hasExecuteFunction(tool); }); @@ -231,8 +229,7 @@ export class ModelResult { let currentResponse = initialResponse; let currentRound = 0; - let currentInput: models.OpenResponsesInput = - this.options.request.input || []; + let currentInput: models.OpenResponsesInput = this.options.request.input || []; while (true) { const currentToolCalls = extractToolCallsFromResponse(currentResponse); @@ -242,9 +239,7 @@ export class ModelResult { } const hasExecutable = currentToolCalls.some((toolCall) => { - const tool = this.options.tools?.find( - (t) => t.function.name === toolCall.name - ); + const tool = this.options.tools?.find((t) => t.function.name === toolCall.name); return tool && hasExecuteFunction(tool); }); @@ -253,11 +248,11 @@ export class ModelResult { } // Check if we should continue based on maxToolRounds - if (typeof maxToolRounds === "number") { + if (typeof maxToolRounds === 'number') { if (currentRound >= maxToolRounds) { break; } - } else if (typeof maxToolRounds === "function") { + } else if (typeof maxToolRounds === 'function') { // Function signature: (context: TurnContext) => boolean const turnContext: TurnContext = { numberOfTurns: currentRound + 1, @@ -298,9 +293,7 @@ export class ModelResult { const toolResults: Array = []; for (const toolCall of currentToolCalls) { - const tool = this.options.tools?.find( - (t) => t.function.name === toolCall.name - ); + const tool = this.options.tools?.find((t) => t.function.name === toolCall.name); if (!tool || !hasExecuteFunction(tool)) { continue; @@ -309,15 +302,12 @@ export class ModelResult { const result = await executeTool(tool, toolCall, turnContext); // Store preliminary results - if ( - result.preliminaryResults && - result.preliminaryResults.length > 0 - ) { + if (result.preliminaryResults && result.preliminaryResults.length > 0) { this.preliminaryResults.set(toolCall.id, result.preliminaryResults); } toolResults.push({ - type: "function_call_output" as const, + type: 'function_call_output' as const, id: `output_${toolCall.id}`, callId: toolCall.id, output: result.error @@ -333,7 +323,9 @@ export class ModelResult { const newInput: models.OpenResponsesInput = [ ...(Array.isArray(currentResponse.output) ? currentResponse.output - : [currentResponse.output]), + : [ + currentResponse.output, + ]), ...toolResults, ]; @@ -350,7 +342,7 @@ export class ModelResult { const newResult = await betaResponsesSend( this.options.client, newRequest, - this.options.options + this.options.options, ); if (!newResult.ok) { @@ -366,7 +358,7 @@ export class ModelResult { } else if (this.isNonStreamingResponse(value)) { currentResponse = value; } else { - throw new Error("Unexpected response type from API"); + throw new Error('Unexpected response type from API'); } currentRound++; @@ -374,15 +366,12 @@ export class ModelResult { // Validate the final response has required fields if (!currentResponse || !currentResponse.id || !currentResponse.output) { - throw new Error("Invalid final response: missing required fields"); + throw new Error('Invalid final response: missing required fields'); } // Ensure the response is in a completed state (has output content) - if ( - !Array.isArray(currentResponse.output) || - currentResponse.output.length === 0 - ) { - throw new Error("Invalid final response: empty or invalid output"); + if (!Array.isArray(currentResponse.output) || currentResponse.output.length === 0) { + throw new Error('Invalid final response: empty or invalid output'); } this.finalResponse = currentResponse; @@ -398,7 +387,7 @@ export class ModelResult { await this.executeToolsIfNeeded(); if (!this.finalResponse) { - throw new Error("Response not available"); + throw new Error('Response not available'); } return extractTextFromResponse(this.finalResponse); @@ -426,7 +415,7 @@ export class ModelResult { await this.executeToolsIfNeeded(); if (!this.finalResponse) { - throw new Error("Response not available"); + throw new Error('Response not available'); } return this.finalResponse; @@ -441,7 +430,7 @@ export class ModelResult { return async function* (this: ModelResult) { await this.initStream(); if (!this.reusableStream) { - throw new Error("Stream not initialized"); + throw new Error('Stream not initialized'); } const consumer = this.reusableStream.createConsumer(); @@ -458,7 +447,7 @@ export class ModelResult { for (const [toolCallId, results] of this.preliminaryResults) { for (const result of results) { yield { - type: "tool.preliminary_result" as const, + type: 'tool.preliminary_result' as const, toolCallId, result, timestamp: Date.now(), @@ -476,7 +465,7 @@ export class ModelResult { return async function* (this: ModelResult) { await this.initStream(); if (!this.reusableStream) { - throw new Error("Stream not initialized"); + throw new Error('Stream not initialized'); } yield* extractTextDeltas(this.reusableStream); @@ -495,7 +484,7 @@ export class ModelResult { return async function* (this: ModelResult) { await this.initStream(); if (!this.reusableStream) { - throw new Error("Stream not initialized"); + throw new Error('Stream not initialized'); } // First yield messages from the stream in responses format @@ -508,9 +497,7 @@ export class ModelResult { for (const round of this.allToolExecutionRounds) { for (const toolCall of round.toolCalls) { // Find the tool to check if it was executed - const tool = this.options.tools?.find( - (t) => t.function.name === toolCall.name - ); + const tool = this.options.tools?.find((t) => t.function.name === toolCall.name); if (!tool || !hasExecuteFunction(tool)) { continue; } @@ -524,10 +511,10 @@ export class ModelResult { // Yield function call output in responses format yield { - type: "function_call_output" as const, + type: 'function_call_output' as const, id: `output_${toolCall.id}`, callId: toolCall.id, - output: result !== undefined ? JSON.stringify(result) : "", + output: result !== undefined ? JSON.stringify(result) : '', } as models.OpenResponsesFunctionCallOutput; } } @@ -536,7 +523,7 @@ export class ModelResult { if (this.finalResponse && this.allToolExecutionRounds.length > 0) { // Check if the final response contains a message const hasMessage = this.finalResponse.output.some( - (item) => hasTypeProperty(item) && item.type === "message" + (item) => hasTypeProperty(item) && item.type === 'message', ); if (hasMessage) { yield extractResponsesMessageFromResponse(this.finalResponse); @@ -553,7 +540,7 @@ export class ModelResult { return async function* (this: ModelResult) { await this.initStream(); if (!this.reusableStream) { - throw new Error("Stream not initialized"); + throw new Error('Stream not initialized'); } yield* extractReasoningDeltas(this.reusableStream); @@ -570,13 +557,13 @@ export class ModelResult { return async function* (this: ModelResult) { await this.initStream(); if (!this.reusableStream) { - throw new Error("Stream not initialized"); + throw new Error('Stream not initialized'); } // Yield tool deltas as structured events for await (const delta of extractToolDeltas(this.reusableStream)) { yield { - type: "delta" as const, + type: 'delta' as const, content: delta, }; } @@ -588,7 +575,7 @@ export class ModelResult { for (const [toolCallId, results] of this.preliminaryResults) { for (const result of results) { yield { - type: "preliminary_result" as const, + type: 'preliminary_result' as const, toolCallId, result, }; @@ -611,25 +598,25 @@ export class ModelResult { return async function* (this: ModelResult) { await this.initStream(); if (!this.reusableStream) { - throw new Error("Stream not initialized"); + throw new Error('Stream not initialized'); } const consumer = this.reusableStream.createConsumer(); for await (const event of consumer) { - if (!("type" in event)) { + if (!('type' in event)) { continue; } // Transform responses events to chat-like format using type guards if (isOutputTextDeltaEvent(event)) { yield { - type: "content.delta" as const, + type: 'content.delta' as const, delta: event.delta, }; } else if (isResponseCompletedEvent(event)) { yield { - type: "message.complete" as const, + type: 'message.complete' as const, response: event.response, }; } else { @@ -648,7 +635,7 @@ export class ModelResult { for (const [toolCallId, results] of this.preliminaryResults) { for (const result of results) { yield { - type: "tool.preliminary_result" as const, + type: 'tool.preliminary_result' as const, toolCallId, result, }; @@ -666,12 +653,10 @@ export class ModelResult { async getToolCalls(): Promise { await this.initStream(); if (!this.reusableStream) { - throw new Error("Stream not initialized"); + throw new Error('Stream not initialized'); } - const completedResponse = await consumeStreamForCompletion( - this.reusableStream - ); + const completedResponse = await consumeStreamForCompletion(this.reusableStream); return extractToolCallsFromResponse(completedResponse); } @@ -683,7 +668,7 @@ export class ModelResult { return async function* (this: ModelResult) { await this.initStream(); if (!this.reusableStream) { - throw new Error("Stream not initialized"); + throw new Error('Stream not initialized'); } yield* buildToolCallStream(this.reusableStream); diff --git a/src/lib/primitives.ts b/src/lib/primitives.ts index bdff1670..1eca929e 100644 --- a/src/lib/primitives.ts +++ b/src/lib/primitives.ts @@ -6,14 +6,11 @@ class InvariantError extends Error { constructor(message: string) { super(message); - this.name = "InvariantError"; + this.name = 'InvariantError'; } } -export function invariant( - condition: unknown, - message: string, -): asserts condition { +export function invariant(condition: unknown, message: string): asserts condition { if (!condition) { throw new InvariantError(message); } @@ -27,8 +24,8 @@ export type Remap = { [k in keyof Inp as Mapping[k] extends string /* if we have a string mapping for this key then use it */ ? Mapping[k] : Mapping[k] extends null /* if the mapping is to `null` then drop the key */ - ? never - : k /* otherwise keep the key as-is */]: Inp[k]; + ? never + : k /* otherwise keep the key as-is */]: Inp[k]; }; /** @@ -75,7 +72,7 @@ export function combineSignals( case 1: return filtered[0] || null; default: - if ("any" in AbortSignal && typeof AbortSignal.any === "function") { + if ('any' in AbortSignal && typeof AbortSignal.any === 'function') { return AbortSignal.any(filtered); } return abortSignalAny(filtered); @@ -109,26 +106,24 @@ export function abortSignalAny(signals: AbortSignal[]): AbortSignal { for (const signalRef of signalRefs) { const signal = signalRef.deref(); if (signal) { - signal.removeEventListener("abort", abort); + signal.removeEventListener('abort', abort); } } } for (const signal of signals) { signalRefs.push(new WeakRef(signal)); - signal.addEventListener("abort", abort); + signal.addEventListener('abort', abort); } return result; } -export function compactMap( - values: Record, -): Record { +export function compactMap(values: Record): Record { const out: Record = {}; for (const [k, v] of Object.entries(values)) { - if (typeof v !== "undefined") { + if (typeof v !== 'undefined') { out[k] = v; } } diff --git a/src/lib/retries.ts b/src/lib/retries.ts index 0059a5eb..7f5155c4 100644 --- a/src/lib/retries.ts +++ b/src/lib/retries.ts @@ -3,7 +3,7 @@ * @generated-id: b24a69d15639 */ -import { isConnectionError, isTimeoutError } from "./http.js"; +import { isConnectionError, isTimeoutError } from './http.js'; export type BackoffStrategy = { initialInterval: number; @@ -20,9 +20,11 @@ const defaultBackoff: BackoffStrategy = { }; export type RetryConfig = - | { strategy: "none" } | { - strategy: "backoff"; + strategy: 'none'; + } + | { + strategy: 'backoff'; backoff?: BackoffStrategy; retryConnectionErrors?: boolean; }; @@ -35,17 +37,22 @@ export class PermanentError extends Error { /** The underlying cause of the error. */ override readonly cause: unknown; - constructor(message: string, options?: { cause?: unknown }) { + constructor( + message: string, + options?: { + cause?: unknown; + }, + ) { let msg = message; if (options?.cause) { msg += `: ${options.cause}`; } super(msg, options); - this.name = "PermanentError"; + this.name = 'PermanentError'; // In older runtimes, the cause field would not have been assigned through // the super() call. - if (typeof this.cause === "undefined") { + if (typeof this.cause === 'undefined') { this.cause = options?.cause; } @@ -64,7 +71,7 @@ export class TemporaryError extends Error { constructor(message: string, response: Response) { super(message); this.response = response; - this.name = "TemporaryError"; + this.name = 'TemporaryError'; Object.setPrototypeOf(this, TemporaryError.prototype); } @@ -78,7 +85,7 @@ export async function retry( }, ): Promise { switch (options.config.strategy) { - case "backoff": + case 'backoff': return retryBackoff( wrapFetcher(fetchFn, { statusCodes: options.statusCodes, @@ -102,10 +109,7 @@ function wrapFetcher( try { const res = await fn(); if (isRetryableResponse(res, options.statusCodes)) { - throw new TemporaryError( - "Response failed with retryable status code", - res, - ); + throw new TemporaryError('Response failed with retryable status code', res); } return res; @@ -114,19 +118,18 @@ function wrapFetcher( throw err; } - if ( - options.retryConnectionErrors && - (isTimeoutError(err) || isConnectionError(err)) - ) { + if (options.retryConnectionErrors && (isTimeoutError(err) || isConnectionError(err))) { throw err; } - throw new PermanentError("Permanent error", { cause: err }); + throw new PermanentError('Permanent error', { + cause: err, + }); } }; } -const codeRangeRE = new RegExp("^[0-9]xx$", "i"); +const codeRangeRE = /^[0-9]xx$/i; function isRetryableResponse(res: Response, statusCodes: string[]): boolean { const actual = `${res.status}`; @@ -138,7 +141,7 @@ function isRetryableResponse(res: Response, statusCodes: string[]): boolean { const expectFamily = code.charAt(0); if (!expectFamily) { - throw new Error("Invalid status code range"); + throw new Error('Invalid status code range'); } const actualFamily = actual.charAt(0); @@ -182,8 +185,7 @@ async function retryBackoff( } if (retryInterval <= 0) { - retryInterval = - initialInterval * Math.pow(x, exponent) + Math.random() * 1000; + retryInterval = initialInterval * x ** exponent + Math.random() * 1000; } const d = Math.min(retryInterval, maxInterval); @@ -195,7 +197,7 @@ async function retryBackoff( } function retryIntervalFromResponse(res: Response): number { - const retryVal = res.headers.get("retry-after") || ""; + const retryVal = res.headers.get('retry-after') || ''; if (!retryVal) { return 0; } diff --git a/src/lib/schemas.ts b/src/lib/schemas.ts index 35b0fb3e..07256928 100644 --- a/src/lib/schemas.ts +++ b/src/lib/schemas.ts @@ -3,20 +3,18 @@ * @generated-id: deb4b531fae1 */ -import * as z from "zod/v4"; -import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; -import { ERR, OK, Result } from "../types/fp.js"; +import type { Result } from '../types/fp.js'; + +import * as z from 'zod/v4'; +import { SDKValidationError } from '../models/errors/sdkvalidationerror.js'; +import { ERR, OK } from '../types/fp.js'; /** * Utility function that executes some code which may throw a ZodError. It * intercepts this error and converts it to an SDKValidationError so as to not * leak Zod implementation details to user code. */ -export function parse( - rawValue: Inp, - fn: (value: Inp) => Out, - errorMessage: string, -): Out { +export function parse(rawValue: Inp, fn: (value: Inp) => Out, errorMessage: string): Out { try { return fn(rawValue); } catch (err) { @@ -56,13 +54,14 @@ export function collectExtraKeys< ): z.ZodPipe< z.ZodObject>, z.ZodTransform< - & z.output> - & (Optional extends false ? { - [k in K]: Record>; - } - : { - [k in K]?: Record> | undefined; - }), + z.output> & + (Optional extends false + ? { + [k in K]: Record>; + } + : { + [k in K]?: Record> | undefined; + }), z.output>> > > { @@ -75,7 +74,7 @@ export function collectExtraKeys< } const v = val[key]; - if (typeof v === "undefined") { + if (typeof v === 'undefined') { continue; } @@ -87,6 +86,9 @@ export function collectExtraKeys< return val; } - return { ...val, [extrasKey]: extras }; + return { + ...val, + [extrasKey]: extras, + }; }); } diff --git a/src/lib/sdks.ts b/src/lib/sdks.ts index 89074c11..8ea30eda 100644 --- a/src/lib/sdks.ts +++ b/src/lib/sdks.ts @@ -3,20 +3,26 @@ * @generated-id: 8a6d91f1218d */ -import { SDKHooks } from "../hooks/hooks.js"; -import { HookContext } from "../hooks/types.js"; +import type { HookContext } from '../hooks/types.js'; +import type { Result } from '../types/fp.js'; +import type { SDKOptions } from './config.js'; +import type { Logger } from './logger.js'; +import type { RetryConfig } from './retries.js'; +import type { SecurityState } from './security.js'; + +import { SDKHooks } from '../hooks/hooks.js'; import { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError, -} from "../models/errors/httpclienterrors.js"; -import { ERR, OK, Result } from "../types/fp.js"; -import { stringToBase64 } from "./base64.js"; -import { SDK_METADATA, SDKOptions, serverURLFromOptions } from "./config.js"; -import { encodeForm } from "./encodings.js"; -import { env, fillGlobals } from "./env.js"; +} from '../models/errors/httpclienterrors.js'; +import { ERR, OK } from '../types/fp.js'; +import { stringToBase64 } from './base64.js'; +import { SDK_METADATA, serverURLFromOptions } from './config.js'; +import { encodeForm } from './encodings.js'; +import { env, fillGlobals } from './env.js'; import { HTTPClient, isAbortError, @@ -24,10 +30,8 @@ import { isTimeoutError, matchContentType, matchStatusCode, -} from "./http.js"; -import { Logger } from "./logger.js"; -import { retry, RetryConfig } from "./retries.js"; -import { SecurityState } from "./security.js"; +} from './http.js'; +import { retry } from './retries.js'; export type RequestOptions = { /** @@ -54,15 +58,15 @@ export type RequestOptions = { * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options|Request} */ - fetchOptions?: Omit; -} & Omit; + fetchOptions?: Omit; +} & Omit; type RequestConfig = { method: string; path: string; baseURL?: string | URL | undefined; query?: string; - body?: RequestInit["body"]; + body?: RequestInit['body']; headers?: HeadersInit; security?: SecurityState | null; uaHeader?: string; @@ -70,30 +74,29 @@ type RequestConfig = { timeoutMs?: number; }; -const gt: unknown = typeof globalThis === "undefined" ? null : globalThis; -const webWorkerLike = typeof gt === "object" - && gt != null - && "importScripts" in gt - && typeof gt["importScripts"] === "function"; -const isBrowserLike = webWorkerLike - || (typeof navigator !== "undefined" && "serviceWorker" in navigator) - || (typeof window === "object" && typeof window.document !== "undefined"); +const gt: unknown = typeof globalThis === 'undefined' ? null : globalThis; +const webWorkerLike = + typeof gt === 'object' && + gt != null && + 'importScripts' in gt && + typeof gt['importScripts'] === 'function'; +const isBrowserLike = + webWorkerLike || + (typeof navigator !== 'undefined' && 'serviceWorker' in navigator) || + (typeof window === 'object' && typeof window.document !== 'undefined'); export class ClientSDK { readonly #httpClient: HTTPClient; readonly #hooks: SDKHooks; readonly #logger?: Logger | undefined; public readonly _baseURL: URL | null; - public readonly _options: SDKOptions & { hooks?: SDKHooks }; + public readonly _options: SDKOptions & { + hooks?: SDKHooks; + }; constructor(options: SDKOptions = {}) { const opt = options as unknown; - if ( - typeof opt === "object" - && opt != null - && "hooks" in opt - && opt.hooks instanceof SDKHooks - ) { + if (typeof opt === 'object' && opt != null && 'hooks' in opt && opt.hooks instanceof SDKHooks) { this.#hooks = opt.hooks; } else { this.#hooks = new SDKHooks(); @@ -104,12 +107,15 @@ export class ClientSDK { const url = serverURLFromOptions(options); if (url) { - url.pathname = url.pathname.replace(/\/+$/, "") + "/"; + url.pathname = url.pathname.replace(/\/+$/, '') + '/'; } this._baseURL = url; this.#httpClient = options.httpClient || defaultHttpClient; - this._options = { ...fillGlobals(options), hooks: this.#hooks }; + this._options = { + ...fillGlobals(options), + hooks: this.#hooks, + }; this.#logger = this._options.debugLogger; if (!this.#logger && env().OPENROUTER_DEBUG) { @@ -126,31 +132,33 @@ export class ClientSDK { const base = conf.baseURL ?? this._baseURL; if (!base) { - return ERR(new InvalidRequestError("No base URL provided for operation")); + return ERR(new InvalidRequestError('No base URL provided for operation')); } const reqURL = new URL(base); const inputURL = new URL(path, reqURL); if (path) { - reqURL.pathname += reqURL.pathname.endsWith("/") ? "" : "/"; - reqURL.pathname += inputURL.pathname.replace(/^\/+/, ""); + reqURL.pathname += reqURL.pathname.endsWith('/') ? '' : '/'; + reqURL.pathname += inputURL.pathname.replace(/^\/+/, ''); } - let finalQuery = query || ""; + let finalQuery = query || ''; const secQuery: string[] = []; for (const [k, v] of Object.entries(security?.queryParams || {})) { - const q = encodeForm(k, v, { charEncoding: "percent" }); - if (typeof q !== "undefined") { + const q = encodeForm(k, v, { + charEncoding: 'percent', + }); + if (typeof q !== 'undefined') { secQuery.push(q); } } if (secQuery.length) { - finalQuery += `&${secQuery.join("&")}`; + finalQuery += `&${secQuery.join('&')}`; } if (finalQuery) { - const q = finalQuery.startsWith("&") ? finalQuery.slice(1) : finalQuery; + const q = finalQuery.startsWith('&') ? finalQuery.slice(1) : finalQuery; reqURL.search = `?${q}`; } @@ -160,9 +168,12 @@ export class ClientSDK { const password = security?.basic.password; if (username != null || password != null) { const encoded = stringToBase64( - [username || "", password || ""].join(":"), + [ + username || '', + password || '', + ].join(':'), ); - headers.set("Authorization", `Basic ${encoded}`); + headers.set('Authorization', `Basic ${encoded}`); } const securityHeaders = new Headers(security?.headers || {}); @@ -170,16 +181,14 @@ export class ClientSDK { headers.set(k, v); } - let cookie = headers.get("cookie") || ""; + let cookie = headers.get('cookie') || ''; for (const [k, v] of Object.entries(security?.cookies || {})) { cookie += `; ${k}=${v}`; } - cookie = cookie.startsWith("; ") ? cookie.slice(2) : cookie; - headers.set("cookie", cookie); + cookie = cookie.startsWith('; ') ? cookie.slice(2) : cookie; + headers.set('cookie', cookie); - const userHeaders = new Headers( - options?.headers ?? options?.fetchOptions?.headers, - ); + const userHeaders = new Headers(options?.headers ?? options?.fetchOptions?.headers); for (const [k, v] of userHeaders) { headers.set(k, v); } @@ -187,13 +196,10 @@ export class ClientSDK { // Only set user agent header in non-browser-like environments since CORS // policy disallows setting it in browsers e.g. Chrome throws an error. if (!isBrowserLike) { - headers.set( - conf.uaHeader ?? "user-agent", - conf.userAgent ?? SDK_METADATA.userAgent, - ); + headers.set(conf.uaHeader ?? 'user-agent', conf.userAgent ?? SDK_METADATA.userAgent); } - const fetchOptions: Omit = { + const fetchOptions: Omit = { ...options?.fetchOptions, ...options, }; @@ -203,7 +209,9 @@ export class ClientSDK { } if (conf.body instanceof ReadableStream) { - Object.assign(fetchOptions, { duplex: "half" }); + Object.assign(fetchOptions, { + duplex: 'half', + }); } let input; @@ -219,7 +227,7 @@ export class ClientSDK { }); } catch (err: unknown) { return ERR( - new UnexpectedClientError("Create request hook failed to execute", { + new UnexpectedClientError('Create request hook failed to execute', { cause: err, }), ); @@ -239,10 +247,7 @@ export class ClientSDK { ): Promise< Result< Response, - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - | UnexpectedClientError + RequestAbortedError | RequestTimeoutError | ConnectionError | UnexpectedClientError > > { const { context, errorCodes } = options; @@ -251,18 +256,14 @@ export class ClientSDK { async () => { const req = await this.#hooks.beforeRequest(context, request.clone()); await logRequest(this.#logger, req).catch((e) => - this.#logger?.log("Failed to log request:", e) + this.#logger?.log('Failed to log request:', e), ); let response = await this.#httpClient.request(req); try { if (matchStatusCode(response, errorCodes)) { - const result = await this.#hooks.afterError( - context, - response, - null, - ); + const result = await this.#hooks.afterError(context, response, null); if (result.error) { throw result.error; } @@ -271,34 +272,42 @@ export class ClientSDK { response = await this.#hooks.afterSuccess(context, response); } } finally { - await logResponse(this.#logger, response, req) - .catch(e => this.#logger?.log("Failed to log response:", e)); + await logResponse(this.#logger, response, req).catch((e) => + this.#logger?.log('Failed to log response:', e), + ); } return response; }, - { config: options.retryConfig, statusCodes: options.retryCodes }, + { + config: options.retryConfig, + statusCodes: options.retryCodes, + }, ).then( (r) => OK(r), (err) => { switch (true) { case isAbortError(err): return ERR( - new RequestAbortedError("Request aborted by client", { + new RequestAbortedError('Request aborted by client', { cause: err, }), ); case isTimeoutError(err): return ERR( - new RequestTimeoutError("Request timed out", { cause: err }), + new RequestTimeoutError('Request timed out', { + cause: err, + }), ); case isConnectionError(err): return ERR( - new ConnectionError("Unable to make request", { cause: err }), + new ConnectionError('Unable to make request', { + cause: err, + }), ); default: return ERR( - new UnexpectedClientError("Unexpected HTTP client error", { + new UnexpectedClientError('Unexpected HTTP client error', { cause: err, }), ); @@ -309,36 +318,35 @@ export class ClientSDK { } const jsonLikeContentTypeRE = /(application|text)\/.*?\+*json.*/; -const jsonlLikeContentTypeRE = - /(application|text)\/(.*?\+*\bjsonl\b.*|.*?\+*\bx-ndjson\b.*)/; +const jsonlLikeContentTypeRE = /(application|text)\/(.*?\+*\bjsonl\b.*|.*?\+*\bx-ndjson\b.*)/; async function logRequest(logger: Logger | undefined, req: Request) { if (!logger) { return; } - const contentType = req.headers.get("content-type"); - const ct = contentType?.split(";")[0] || ""; + const contentType = req.headers.get('content-type'); + const ct = contentType?.split(';')[0] || ''; logger.group(`> Request: ${req.method} ${req.url}`); - logger.group("Headers:"); + logger.group('Headers:'); for (const [k, v] of req.headers.entries()) { logger.log(`${k}: ${v}`); } logger.groupEnd(); - logger.group("Body:"); + logger.group('Body:'); switch (true) { case jsonLikeContentTypeRE.test(ct): logger.log(await req.clone().json()); break; - case ct.startsWith("text/"): + case ct.startsWith('text/'): logger.log(await req.clone().text()); break; - case ct === "multipart/form-data": { + case ct === 'multipart/form-data': { const body = await req.clone().formData(); for (const [k, v] of body) { - const vlabel = v instanceof Blob ? "" : v; + const vlabel = v instanceof Blob ? '' : v; logger.log(`${k}: ${vlabel}`); } break; @@ -352,47 +360,42 @@ async function logRequest(logger: Logger | undefined, req: Request) { logger.groupEnd(); } -async function logResponse( - logger: Logger | undefined, - res: Response, - req: Request, -) { +async function logResponse(logger: Logger | undefined, res: Response, req: Request) { if (!logger) { return; } - const contentType = res.headers.get("content-type"); - const ct = contentType?.split(";")[0] || ""; + const contentType = res.headers.get('content-type'); + const ct = contentType?.split(';')[0] || ''; logger.group(`< Response: ${req.method} ${req.url}`); - logger.log("Status Code:", res.status, res.statusText); + logger.log('Status Code:', res.status, res.statusText); - logger.group("Headers:"); + logger.group('Headers:'); for (const [k, v] of res.headers.entries()) { logger.log(`${k}: ${v}`); } logger.groupEnd(); - logger.group("Body:"); + logger.group('Body:'); switch (true) { - case matchContentType(res, "application/json") - || jsonLikeContentTypeRE.test(ct) && !jsonlLikeContentTypeRE.test(ct): + case matchContentType(res, 'application/json') || + (jsonLikeContentTypeRE.test(ct) && !jsonlLikeContentTypeRE.test(ct)): logger.log(await res.clone().json()); break; - case matchContentType(res, "application/jsonl") - || jsonlLikeContentTypeRE.test(ct): + case matchContentType(res, 'application/jsonl') || jsonlLikeContentTypeRE.test(ct): logger.log(await res.clone().text()); break; - case matchContentType(res, "text/event-stream"): + case matchContentType(res, 'text/event-stream'): logger.log(`<${contentType}>`); break; - case matchContentType(res, "text/*"): + case matchContentType(res, 'text/*'): logger.log(await res.clone().text()); break; - case matchContentType(res, "multipart/form-data"): { + case matchContentType(res, 'multipart/form-data'): { const body = await res.clone().formData(); for (const [k, v] of body) { - const vlabel = v instanceof Blob ? "" : v; + const vlabel = v instanceof Blob ? '' : v; logger.log(`${k}: ${vlabel}`); } break; diff --git a/src/lib/security.ts b/src/lib/security.ts index 93be85a2..e05eca56 100644 --- a/src/lib/security.ts +++ b/src/lib/security.ts @@ -3,8 +3,9 @@ * @generated-id: 0502afa7922e */ -import * as models from "../models/index.js"; -import { env } from "./env.js"; +import type * as models from '../models/index.js'; + +import { env } from './env.js'; type OAuth2PasswordFlow = { username: string; @@ -15,8 +16,8 @@ type OAuth2PasswordFlow = { }; export enum SecurityErrorCode { - Incomplete = "incomplete", - UnrecognisedSecurityType = "unrecognized_security_type", + Incomplete = 'incomplete', + UnrecognisedSecurityType = 'unrecognized_security_type', } export class SecurityError extends Error { @@ -25,13 +26,13 @@ export class SecurityError extends Error { message: string, ) { super(message); - this.name = "SecurityError"; + this.name = 'SecurityError'; } static incomplete(): SecurityError { return new SecurityError( SecurityErrorCode.Incomplete, - "Security requirements not met in order to perform the operation", + 'Security requirements not met in order to perform the operation', ); } static unrecognizedType(type: string): SecurityError { @@ -43,52 +44,64 @@ export class SecurityError extends Error { } export type SecurityState = { - basic: { username?: string | undefined; password?: string | undefined }; + basic: { + username?: string | undefined; + password?: string | undefined; + }; headers: Record; queryParams: Record; cookies: Record; - oauth2: ({ type: "password" } & OAuth2PasswordFlow) | { type: "none" }; + oauth2: + | ({ + type: 'password'; + } & OAuth2PasswordFlow) + | { + type: 'none'; + }; }; type SecurityInputBasic = { - type: "http:basic"; + type: 'http:basic'; value: - | { username?: string | undefined; password?: string | undefined } + | { + username?: string | undefined; + password?: string | undefined; + } | null | undefined; }; type SecurityInputBearer = { - type: "http:bearer"; + type: 'http:bearer'; value: string | null | undefined; fieldName: string; }; type SecurityInputAPIKey = { - type: "apiKey:header" | "apiKey:query" | "apiKey:cookie"; + type: 'apiKey:header' | 'apiKey:query' | 'apiKey:cookie'; value: string | null | undefined; fieldName: string; }; type SecurityInputOIDC = { - type: "openIdConnect"; + type: 'openIdConnect'; value: string | null | undefined; fieldName: string; }; type SecurityInputOAuth2 = { - type: "oauth2"; + type: 'oauth2'; value: string | null | undefined; fieldName: string; }; type SecurityInputOAuth2ClientCredentials = { - type: "oauth2:client_credentials"; + type: 'oauth2:client_credentials'; value: | { - clientID?: string | undefined; - clientSecret?: string | undefined; - } + clientID?: string | undefined; + clientSecret?: string | undefined; + } | null | string | undefined; @@ -96,16 +109,13 @@ type SecurityInputOAuth2ClientCredentials = { }; type SecurityInputOAuth2PasswordCredentials = { - type: "oauth2:password"; - value: - | string - | null - | undefined; + type: 'oauth2:password'; + value: string | null | undefined; fieldName?: string; }; type SecurityInputCustom = { - type: "http:custom"; + type: 'http:custom'; value: any | null | undefined; fieldName?: string; }; @@ -120,42 +130,41 @@ export type SecurityInput = | SecurityInputOIDC | SecurityInputCustom; -export function resolveSecurity( - ...options: SecurityInput[][] -): SecurityState | null { +export function resolveSecurity(...options: SecurityInput[][]): SecurityState | null { const state: SecurityState = { basic: {}, headers: {}, queryParams: {}, cookies: {}, - oauth2: { type: "none" }, + oauth2: { + type: 'none', + }, }; const option = options.find((opts) => { return opts.every((o) => { if (o.value == null) { return false; - } else if (o.type === "http:basic") { + } + if (o.type === 'http:basic') { return o.value.username != null || o.value.password != null; - } else if (o.type === "http:custom") { + } + if (o.type === 'http:custom') { return null; - } else if (o.type === "oauth2:password") { - return ( - typeof o.value === "string" && !!o.value - ); - } else if (o.type === "oauth2:client_credentials") { - if (typeof o.value == "string") { + } + if (o.type === 'oauth2:password') { + return typeof o.value === 'string' && !!o.value; + } + if (o.type === 'oauth2:client_credentials') { + if (typeof o.value == 'string') { return !!o.value; } return o.value.clientID != null || o.value.clientSecret != null; - } else if (typeof o.value === "string") { + } + if (typeof o.value === 'string') { return !!o.value; - } else { - throw new Error( - `Unrecognized security type: ${o.type} (value type: ${typeof o - .value})`, - ); } + throw new Error(`Unrecognized security type: ${o.type} (value type: ${typeof o.value})`); }); }); if (option == null) { @@ -170,32 +179,32 @@ export function resolveSecurity( const { type } = spec; switch (type) { - case "apiKey:header": + case 'apiKey:header': state.headers[spec.fieldName] = spec.value; break; - case "apiKey:query": + case 'apiKey:query': state.queryParams[spec.fieldName] = spec.value; break; - case "apiKey:cookie": + case 'apiKey:cookie': state.cookies[spec.fieldName] = spec.value; break; - case "http:basic": + case 'http:basic': applyBasic(state, spec); break; - case "http:custom": + case 'http:custom': break; - case "http:bearer": + case 'http:bearer': applyBearer(state, spec); break; - case "oauth2": + case 'oauth2': applyBearer(state, spec); break; - case "oauth2:password": + case 'oauth2:password': applyBearer(state, spec); break; - case "oauth2:client_credentials": + case 'oauth2:client_credentials': break; - case "openIdConnect": + case 'openIdConnect': applyBearer(state, spec); break; default: @@ -207,10 +216,7 @@ export function resolveSecurity( return state; } -function applyBasic( - state: SecurityState, - spec: SecurityInputBasic, -) { +function applyBasic(state: SecurityState, spec: SecurityInputBasic) { if (spec.value == null) { return; } @@ -226,12 +232,12 @@ function applyBearer( | SecurityInputOIDC | SecurityInputOAuth2PasswordCredentials, ) { - if (typeof spec.value !== "string" || !spec.value) { + if (typeof spec.value !== 'string' || !spec.value) { return; } let value = spec.value; - if (value.slice(0, 7).toLowerCase() !== "bearer ") { + if (value.slice(0, 7).toLowerCase() !== 'bearer ') { value = `Bearer ${value}`; } @@ -243,23 +249,21 @@ function applyBearer( export function resolveGlobalSecurity( security: Partial | null | undefined, ): SecurityState | null { - return resolveSecurity( - [ - { - fieldName: "Authorization", - type: "http:bearer", - value: security?.apiKey ?? env().OPENROUTER_API_KEY, - }, - ], - ); + return resolveSecurity([ + { + fieldName: 'Authorization', + type: 'http:bearer', + value: security?.apiKey ?? env().OPENROUTER_API_KEY, + }, + ]); } -export async function extractSecurity< - T extends string | Record, ->(sec: T | (() => Promise) | undefined): Promise { +export async function extractSecurity>( + sec: T | (() => Promise) | undefined, +): Promise { if (sec == null) { return; } - return typeof sec === "function" ? sec() : sec; + return typeof sec === 'function' ? sec() : sec; } diff --git a/src/lib/tool-executor.ts b/src/lib/tool-executor.ts index c9f149f0..acc89380 100644 --- a/src/lib/tool-executor.ts +++ b/src/lib/tool-executor.ts @@ -1,8 +1,8 @@ import type { ZodType } from 'zod/v4'; import type { APITool, - Tool, ParsedToolCall, + Tool, ToolExecutionResult, TurnContext, } from './tool-types.js'; @@ -137,36 +137,30 @@ export async function executeGeneratorTool( toolCall.arguments, ) as Parameters[0]; - // Execute generator and collect all results - const preliminaryResults: unknown[] = []; - let lastEmittedValue: unknown = null; - let hasEmittedValue = false; + // Execute generator and collect all yielded values. + // Contract: all yields except the last must match eventSchema; the last yield must match outputSchema. + const yielded: unknown[] = []; + for await (const value of tool.function.execute(validatedInput, context)) { + yielded.push(value); + } - for await (const event of tool.function.execute(validatedInput, context)) { - hasEmittedValue = true; + if (yielded.length === 0) { + throw new Error(`Generator tool "${toolCall.name}" completed without emitting any values`); + } - // Validate event against eventSchema - const validatedEvent = validateToolOutput(tool.function.eventSchema, event); + const finalCandidate = yielded[yielded.length - 1]; + const preliminaryCandidates = yielded.slice(0, -1); + const preliminaryResults: unknown[] = []; + for (const event of preliminaryCandidates) { + const validatedEvent = validateToolOutput(tool.function.eventSchema, event); preliminaryResults.push(validatedEvent); - lastEmittedValue = validatedEvent; - - // Emit preliminary result via callback if (onPreliminaryResult) { onPreliminaryResult(toolCall.id, validatedEvent); } } - // Generator must emit at least one value - if (!hasEmittedValue) { - throw new Error(`Generator tool "${toolCall.name}" completed without emitting any values`); - } - - // Validate the last emitted value against outputSchema (this is the final result) - const finalResult = validateToolOutput(tool.function.outputSchema, lastEmittedValue); - - // Remove last item from preliminaryResults since it's the final output - preliminaryResults.pop(); + const finalResult = validateToolOutput(tool.function.outputSchema, finalCandidate); return { toolCallId: toolCall.id, diff --git a/src/lib/tool-orchestrator.ts b/src/lib/tool-orchestrator.ts index 18783860..13686d50 100644 --- a/src/lib/tool-orchestrator.ts +++ b/src/lib/tool-orchestrator.ts @@ -118,7 +118,7 @@ export async function executeToolLoop( const toolCall = toolCalls[i]; if (!toolCall) return; - if (settled.status === "fulfilled") { + if (settled.status === 'fulfilled') { if (settled.value !== null) { roundResults.push(settled.value); } @@ -128,9 +128,8 @@ export async function executeToolLoop( toolCallId: toolCall.id, toolName: toolCall.name, result: null, - error: settled.reason instanceof Error - ? settled.reason - : new Error(String(settled.reason)), + error: + settled.reason instanceof Error ? settled.reason : new Error(String(settled.reason)), }); } }); diff --git a/src/lib/tool-types.ts b/src/lib/tool-types.ts index 7fc41105..f1e72a54 100644 --- a/src/lib/tool-types.ts +++ b/src/lib/tool-types.ts @@ -131,7 +131,11 @@ export type Tool = /** * Extracts the input type from a tool definition */ -export type InferToolInput = T extends { function: { inputSchema: infer S } } +export type InferToolInput = T extends { + function: { + inputSchema: infer S; + }; +} ? S extends ZodType ? z.infer : unknown @@ -140,7 +144,11 @@ export type InferToolInput = T extends { function: { inputSchema: infer S } } /** * Extracts the output type from a tool definition */ -export type InferToolOutput = T extends { function: { outputSchema: infer S } } +export type InferToolOutput = T extends { + function: { + outputSchema: infer S; + }; +} ? S extends ZodType ? z.infer : unknown @@ -151,7 +159,13 @@ export type InferToolOutput = T extends { function: { outputSchema: infer S } */ export type TypedToolCall = { id: string; - name: T extends { function: { name: infer N } } ? N : string; + name: T extends { + function: { + name: infer N; + }; + } + ? N + : string; arguments: InferToolInput; }; @@ -166,7 +180,11 @@ export type TypedToolCallUnion = { * Extracts the event type from a generator tool definition * Returns `never` for non-generator tools */ -export type InferToolEvent = T extends { function: { eventSchema: infer S } } +export type InferToolEvent = T extends { + function: { + eventSchema: infer S; + }; +} ? S extends ZodType ? z.infer : never @@ -183,9 +201,7 @@ export type InferToolEventsUnion = { /** * Type guard to check if a tool has an execute function */ -export function hasExecuteFunction( - tool: Tool, -): tool is ToolWithExecute | ToolWithGenerator { +export function hasExecuteFunction(tool: Tool): tool is ToolWithExecute | ToolWithGenerator { return 'execute' in tool.function && typeof tool.function.execute === 'function'; } diff --git a/src/lib/tool.ts b/src/lib/tool.ts index 23445feb..32e6b1c9 100644 --- a/src/lib/tool.ts +++ b/src/lib/tool.ts @@ -1,19 +1,12 @@ -import type { ZodObject, ZodRawShape, ZodType, z } from "zod/v4"; -import { - ToolType, - type TurnContext, - type ToolWithExecute, - type ToolWithGenerator, - type ManualTool, -} from "./tool-types.js"; +import type { ZodObject, ZodRawShape, ZodType, z } from 'zod/v4'; +import type { ManualTool, ToolWithExecute, ToolWithGenerator, TurnContext } from './tool-types.js'; + +import { ToolType } from './tool-types.js'; /** * Configuration for a regular tool with outputSchema */ -type RegularToolConfigWithOutput< - TInput extends ZodObject, - TOutput extends ZodType, -> = { +type RegularToolConfigWithOutput, TOutput extends ZodType> = { name: string; description?: string; inputSchema: TInput; @@ -21,26 +14,20 @@ type RegularToolConfigWithOutput< eventSchema?: undefined; execute: ( params: z.infer, - context?: TurnContext + context?: TurnContext, ) => Promise> | z.infer; }; /** * Configuration for a regular tool without outputSchema (infers return type from execute) */ -type RegularToolConfigWithoutOutput< - TInput extends ZodObject, - TReturn, -> = { +type RegularToolConfigWithoutOutput, TReturn> = { name: string; description?: string; inputSchema: TInput; outputSchema?: undefined; eventSchema?: undefined; - execute: ( - params: z.infer, - context?: TurnContext - ) => Promise | TReturn; + execute: (params: z.infer, context?: TurnContext) => Promise | TReturn; }; /** @@ -58,7 +45,7 @@ type GeneratorToolConfig< outputSchema: TOutput; execute: ( params: z.infer, - context?: TurnContext + context?: TurnContext, ) => AsyncGenerator | z.infer>; }; @@ -91,9 +78,9 @@ function isGeneratorConfig< config: | GeneratorToolConfig | RegularToolConfig - | ManualToolConfig + | ManualToolConfig, ): config is GeneratorToolConfig { - return "eventSchema" in config && config.eventSchema !== undefined; + return 'eventSchema' in config && config.eventSchema !== undefined; } /** @@ -103,7 +90,7 @@ function isManualConfig, TOutput extends Z config: | GeneratorToolConfig | RegularToolConfig - | ManualToolConfig + | ManualToolConfig, ): config is ManualToolConfig { return config.execute === false; } @@ -158,26 +145,22 @@ export function tool< TInput extends ZodObject, TEvent extends ZodType, TOutput extends ZodType, ->( - config: GeneratorToolConfig -): ToolWithGenerator; +>(config: GeneratorToolConfig): ToolWithGenerator; // Overload for manual tools (execute: false) export function tool>( - config: ManualToolConfig + config: ManualToolConfig, ): ManualTool; // Overload for regular tools with outputSchema -export function tool< - TInput extends ZodObject, - TOutput extends ZodType, ->(config: RegularToolConfigWithOutput): ToolWithExecute; +export function tool, TOutput extends ZodType>( + config: RegularToolConfigWithOutput, +): ToolWithExecute; // Overload for regular tools without outputSchema (infers return type) -export function tool< - TInput extends ZodObject, - TReturn, ->(config: RegularToolConfigWithoutOutput): ToolWithExecute>; +export function tool, TReturn>( + config: RegularToolConfigWithoutOutput, +): ToolWithExecute>; // Implementation export function tool< @@ -189,7 +172,7 @@ export function tool< config: | GeneratorToolConfig | RegularToolConfig - | ManualToolConfig + | ManualToolConfig, ): | ToolWithGenerator | ToolWithExecute @@ -197,7 +180,7 @@ export function tool< | ManualTool { // Check for manual tool first (execute === false) if (isManualConfig(config)) { - const fn: ManualTool["function"] = { + const fn: ManualTool['function'] = { name: config.name, inputSchema: config.inputSchema, }; @@ -214,18 +197,14 @@ export function tool< // Check for generator tool (has eventSchema) if (isGeneratorConfig(config)) { - const fn: ToolWithGenerator["function"] = { + const fn: ToolWithGenerator['function'] = { name: config.name, inputSchema: config.inputSchema, eventSchema: config.eventSchema, outputSchema: config.outputSchema, // The config execute allows yielding both events and output, // but the interface only types for events (output is extracted separately) - execute: config.execute as ToolWithGenerator< - TInput, - TEvent, - TOutput - >["function"]["execute"], + execute: config.execute as ToolWithGenerator['function']['execute'], }; if (config.description !== undefined) { @@ -245,7 +224,7 @@ export function tool< name: config.name, inputSchema: config.inputSchema, execute: config.execute, - } as ToolWithExecute["function"]; + } as ToolWithExecute['function']; if (config.description !== undefined) { fn.description = config.description; diff --git a/src/lib/url.ts b/src/lib/url.ts index 99835829..6c983830 100644 --- a/src/lib/url.ts +++ b/src/lib/url.ts @@ -9,26 +9,24 @@ export type Params = Partial>; export function pathToFunc( pathPattern: string, - options?: { charEncoding?: "percent" | "none" }, + options?: { + charEncoding?: 'percent' | 'none'; + }, ): (params?: Params) => string { const paramRE = /\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g; return function buildURLPath(params: Record = {}): string { - return pathPattern.replace(paramRE, function (_, placeholder) { + return pathPattern.replace(paramRE, (_, placeholder) => { if (!hasOwn.call(params, placeholder)) { throw new Error(`Parameter '${placeholder}' is required`); } const value = params[placeholder]; - if (typeof value !== "string" && typeof value !== "number") { - throw new Error( - `Parameter '${placeholder}' must be a string or number`, - ); + if (typeof value !== 'string' && typeof value !== 'number') { + throw new Error(`Parameter '${placeholder}' must be a string or number`); } - return options?.charEncoding === "percent" - ? encodeURIComponent(`${value}`) - : `${value}`; + return options?.charEncoding === 'percent' ? encodeURIComponent(`${value}`) : `${value}`; }); }; } diff --git a/src/models/activityitem.ts b/src/models/activityitem.ts index c13ce725..77aa65a5 100644 --- a/src/models/activityitem.ts +++ b/src/models/activityitem.ts @@ -3,11 +3,12 @@ * @generated-id: ee2d86453873 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; export type ActivityItem = { /** @@ -70,15 +71,16 @@ export const ActivityItem$inboundSchema: z.ZodType = z prompt_tokens: z.number(), completion_tokens: z.number(), reasoning_tokens: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "model_permaslug": "modelPermaslug", - "endpoint_id": "endpointId", - "provider_name": "providerName", - "byok_usage_inference": "byokUsageInference", - "prompt_tokens": "promptTokens", - "completion_tokens": "completionTokens", - "reasoning_tokens": "reasoningTokens", + model_permaslug: 'modelPermaslug', + endpoint_id: 'endpointId', + provider_name: 'providerName', + byok_usage_inference: 'byokUsageInference', + prompt_tokens: 'promptTokens', + completion_tokens: 'completionTokens', + reasoning_tokens: 'reasoningTokens', }); }); diff --git a/src/models/assistantmessage.ts b/src/models/assistantmessage.ts index 6bebeafe..6f391f5f 100644 --- a/src/models/assistantmessage.ts +++ b/src/models/assistantmessage.ts @@ -3,28 +3,30 @@ * @generated-id: 2147a953e992 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { ChatMessageContentItem, - ChatMessageContentItem$inboundSchema, ChatMessageContentItem$Outbound, +} from './chatmessagecontentitem.js'; +import type { ChatMessageToolCall, ChatMessageToolCall$Outbound } from './chatmessagetoolcall.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { + ChatMessageContentItem$inboundSchema, ChatMessageContentItem$outboundSchema, -} from "./chatmessagecontentitem.js"; +} from './chatmessagecontentitem.js'; import { - ChatMessageToolCall, ChatMessageToolCall$inboundSchema, - ChatMessageToolCall$Outbound, ChatMessageToolCall$outboundSchema, -} from "./chatmessagetoolcall.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +} from './chatmessagetoolcall.js'; export type AssistantMessageContent = string | Array; export type AssistantMessage = { - role: "assistant"; + role: 'assistant'; content?: string | Array | null | undefined; name?: string | undefined; toolCalls?: Array | undefined; @@ -33,27 +35,27 @@ export type AssistantMessage = { }; /** @internal */ -export const AssistantMessageContent$inboundSchema: z.ZodType< - AssistantMessageContent, - unknown -> = z.union([z.string(), z.array(ChatMessageContentItem$inboundSchema)]); +export const AssistantMessageContent$inboundSchema: z.ZodType = + z.union([ + z.string(), + z.array(ChatMessageContentItem$inboundSchema), + ]); /** @internal */ -export type AssistantMessageContent$Outbound = - | string - | Array; +export type AssistantMessageContent$Outbound = string | Array; /** @internal */ export const AssistantMessageContent$outboundSchema: z.ZodType< AssistantMessageContent$Outbound, AssistantMessageContent -> = z.union([z.string(), z.array(ChatMessageContentItem$outboundSchema)]); +> = z.union([ + z.string(), + z.array(ChatMessageContentItem$outboundSchema), +]); export function assistantMessageContentToJSON( assistantMessageContent: AssistantMessageContent, ): string { - return JSON.stringify( - AssistantMessageContent$outboundSchema.parse(assistantMessageContent), - ); + return JSON.stringify(AssistantMessageContent$outboundSchema.parse(assistantMessageContent)); } export function assistantMessageContentFromJSON( jsonString: string, @@ -66,26 +68,30 @@ export function assistantMessageContentFromJSON( } /** @internal */ -export const AssistantMessage$inboundSchema: z.ZodType< - AssistantMessage, - unknown -> = z.object({ - role: z.literal("assistant"), - content: z.nullable( - z.union([z.string(), z.array(ChatMessageContentItem$inboundSchema)]), - ).optional(), - name: z.string().optional(), - tool_calls: z.array(ChatMessageToolCall$inboundSchema).optional(), - refusal: z.nullable(z.string()).optional(), - reasoning: z.nullable(z.string()).optional(), -}).transform((v) => { - return remap$(v, { - "tool_calls": "toolCalls", +export const AssistantMessage$inboundSchema: z.ZodType = z + .object({ + role: z.literal('assistant'), + content: z + .nullable( + z.union([ + z.string(), + z.array(ChatMessageContentItem$inboundSchema), + ]), + ) + .optional(), + name: z.string().optional(), + tool_calls: z.array(ChatMessageToolCall$inboundSchema).optional(), + refusal: z.nullable(z.string()).optional(), + reasoning: z.nullable(z.string()).optional(), + }) + .transform((v) => { + return remap$(v, { + tool_calls: 'toolCalls', + }); }); -}); /** @internal */ export type AssistantMessage$Outbound = { - role: "assistant"; + role: 'assistant'; content?: string | Array | null | undefined; name?: string | undefined; tool_calls?: Array | undefined; @@ -97,27 +103,30 @@ export type AssistantMessage$Outbound = { export const AssistantMessage$outboundSchema: z.ZodType< AssistantMessage$Outbound, AssistantMessage -> = z.object({ - role: z.literal("assistant"), - content: z.nullable( - z.union([z.string(), z.array(ChatMessageContentItem$outboundSchema)]), - ).optional(), - name: z.string().optional(), - toolCalls: z.array(ChatMessageToolCall$outboundSchema).optional(), - refusal: z.nullable(z.string()).optional(), - reasoning: z.nullable(z.string()).optional(), -}).transform((v) => { - return remap$(v, { - toolCalls: "tool_calls", +> = z + .object({ + role: z.literal('assistant'), + content: z + .nullable( + z.union([ + z.string(), + z.array(ChatMessageContentItem$outboundSchema), + ]), + ) + .optional(), + name: z.string().optional(), + toolCalls: z.array(ChatMessageToolCall$outboundSchema).optional(), + refusal: z.nullable(z.string()).optional(), + reasoning: z.nullable(z.string()).optional(), + }) + .transform((v) => { + return remap$(v, { + toolCalls: 'tool_calls', + }); }); -}); -export function assistantMessageToJSON( - assistantMessage: AssistantMessage, -): string { - return JSON.stringify( - AssistantMessage$outboundSchema.parse(assistantMessage), - ); +export function assistantMessageToJSON(assistantMessage: AssistantMessage): string { + return JSON.stringify(AssistantMessage$outboundSchema.parse(assistantMessage)); } export function assistantMessageFromJSON( jsonString: string, diff --git a/src/models/badgatewayresponseerrordata.ts b/src/models/badgatewayresponseerrordata.ts index d636dbfd..f5a67b76 100644 --- a/src/models/badgatewayresponseerrordata.ts +++ b/src/models/badgatewayresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: de317517c298 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for BadGatewayResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type BadGatewayResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ diff --git a/src/models/badrequestresponseerrordata.ts b/src/models/badrequestresponseerrordata.ts index f2adbe93..3df91af7 100644 --- a/src/models/badrequestresponseerrordata.ts +++ b/src/models/badrequestresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: 42d173ee6203 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for BadRequestResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type BadRequestResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ diff --git a/src/models/chatcompletionfinishreason.ts b/src/models/chatcompletionfinishreason.ts index 83a32911..4e4e7fbd 100644 --- a/src/models/chatcompletionfinishreason.ts +++ b/src/models/chatcompletionfinishreason.ts @@ -3,20 +3,19 @@ * @generated-id: 6b06a4d1562d */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const ChatCompletionFinishReason = { - ToolCalls: "tool_calls", - Stop: "stop", - Length: "length", - ContentFilter: "content_filter", - Error: "error", + ToolCalls: 'tool_calls', + Stop: 'stop', + Length: 'length', + ContentFilter: 'content_filter', + Error: 'error', } as const; -export type ChatCompletionFinishReason = OpenEnum< - typeof ChatCompletionFinishReason ->; +export type ChatCompletionFinishReason = OpenEnum; /** @internal */ export const ChatCompletionFinishReason$inboundSchema: z.ZodType< diff --git a/src/models/chaterror.ts b/src/models/chaterror.ts index 9f509fc9..fcc72c2b 100644 --- a/src/models/chaterror.ts +++ b/src/models/chaterror.ts @@ -3,10 +3,11 @@ * @generated-id: b107ec938dc1 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; export type Code = string | number; @@ -23,9 +24,7 @@ export const Code$inboundSchema: z.ZodType = z.union([ z.number(), ]); -export function codeFromJSON( - jsonString: string, -): SafeParseResult { +export function codeFromJSON(jsonString: string): SafeParseResult { return safeParse( jsonString, (x) => Code$inboundSchema.parse(JSON.parse(x)), @@ -34,13 +33,17 @@ export function codeFromJSON( } /** @internal */ -export const ChatErrorError$inboundSchema: z.ZodType = - z.object({ - code: z.nullable(z.union([z.string(), z.number()])), - message: z.string(), - param: z.nullable(z.string()).optional(), - type: z.nullable(z.string()).optional(), - }); +export const ChatErrorError$inboundSchema: z.ZodType = z.object({ + code: z.nullable( + z.union([ + z.string(), + z.number(), + ]), + ), + message: z.string(), + param: z.nullable(z.string()).optional(), + type: z.nullable(z.string()).optional(), +}); export function chatErrorErrorFromJSON( jsonString: string, diff --git a/src/models/chatgenerationparams.ts b/src/models/chatgenerationparams.ts index 6f601cc6..552adc79 100644 --- a/src/models/chatgenerationparams.ts +++ b/src/models/chatgenerationparams.ts @@ -3,68 +3,52 @@ * @generated-id: f98a2a558f3f */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { - ChatStreamOptions, - ChatStreamOptions$Outbound, - ChatStreamOptions$outboundSchema, -} from "./chatstreamoptions.js"; -import { - Message, - Message$Outbound, - Message$outboundSchema, -} from "./message.js"; -import { - ProviderSortUnion, - ProviderSortUnion$Outbound, - ProviderSortUnion$outboundSchema, -} from "./providersortunion.js"; -import { - ReasoningSummaryVerbosity, - ReasoningSummaryVerbosity$outboundSchema, -} from "./reasoningsummaryverbosity.js"; -import { +import type { OpenEnum } from '../types/enums.js'; +import type { ChatStreamOptions, ChatStreamOptions$Outbound } from './chatstreamoptions.js'; +import type { Message, Message$Outbound } from './message.js'; +import type { ProviderSortUnion, ProviderSortUnion$Outbound } from './providersortunion.js'; +import type { ReasoningSummaryVerbosity } from './reasoningsummaryverbosity.js'; +import type { ResponseFormatJSONSchema, ResponseFormatJSONSchema$Outbound, - ResponseFormatJSONSchema$outboundSchema, -} from "./responseformatjsonschema.js"; -import { +} from './responseformatjsonschema.js'; +import type { ResponseFormatTextGrammar, ResponseFormatTextGrammar$Outbound, - ResponseFormatTextGrammar$outboundSchema, -} from "./responseformattextgrammar.js"; -import { - Schema0, - Schema0$Outbound, - Schema0$outboundSchema, -} from "./schema0.js"; -import { - ToolDefinitionJson, - ToolDefinitionJson$Outbound, - ToolDefinitionJson$outboundSchema, -} from "./tooldefinitionjson.js"; +} from './responseformattextgrammar.js'; +import type { Schema0, Schema0$Outbound } from './schema0.js'; +import type { ToolDefinitionJson, ToolDefinitionJson$Outbound } from './tooldefinitionjson.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import * as openEnums from '../types/enums.js'; +import { ChatStreamOptions$outboundSchema } from './chatstreamoptions.js'; +import { Message$outboundSchema } from './message.js'; +import { ProviderSortUnion$outboundSchema } from './providersortunion.js'; +import { ReasoningSummaryVerbosity$outboundSchema } from './reasoningsummaryverbosity.js'; +import { ResponseFormatJSONSchema$outboundSchema } from './responseformatjsonschema.js'; +import { ResponseFormatTextGrammar$outboundSchema } from './responseformattextgrammar.js'; +import { Schema0$outboundSchema } from './schema0.js'; +import { ToolDefinitionJson$outboundSchema } from './tooldefinitionjson.js'; export const ChatGenerationParamsDataCollection = { - Deny: "deny", - Allow: "allow", + Deny: 'deny', + Allow: 'allow', } as const; export type ChatGenerationParamsDataCollection = OpenEnum< typeof ChatGenerationParamsDataCollection >; export const Quantizations = { - Int4: "int4", - Int8: "int8", - Fp4: "fp4", - Fp6: "fp6", - Fp8: "fp8", - Fp16: "fp16", - Bf16: "bf16", - Fp32: "fp32", - Unknown: "unknown", + Int4: 'int4', + Int8: 'int8', + Fp4: 'fp4', + Fp6: 'fp6', + Fp8: 'fp8', + Fp16: 'fp16', + Bf16: 'bf16', + Fp32: 'fp32', + Unknown: 'unknown', } as const; export type Quantizations = OpenEnum; @@ -134,14 +118,14 @@ export type ChatGenerationParamsProvider = { }; export type ChatGenerationParamsPluginResponseHealing = { - id: "response-healing"; + id: 'response-healing'; enabled?: boolean | undefined; }; export const PdfEngine = { - MistralOcr: "mistral-ocr", - PdfText: "pdf-text", - Native: "native", + MistralOcr: 'mistral-ocr', + PdfText: 'pdf-text', + Native: 'native', } as const; export type PdfEngine = OpenEnum; @@ -150,19 +134,19 @@ export type Pdf = { }; export type ChatGenerationParamsPluginFileParser = { - id: "file-parser"; + id: 'file-parser'; enabled?: boolean | undefined; pdf?: Pdf | undefined; }; export const Engine = { - Native: "native", - Exa: "exa", + Native: 'native', + Exa: 'exa', } as const; export type Engine = OpenEnum; export type ChatGenerationParamsPluginWeb = { - id: "web"; + id: 'web'; enabled?: boolean | undefined; maxResults?: number | undefined; searchPrompt?: string | undefined; @@ -170,7 +154,7 @@ export type ChatGenerationParamsPluginWeb = { }; export type ChatGenerationParamsPluginModeration = { - id: "moderation"; + id: 'moderation'; }; export type ChatGenerationParamsPluginUnion = @@ -180,18 +164,18 @@ export type ChatGenerationParamsPluginUnion = | ChatGenerationParamsPluginResponseHealing; export const Route = { - Fallback: "fallback", - Sort: "sort", + Fallback: 'fallback', + Sort: 'sort', } as const; export type Route = OpenEnum; export const Effort = { - Xhigh: "xhigh", - High: "high", - Medium: "medium", - Low: "low", - Minimal: "minimal", - None: "none", + Xhigh: 'xhigh', + High: 'high', + Medium: 'medium', + Low: 'low', + Minimal: 'minimal', + None: 'none', } as const; export type Effort = OpenEnum; @@ -201,15 +185,15 @@ export type Reasoning = { }; export type ChatGenerationParamsResponseFormatPython = { - type: "python"; + type: 'python'; }; export type ChatGenerationParamsResponseFormatJSONObject = { - type: "json_object"; + type: 'json_object'; }; export type ChatGenerationParamsResponseFormatText = { - type: "text"; + type: 'text'; }; export type ChatGenerationParamsResponseFormatUnion = @@ -235,11 +219,11 @@ export type ChatGenerationParams = { */ plugins?: | Array< - | ChatGenerationParamsPluginModeration - | ChatGenerationParamsPluginWeb - | ChatGenerationParamsPluginFileParser - | ChatGenerationParamsPluginResponseHealing - > + | ChatGenerationParamsPluginModeration + | ChatGenerationParamsPluginWeb + | ChatGenerationParamsPluginFileParser + | ChatGenerationParamsPluginResponseHealing + > | undefined; route?: Route | null | undefined; user?: string | undefined; @@ -251,12 +235,21 @@ export type ChatGenerationParams = { model?: string | undefined; models?: Array | undefined; frequencyPenalty?: number | null | undefined; - logitBias?: { [k: string]: number } | null | undefined; + logitBias?: + | { + [k: string]: number; + } + | null + | undefined; logprobs?: boolean | null | undefined; topLogprobs?: number | null | undefined; maxCompletionTokens?: number | null | undefined; maxTokens?: number | null | undefined; - metadata?: { [k: string]: string } | undefined; + metadata?: + | { + [k: string]: string; + } + | undefined; presencePenalty?: number | null | undefined; reasoning?: Reasoning | undefined; responseFormat?: @@ -312,9 +305,7 @@ export function chatGenerationParamsMaxPriceToJSON( chatGenerationParamsMaxPrice: ChatGenerationParamsMaxPrice, ): string { return JSON.stringify( - ChatGenerationParamsMaxPrice$outboundSchema.parse( - chatGenerationParamsMaxPrice, - ), + ChatGenerationParamsMaxPrice$outboundSchema.parse(chatGenerationParamsMaxPrice), ); } @@ -341,67 +332,63 @@ export type ChatGenerationParamsProvider$Outbound = { export const ChatGenerationParamsProvider$outboundSchema: z.ZodType< ChatGenerationParamsProvider$Outbound, ChatGenerationParamsProvider -> = z.object({ - allowFallbacks: z.nullable(z.boolean()).optional(), - requireParameters: z.nullable(z.boolean()).optional(), - dataCollection: z.nullable(ChatGenerationParamsDataCollection$outboundSchema) - .optional(), - zdr: z.nullable(z.boolean()).optional(), - enforceDistillableText: z.nullable(z.boolean()).optional(), - order: z.nullable(z.array(Schema0$outboundSchema)).optional(), - only: z.nullable(z.array(Schema0$outboundSchema)).optional(), - ignore: z.nullable(z.array(Schema0$outboundSchema)).optional(), - quantizations: z.nullable(z.array(Quantizations$outboundSchema)).optional(), - sort: z.nullable(ProviderSortUnion$outboundSchema).optional(), - maxPrice: z.lazy(() => ChatGenerationParamsMaxPrice$outboundSchema) - .optional(), - preferredMinThroughput: z.nullable(z.number()).optional(), - preferredMaxLatency: z.nullable(z.number()).optional(), - minThroughput: z.nullable(z.number()).optional(), - maxLatency: z.nullable(z.number()).optional(), -}).transform((v) => { - return remap$(v, { - allowFallbacks: "allow_fallbacks", - requireParameters: "require_parameters", - dataCollection: "data_collection", - enforceDistillableText: "enforce_distillable_text", - maxPrice: "max_price", - preferredMinThroughput: "preferred_min_throughput", - preferredMaxLatency: "preferred_max_latency", - minThroughput: "min_throughput", - maxLatency: "max_latency", +> = z + .object({ + allowFallbacks: z.nullable(z.boolean()).optional(), + requireParameters: z.nullable(z.boolean()).optional(), + dataCollection: z.nullable(ChatGenerationParamsDataCollection$outboundSchema).optional(), + zdr: z.nullable(z.boolean()).optional(), + enforceDistillableText: z.nullable(z.boolean()).optional(), + order: z.nullable(z.array(Schema0$outboundSchema)).optional(), + only: z.nullable(z.array(Schema0$outboundSchema)).optional(), + ignore: z.nullable(z.array(Schema0$outboundSchema)).optional(), + quantizations: z.nullable(z.array(Quantizations$outboundSchema)).optional(), + sort: z.nullable(ProviderSortUnion$outboundSchema).optional(), + maxPrice: z.lazy(() => ChatGenerationParamsMaxPrice$outboundSchema).optional(), + preferredMinThroughput: z.nullable(z.number()).optional(), + preferredMaxLatency: z.nullable(z.number()).optional(), + minThroughput: z.nullable(z.number()).optional(), + maxLatency: z.nullable(z.number()).optional(), + }) + .transform((v) => { + return remap$(v, { + allowFallbacks: 'allow_fallbacks', + requireParameters: 'require_parameters', + dataCollection: 'data_collection', + enforceDistillableText: 'enforce_distillable_text', + maxPrice: 'max_price', + preferredMinThroughput: 'preferred_min_throughput', + preferredMaxLatency: 'preferred_max_latency', + minThroughput: 'min_throughput', + maxLatency: 'max_latency', + }); }); -}); export function chatGenerationParamsProviderToJSON( chatGenerationParamsProvider: ChatGenerationParamsProvider, ): string { return JSON.stringify( - ChatGenerationParamsProvider$outboundSchema.parse( - chatGenerationParamsProvider, - ), + ChatGenerationParamsProvider$outboundSchema.parse(chatGenerationParamsProvider), ); } /** @internal */ export type ChatGenerationParamsPluginResponseHealing$Outbound = { - id: "response-healing"; + id: 'response-healing'; enabled?: boolean | undefined; }; /** @internal */ -export const ChatGenerationParamsPluginResponseHealing$outboundSchema: - z.ZodType< - ChatGenerationParamsPluginResponseHealing$Outbound, - ChatGenerationParamsPluginResponseHealing - > = z.object({ - id: z.literal("response-healing"), - enabled: z.boolean().optional(), - }); +export const ChatGenerationParamsPluginResponseHealing$outboundSchema: z.ZodType< + ChatGenerationParamsPluginResponseHealing$Outbound, + ChatGenerationParamsPluginResponseHealing +> = z.object({ + id: z.literal('response-healing'), + enabled: z.boolean().optional(), +}); export function chatGenerationParamsPluginResponseHealingToJSON( - chatGenerationParamsPluginResponseHealing: - ChatGenerationParamsPluginResponseHealing, + chatGenerationParamsPluginResponseHealing: ChatGenerationParamsPluginResponseHealing, ): string { return JSON.stringify( ChatGenerationParamsPluginResponseHealing$outboundSchema.parse( @@ -411,8 +398,8 @@ export function chatGenerationParamsPluginResponseHealingToJSON( } /** @internal */ -export const PdfEngine$outboundSchema: z.ZodType = openEnums - .outboundSchema(PdfEngine); +export const PdfEngine$outboundSchema: z.ZodType = + openEnums.outboundSchema(PdfEngine); /** @internal */ export type Pdf$Outbound = { @@ -430,7 +417,7 @@ export function pdfToJSON(pdf: Pdf): string { /** @internal */ export type ChatGenerationParamsPluginFileParser$Outbound = { - id: "file-parser"; + id: 'file-parser'; enabled?: boolean | undefined; pdf?: Pdf$Outbound | undefined; }; @@ -440,7 +427,7 @@ export const ChatGenerationParamsPluginFileParser$outboundSchema: z.ZodType< ChatGenerationParamsPluginFileParser$Outbound, ChatGenerationParamsPluginFileParser > = z.object({ - id: z.literal("file-parser"), + id: z.literal('file-parser'), enabled: z.boolean().optional(), pdf: z.lazy(() => Pdf$outboundSchema).optional(), }); @@ -449,19 +436,16 @@ export function chatGenerationParamsPluginFileParserToJSON( chatGenerationParamsPluginFileParser: ChatGenerationParamsPluginFileParser, ): string { return JSON.stringify( - ChatGenerationParamsPluginFileParser$outboundSchema.parse( - chatGenerationParamsPluginFileParser, - ), + ChatGenerationParamsPluginFileParser$outboundSchema.parse(chatGenerationParamsPluginFileParser), ); } /** @internal */ -export const Engine$outboundSchema: z.ZodType = openEnums - .outboundSchema(Engine); +export const Engine$outboundSchema: z.ZodType = openEnums.outboundSchema(Engine); /** @internal */ export type ChatGenerationParamsPluginWeb$Outbound = { - id: "web"; + id: 'web'; enabled?: boolean | undefined; max_results?: number | undefined; search_prompt?: string | undefined; @@ -472,32 +456,32 @@ export type ChatGenerationParamsPluginWeb$Outbound = { export const ChatGenerationParamsPluginWeb$outboundSchema: z.ZodType< ChatGenerationParamsPluginWeb$Outbound, ChatGenerationParamsPluginWeb -> = z.object({ - id: z.literal("web"), - enabled: z.boolean().optional(), - maxResults: z.number().optional(), - searchPrompt: z.string().optional(), - engine: Engine$outboundSchema.optional(), -}).transform((v) => { - return remap$(v, { - maxResults: "max_results", - searchPrompt: "search_prompt", +> = z + .object({ + id: z.literal('web'), + enabled: z.boolean().optional(), + maxResults: z.number().optional(), + searchPrompt: z.string().optional(), + engine: Engine$outboundSchema.optional(), + }) + .transform((v) => { + return remap$(v, { + maxResults: 'max_results', + searchPrompt: 'search_prompt', + }); }); -}); export function chatGenerationParamsPluginWebToJSON( chatGenerationParamsPluginWeb: ChatGenerationParamsPluginWeb, ): string { return JSON.stringify( - ChatGenerationParamsPluginWeb$outboundSchema.parse( - chatGenerationParamsPluginWeb, - ), + ChatGenerationParamsPluginWeb$outboundSchema.parse(chatGenerationParamsPluginWeb), ); } /** @internal */ export type ChatGenerationParamsPluginModeration$Outbound = { - id: "moderation"; + id: 'moderation'; }; /** @internal */ @@ -505,16 +489,14 @@ export const ChatGenerationParamsPluginModeration$outboundSchema: z.ZodType< ChatGenerationParamsPluginModeration$Outbound, ChatGenerationParamsPluginModeration > = z.object({ - id: z.literal("moderation"), + id: z.literal('moderation'), }); export function chatGenerationParamsPluginModerationToJSON( chatGenerationParamsPluginModeration: ChatGenerationParamsPluginModeration, ): string { return JSON.stringify( - ChatGenerationParamsPluginModeration$outboundSchema.parse( - chatGenerationParamsPluginModeration, - ), + ChatGenerationParamsPluginModeration$outboundSchema.parse(chatGenerationParamsPluginModeration), ); } @@ -540,19 +522,15 @@ export function chatGenerationParamsPluginUnionToJSON( chatGenerationParamsPluginUnion: ChatGenerationParamsPluginUnion, ): string { return JSON.stringify( - ChatGenerationParamsPluginUnion$outboundSchema.parse( - chatGenerationParamsPluginUnion, - ), + ChatGenerationParamsPluginUnion$outboundSchema.parse(chatGenerationParamsPluginUnion), ); } /** @internal */ -export const Route$outboundSchema: z.ZodType = openEnums - .outboundSchema(Route); +export const Route$outboundSchema: z.ZodType = openEnums.outboundSchema(Route); /** @internal */ -export const Effort$outboundSchema: z.ZodType = openEnums - .outboundSchema(Effort); +export const Effort$outboundSchema: z.ZodType = openEnums.outboundSchema(Effort); /** @internal */ export type Reasoning$Outbound = { @@ -561,10 +539,7 @@ export type Reasoning$Outbound = { }; /** @internal */ -export const Reasoning$outboundSchema: z.ZodType< - Reasoning$Outbound, - Reasoning -> = z.object({ +export const Reasoning$outboundSchema: z.ZodType = z.object({ effort: z.nullable(Effort$outboundSchema).optional(), summary: z.nullable(ReasoningSummaryVerbosity$outboundSchema).optional(), }); @@ -575,7 +550,7 @@ export function reasoningToJSON(reasoning: Reasoning): string { /** @internal */ export type ChatGenerationParamsResponseFormatPython$Outbound = { - type: "python"; + type: 'python'; }; /** @internal */ @@ -583,12 +558,11 @@ export const ChatGenerationParamsResponseFormatPython$outboundSchema: z.ZodType< ChatGenerationParamsResponseFormatPython$Outbound, ChatGenerationParamsResponseFormatPython > = z.object({ - type: z.literal("python"), + type: z.literal('python'), }); export function chatGenerationParamsResponseFormatPythonToJSON( - chatGenerationParamsResponseFormatPython: - ChatGenerationParamsResponseFormatPython, + chatGenerationParamsResponseFormatPython: ChatGenerationParamsResponseFormatPython, ): string { return JSON.stringify( ChatGenerationParamsResponseFormatPython$outboundSchema.parse( @@ -599,21 +573,19 @@ export function chatGenerationParamsResponseFormatPythonToJSON( /** @internal */ export type ChatGenerationParamsResponseFormatJSONObject$Outbound = { - type: "json_object"; + type: 'json_object'; }; /** @internal */ -export const ChatGenerationParamsResponseFormatJSONObject$outboundSchema: - z.ZodType< - ChatGenerationParamsResponseFormatJSONObject$Outbound, - ChatGenerationParamsResponseFormatJSONObject - > = z.object({ - type: z.literal("json_object"), - }); +export const ChatGenerationParamsResponseFormatJSONObject$outboundSchema: z.ZodType< + ChatGenerationParamsResponseFormatJSONObject$Outbound, + ChatGenerationParamsResponseFormatJSONObject +> = z.object({ + type: z.literal('json_object'), +}); export function chatGenerationParamsResponseFormatJSONObjectToJSON( - chatGenerationParamsResponseFormatJSONObject: - ChatGenerationParamsResponseFormatJSONObject, + chatGenerationParamsResponseFormatJSONObject: ChatGenerationParamsResponseFormatJSONObject, ): string { return JSON.stringify( ChatGenerationParamsResponseFormatJSONObject$outboundSchema.parse( @@ -624,7 +596,7 @@ export function chatGenerationParamsResponseFormatJSONObjectToJSON( /** @internal */ export type ChatGenerationParamsResponseFormatText$Outbound = { - type: "text"; + type: 'text'; }; /** @internal */ @@ -632,12 +604,11 @@ export const ChatGenerationParamsResponseFormatText$outboundSchema: z.ZodType< ChatGenerationParamsResponseFormatText$Outbound, ChatGenerationParamsResponseFormatText > = z.object({ - type: z.literal("text"), + type: z.literal('text'), }); export function chatGenerationParamsResponseFormatTextToJSON( - chatGenerationParamsResponseFormatText: - ChatGenerationParamsResponseFormatText, + chatGenerationParamsResponseFormatText: ChatGenerationParamsResponseFormatText, ): string { return JSON.stringify( ChatGenerationParamsResponseFormatText$outboundSchema.parse( @@ -667,8 +638,7 @@ export const ChatGenerationParamsResponseFormatUnion$outboundSchema: z.ZodType< ]); export function chatGenerationParamsResponseFormatUnionToJSON( - chatGenerationParamsResponseFormatUnion: - ChatGenerationParamsResponseFormatUnion, + chatGenerationParamsResponseFormatUnion: ChatGenerationParamsResponseFormatUnion, ): string { return JSON.stringify( ChatGenerationParamsResponseFormatUnion$outboundSchema.parse( @@ -684,14 +654,15 @@ export type ChatGenerationParamsStop$Outbound = string | Array; export const ChatGenerationParamsStop$outboundSchema: z.ZodType< ChatGenerationParamsStop$Outbound, ChatGenerationParamsStop -> = z.union([z.string(), z.array(z.string())]); +> = z.union([ + z.string(), + z.array(z.string()), +]); export function chatGenerationParamsStopToJSON( chatGenerationParamsStop: ChatGenerationParamsStop, ): string { - return JSON.stringify( - ChatGenerationParamsStop$outboundSchema.parse(chatGenerationParamsStop), - ); + return JSON.stringify(ChatGenerationParamsStop$outboundSchema.parse(chatGenerationParamsStop)); } /** @internal */ @@ -700,13 +671,15 @@ export type Debug$Outbound = { }; /** @internal */ -export const Debug$outboundSchema: z.ZodType = z.object({ - echoUpstreamBody: z.boolean().optional(), -}).transform((v) => { - return remap$(v, { - echoUpstreamBody: "echo_upstream_body", +export const Debug$outboundSchema: z.ZodType = z + .object({ + echoUpstreamBody: z.boolean().optional(), + }) + .transform((v) => { + return remap$(v, { + echoUpstreamBody: 'echo_upstream_body', + }); }); -}); export function debugToJSON(debug: Debug): string { return JSON.stringify(Debug$outboundSchema.parse(debug)); @@ -717,11 +690,11 @@ export type ChatGenerationParams$Outbound = { provider?: ChatGenerationParamsProvider$Outbound | null | undefined; plugins?: | Array< - | ChatGenerationParamsPluginModeration$Outbound - | ChatGenerationParamsPluginWeb$Outbound - | ChatGenerationParamsPluginFileParser$Outbound - | ChatGenerationParamsPluginResponseHealing$Outbound - > + | ChatGenerationParamsPluginModeration$Outbound + | ChatGenerationParamsPluginWeb$Outbound + | ChatGenerationParamsPluginFileParser$Outbound + | ChatGenerationParamsPluginResponseHealing$Outbound + > | undefined; route?: string | null | undefined; user?: string | undefined; @@ -730,12 +703,21 @@ export type ChatGenerationParams$Outbound = { model?: string | undefined; models?: Array | undefined; frequency_penalty?: number | null | undefined; - logit_bias?: { [k: string]: number } | null | undefined; + logit_bias?: + | { + [k: string]: number; + } + | null + | undefined; logprobs?: boolean | null | undefined; top_logprobs?: number | null | undefined; max_completion_tokens?: number | null | undefined; max_tokens?: number | null | undefined; - metadata?: { [k: string]: string } | undefined; + metadata?: + | { + [k: string]: string; + } + | undefined; presence_penalty?: number | null | undefined; reasoning?: Reasoning$Outbound | undefined; response_format?: @@ -760,69 +742,76 @@ export type ChatGenerationParams$Outbound = { export const ChatGenerationParams$outboundSchema: z.ZodType< ChatGenerationParams$Outbound, ChatGenerationParams -> = z.object({ - provider: z.nullable( - z.lazy(() => ChatGenerationParamsProvider$outboundSchema), - ).optional(), - plugins: z.array( - z.union([ - z.lazy(() => ChatGenerationParamsPluginModeration$outboundSchema), - z.lazy(() => ChatGenerationParamsPluginWeb$outboundSchema), - z.lazy(() => ChatGenerationParamsPluginFileParser$outboundSchema), - z.lazy(() => ChatGenerationParamsPluginResponseHealing$outboundSchema), - ]), - ).optional(), - route: z.nullable(Route$outboundSchema).optional(), - user: z.string().optional(), - sessionId: z.string().optional(), - messages: z.array(Message$outboundSchema), - model: z.string().optional(), - models: z.array(z.string()).optional(), - frequencyPenalty: z.nullable(z.number()).optional(), - logitBias: z.nullable(z.record(z.string(), z.number())).optional(), - logprobs: z.nullable(z.boolean()).optional(), - topLogprobs: z.nullable(z.number()).optional(), - maxCompletionTokens: z.nullable(z.number()).optional(), - maxTokens: z.nullable(z.number()).optional(), - metadata: z.record(z.string(), z.string()).optional(), - presencePenalty: z.nullable(z.number()).optional(), - reasoning: z.lazy(() => Reasoning$outboundSchema).optional(), - responseFormat: z.union([ - z.lazy(() => ChatGenerationParamsResponseFormatText$outboundSchema), - z.lazy(() => ChatGenerationParamsResponseFormatJSONObject$outboundSchema), - ResponseFormatJSONSchema$outboundSchema, - ResponseFormatTextGrammar$outboundSchema, - z.lazy(() => ChatGenerationParamsResponseFormatPython$outboundSchema), - ]).optional(), - seed: z.nullable(z.int()).optional(), - stop: z.nullable(z.union([z.string(), z.array(z.string())])).optional(), - stream: z.boolean().default(false), - streamOptions: z.nullable(ChatStreamOptions$outboundSchema).optional(), - temperature: z.nullable(z.number()).optional(), - toolChoice: z.any().optional(), - tools: z.array(ToolDefinitionJson$outboundSchema).optional(), - topP: z.nullable(z.number()).optional(), - debug: z.lazy(() => Debug$outboundSchema).optional(), -}).transform((v) => { - return remap$(v, { - sessionId: "session_id", - frequencyPenalty: "frequency_penalty", - logitBias: "logit_bias", - topLogprobs: "top_logprobs", - maxCompletionTokens: "max_completion_tokens", - maxTokens: "max_tokens", - presencePenalty: "presence_penalty", - responseFormat: "response_format", - streamOptions: "stream_options", - toolChoice: "tool_choice", - topP: "top_p", +> = z + .object({ + provider: z.nullable(z.lazy(() => ChatGenerationParamsProvider$outboundSchema)).optional(), + plugins: z + .array( + z.union([ + z.lazy(() => ChatGenerationParamsPluginModeration$outboundSchema), + z.lazy(() => ChatGenerationParamsPluginWeb$outboundSchema), + z.lazy(() => ChatGenerationParamsPluginFileParser$outboundSchema), + z.lazy(() => ChatGenerationParamsPluginResponseHealing$outboundSchema), + ]), + ) + .optional(), + route: z.nullable(Route$outboundSchema).optional(), + user: z.string().optional(), + sessionId: z.string().optional(), + messages: z.array(Message$outboundSchema), + model: z.string().optional(), + models: z.array(z.string()).optional(), + frequencyPenalty: z.nullable(z.number()).optional(), + logitBias: z.nullable(z.record(z.string(), z.number())).optional(), + logprobs: z.nullable(z.boolean()).optional(), + topLogprobs: z.nullable(z.number()).optional(), + maxCompletionTokens: z.nullable(z.number()).optional(), + maxTokens: z.nullable(z.number()).optional(), + metadata: z.record(z.string(), z.string()).optional(), + presencePenalty: z.nullable(z.number()).optional(), + reasoning: z.lazy(() => Reasoning$outboundSchema).optional(), + responseFormat: z + .union([ + z.lazy(() => ChatGenerationParamsResponseFormatText$outboundSchema), + z.lazy(() => ChatGenerationParamsResponseFormatJSONObject$outboundSchema), + ResponseFormatJSONSchema$outboundSchema, + ResponseFormatTextGrammar$outboundSchema, + z.lazy(() => ChatGenerationParamsResponseFormatPython$outboundSchema), + ]) + .optional(), + seed: z.nullable(z.int()).optional(), + stop: z + .nullable( + z.union([ + z.string(), + z.array(z.string()), + ]), + ) + .optional(), + stream: z.boolean().default(false), + streamOptions: z.nullable(ChatStreamOptions$outboundSchema).optional(), + temperature: z.nullable(z.number()).optional(), + toolChoice: z.any().optional(), + tools: z.array(ToolDefinitionJson$outboundSchema).optional(), + topP: z.nullable(z.number()).optional(), + debug: z.lazy(() => Debug$outboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + sessionId: 'session_id', + frequencyPenalty: 'frequency_penalty', + logitBias: 'logit_bias', + topLogprobs: 'top_logprobs', + maxCompletionTokens: 'max_completion_tokens', + maxTokens: 'max_tokens', + presencePenalty: 'presence_penalty', + responseFormat: 'response_format', + streamOptions: 'stream_options', + toolChoice: 'tool_choice', + topP: 'top_p', + }); }); -}); -export function chatGenerationParamsToJSON( - chatGenerationParams: ChatGenerationParams, -): string { - return JSON.stringify( - ChatGenerationParams$outboundSchema.parse(chatGenerationParams), - ); +export function chatGenerationParamsToJSON(chatGenerationParams: ChatGenerationParams): string { + return JSON.stringify(ChatGenerationParams$outboundSchema.parse(chatGenerationParams)); } diff --git a/src/models/chatgenerationtokenusage.ts b/src/models/chatgenerationtokenusage.ts index 07e1115a..a5cf065a 100644 --- a/src/models/chatgenerationtokenusage.ts +++ b/src/models/chatgenerationtokenusage.ts @@ -3,11 +3,12 @@ * @generated-id: 1d57b0d238b8 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; export type CompletionTokensDetails = { reasoningTokens?: number | null | undefined; @@ -31,22 +32,21 @@ export type ChatGenerationTokenUsage = { }; /** @internal */ -export const CompletionTokensDetails$inboundSchema: z.ZodType< - CompletionTokensDetails, - unknown -> = z.object({ - reasoning_tokens: z.nullable(z.number()).optional(), - audio_tokens: z.nullable(z.number()).optional(), - accepted_prediction_tokens: z.nullable(z.number()).optional(), - rejected_prediction_tokens: z.nullable(z.number()).optional(), -}).transform((v) => { - return remap$(v, { - "reasoning_tokens": "reasoningTokens", - "audio_tokens": "audioTokens", - "accepted_prediction_tokens": "acceptedPredictionTokens", - "rejected_prediction_tokens": "rejectedPredictionTokens", +export const CompletionTokensDetails$inboundSchema: z.ZodType = z + .object({ + reasoning_tokens: z.nullable(z.number()).optional(), + audio_tokens: z.nullable(z.number()).optional(), + accepted_prediction_tokens: z.nullable(z.number()).optional(), + rejected_prediction_tokens: z.nullable(z.number()).optional(), + }) + .transform((v) => { + return remap$(v, { + reasoning_tokens: 'reasoningTokens', + audio_tokens: 'audioTokens', + accepted_prediction_tokens: 'acceptedPredictionTokens', + rejected_prediction_tokens: 'rejectedPredictionTokens', + }); }); -}); export function completionTokensDetailsFromJSON( jsonString: string, @@ -59,20 +59,19 @@ export function completionTokensDetailsFromJSON( } /** @internal */ -export const PromptTokensDetails$inboundSchema: z.ZodType< - PromptTokensDetails, - unknown -> = z.object({ - cached_tokens: z.number().optional(), - audio_tokens: z.number().optional(), - video_tokens: z.number().optional(), -}).transform((v) => { - return remap$(v, { - "cached_tokens": "cachedTokens", - "audio_tokens": "audioTokens", - "video_tokens": "videoTokens", +export const PromptTokensDetails$inboundSchema: z.ZodType = z + .object({ + cached_tokens: z.number().optional(), + audio_tokens: z.number().optional(), + video_tokens: z.number().optional(), + }) + .transform((v) => { + return remap$(v, { + cached_tokens: 'cachedTokens', + audio_tokens: 'audioTokens', + video_tokens: 'videoTokens', + }); }); -}); export function promptTokensDetailsFromJSON( jsonString: string, @@ -85,28 +84,26 @@ export function promptTokensDetailsFromJSON( } /** @internal */ -export const ChatGenerationTokenUsage$inboundSchema: z.ZodType< - ChatGenerationTokenUsage, - unknown -> = z.object({ - completion_tokens: z.number(), - prompt_tokens: z.number(), - total_tokens: z.number(), - completion_tokens_details: z.nullable( - z.lazy(() => CompletionTokensDetails$inboundSchema), - ).optional(), - prompt_tokens_details: z.nullable( - z.lazy(() => PromptTokensDetails$inboundSchema), - ).optional(), -}).transform((v) => { - return remap$(v, { - "completion_tokens": "completionTokens", - "prompt_tokens": "promptTokens", - "total_tokens": "totalTokens", - "completion_tokens_details": "completionTokensDetails", - "prompt_tokens_details": "promptTokensDetails", - }); -}); +export const ChatGenerationTokenUsage$inboundSchema: z.ZodType = + z + .object({ + completion_tokens: z.number(), + prompt_tokens: z.number(), + total_tokens: z.number(), + completion_tokens_details: z + .nullable(z.lazy(() => CompletionTokensDetails$inboundSchema)) + .optional(), + prompt_tokens_details: z.nullable(z.lazy(() => PromptTokensDetails$inboundSchema)).optional(), + }) + .transform((v) => { + return remap$(v, { + completion_tokens: 'completionTokens', + prompt_tokens: 'promptTokens', + total_tokens: 'totalTokens', + completion_tokens_details: 'completionTokensDetails', + prompt_tokens_details: 'promptTokensDetails', + }); + }); export function chatGenerationTokenUsageFromJSON( jsonString: string, diff --git a/src/models/chatmessagecontentitem.ts b/src/models/chatmessagecontentitem.ts index f1548c67..f4e6b9a4 100644 --- a/src/models/chatmessagecontentitem.ts +++ b/src/models/chatmessagecontentitem.ts @@ -3,64 +3,85 @@ * @generated-id: bb7f6b29b93f */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { ChatMessageContentItemAudio, - ChatMessageContentItemAudio$inboundSchema, ChatMessageContentItemAudio$Outbound, +} from './chatmessagecontentitemaudio.js'; +import type { + ChatMessageContentItemImage, + ChatMessageContentItemImage$Outbound, +} from './chatmessagecontentitemimage.js'; +import type { + ChatMessageContentItemText, + ChatMessageContentItemText$Outbound, +} from './chatmessagecontentitemtext.js'; +import type { + ChatMessageContentItemVideo, + ChatMessageContentItemVideo$Outbound, +} from './chatmessagecontentitemvideo.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import { + ChatMessageContentItemAudio$inboundSchema, ChatMessageContentItemAudio$outboundSchema, -} from "./chatmessagecontentitemaudio.js"; +} from './chatmessagecontentitemaudio.js'; import { - ChatMessageContentItemImage, ChatMessageContentItemImage$inboundSchema, - ChatMessageContentItemImage$Outbound, ChatMessageContentItemImage$outboundSchema, -} from "./chatmessagecontentitemimage.js"; +} from './chatmessagecontentitemimage.js'; import { - ChatMessageContentItemText, ChatMessageContentItemText$inboundSchema, - ChatMessageContentItemText$Outbound, ChatMessageContentItemText$outboundSchema, -} from "./chatmessagecontentitemtext.js"; +} from './chatmessagecontentitemtext.js'; import { - ChatMessageContentItemVideo, ChatMessageContentItemVideo$inboundSchema, - ChatMessageContentItemVideo$Outbound, ChatMessageContentItemVideo$outboundSchema, -} from "./chatmessagecontentitemvideo.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +} from './chatmessagecontentitemvideo.js'; export type ChatMessageContentItem = | ChatMessageContentItemText | ChatMessageContentItemImage | ChatMessageContentItemAudio - | (ChatMessageContentItemVideo & { type: "input_video" }) - | (ChatMessageContentItemVideo & { type: "video_url" }); + | (ChatMessageContentItemVideo & { + type: 'input_video'; + }) + | (ChatMessageContentItemVideo & { + type: 'video_url'; + }); /** @internal */ -export const ChatMessageContentItem$inboundSchema: z.ZodType< - ChatMessageContentItem, - unknown -> = z.union([ - ChatMessageContentItemText$inboundSchema, - ChatMessageContentItemImage$inboundSchema, - ChatMessageContentItemAudio$inboundSchema, - ChatMessageContentItemVideo$inboundSchema.and( - z.object({ type: z.literal("input_video") }), - ), - z.lazy(() => ChatMessageContentItemVideo$inboundSchema).and( - z.object({ type: z.literal("video_url") }), - ), -]); +export const ChatMessageContentItem$inboundSchema: z.ZodType = + z.union([ + ChatMessageContentItemText$inboundSchema, + ChatMessageContentItemImage$inboundSchema, + ChatMessageContentItemAudio$inboundSchema, + ChatMessageContentItemVideo$inboundSchema.and( + z.object({ + type: z.literal('input_video'), + }), + ), + z + .lazy(() => ChatMessageContentItemVideo$inboundSchema) + .and( + z.object({ + type: z.literal('video_url'), + }), + ), + ]); /** @internal */ export type ChatMessageContentItem$Outbound = | ChatMessageContentItemText$Outbound | ChatMessageContentItemImage$Outbound | ChatMessageContentItemAudio$Outbound - | (ChatMessageContentItemVideo$Outbound & { type: "input_video" }) - | (ChatMessageContentItemVideo$Outbound & { type: "video_url" }); + | (ChatMessageContentItemVideo$Outbound & { + type: 'input_video'; + }) + | (ChatMessageContentItemVideo$Outbound & { + type: 'video_url'; + }); /** @internal */ export const ChatMessageContentItem$outboundSchema: z.ZodType< @@ -71,19 +92,23 @@ export const ChatMessageContentItem$outboundSchema: z.ZodType< ChatMessageContentItemImage$outboundSchema, ChatMessageContentItemAudio$outboundSchema, ChatMessageContentItemVideo$outboundSchema.and( - z.object({ type: z.literal("input_video") }), - ), - z.lazy(() => ChatMessageContentItemVideo$outboundSchema).and( - z.object({ type: z.literal("video_url") }), + z.object({ + type: z.literal('input_video'), + }), ), + z + .lazy(() => ChatMessageContentItemVideo$outboundSchema) + .and( + z.object({ + type: z.literal('video_url'), + }), + ), ]); export function chatMessageContentItemToJSON( chatMessageContentItem: ChatMessageContentItem, ): string { - return JSON.stringify( - ChatMessageContentItem$outboundSchema.parse(chatMessageContentItem), - ); + return JSON.stringify(ChatMessageContentItem$outboundSchema.parse(chatMessageContentItem)); } export function chatMessageContentItemFromJSON( jsonString: string, diff --git a/src/models/chatmessagecontentitemaudio.ts b/src/models/chatmessagecontentitemaudio.ts index afcdc4c1..25da62d5 100644 --- a/src/models/chatmessagecontentitemaudio.ts +++ b/src/models/chatmessagecontentitemaudio.ts @@ -3,11 +3,12 @@ * @generated-id: 49b1cafcb338 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; export type ChatMessageContentItemAudioInputAudio = { data: string; @@ -15,7 +16,7 @@ export type ChatMessageContentItemAudioInputAudio = { }; export type ChatMessageContentItemAudio = { - type: "input_audio"; + type: 'input_audio'; inputAudio: ChatMessageContentItemAudioInputAudio; }; @@ -56,8 +57,7 @@ export function chatMessageContentItemAudioInputAudioFromJSON( ): SafeParseResult { return safeParse( jsonString, - (x) => - ChatMessageContentItemAudioInputAudio$inboundSchema.parse(JSON.parse(x)), + (x) => ChatMessageContentItemAudioInputAudio$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'ChatMessageContentItemAudioInputAudio' from JSON`, ); } @@ -66,19 +66,19 @@ export function chatMessageContentItemAudioInputAudioFromJSON( export const ChatMessageContentItemAudio$inboundSchema: z.ZodType< ChatMessageContentItemAudio, unknown -> = z.object({ - type: z.literal("input_audio"), - input_audio: z.lazy(() => - ChatMessageContentItemAudioInputAudio$inboundSchema - ), -}).transform((v) => { - return remap$(v, { - "input_audio": "inputAudio", +> = z + .object({ + type: z.literal('input_audio'), + input_audio: z.lazy(() => ChatMessageContentItemAudioInputAudio$inboundSchema), + }) + .transform((v) => { + return remap$(v, { + input_audio: 'inputAudio', + }); }); -}); /** @internal */ export type ChatMessageContentItemAudio$Outbound = { - type: "input_audio"; + type: 'input_audio'; input_audio: ChatMessageContentItemAudioInputAudio$Outbound; }; @@ -86,24 +86,22 @@ export type ChatMessageContentItemAudio$Outbound = { export const ChatMessageContentItemAudio$outboundSchema: z.ZodType< ChatMessageContentItemAudio$Outbound, ChatMessageContentItemAudio -> = z.object({ - type: z.literal("input_audio"), - inputAudio: z.lazy(() => - ChatMessageContentItemAudioInputAudio$outboundSchema - ), -}).transform((v) => { - return remap$(v, { - inputAudio: "input_audio", +> = z + .object({ + type: z.literal('input_audio'), + inputAudio: z.lazy(() => ChatMessageContentItemAudioInputAudio$outboundSchema), + }) + .transform((v) => { + return remap$(v, { + inputAudio: 'input_audio', + }); }); -}); export function chatMessageContentItemAudioToJSON( chatMessageContentItemAudio: ChatMessageContentItemAudio, ): string { return JSON.stringify( - ChatMessageContentItemAudio$outboundSchema.parse( - chatMessageContentItemAudio, - ), + ChatMessageContentItemAudio$outboundSchema.parse(chatMessageContentItemAudio), ); } export function chatMessageContentItemAudioFromJSON( diff --git a/src/models/chatmessagecontentitemcachecontrol.ts b/src/models/chatmessagecontentitemcachecontrol.ts index c368f953..22518a61 100644 --- a/src/models/chatmessagecontentitemcachecontrol.ts +++ b/src/models/chatmessagecontentitemcachecontrol.ts @@ -3,42 +3,41 @@ * @generated-id: b5c18e04e19c */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { OpenEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import * as openEnums from '../types/enums.js'; export const Ttl = { - Fivem: "5m", - Oneh: "1h", + Fivem: '5m', + Oneh: '1h', } as const; export type Ttl = OpenEnum; export type ChatMessageContentItemCacheControl = { - type: "ephemeral"; + type: 'ephemeral'; ttl?: Ttl | undefined; }; /** @internal */ -export const Ttl$inboundSchema: z.ZodType = openEnums - .inboundSchema(Ttl); +export const Ttl$inboundSchema: z.ZodType = openEnums.inboundSchema(Ttl); /** @internal */ -export const Ttl$outboundSchema: z.ZodType = openEnums - .outboundSchema(Ttl); +export const Ttl$outboundSchema: z.ZodType = openEnums.outboundSchema(Ttl); /** @internal */ export const ChatMessageContentItemCacheControl$inboundSchema: z.ZodType< ChatMessageContentItemCacheControl, unknown > = z.object({ - type: z.literal("ephemeral"), + type: z.literal('ephemeral'), ttl: Ttl$inboundSchema.optional(), }); /** @internal */ export type ChatMessageContentItemCacheControl$Outbound = { - type: "ephemeral"; + type: 'ephemeral'; ttl?: string | undefined; }; @@ -47,7 +46,7 @@ export const ChatMessageContentItemCacheControl$outboundSchema: z.ZodType< ChatMessageContentItemCacheControl$Outbound, ChatMessageContentItemCacheControl > = z.object({ - type: z.literal("ephemeral"), + type: z.literal('ephemeral'), ttl: Ttl$outboundSchema.optional(), }); @@ -55,9 +54,7 @@ export function chatMessageContentItemCacheControlToJSON( chatMessageContentItemCacheControl: ChatMessageContentItemCacheControl, ): string { return JSON.stringify( - ChatMessageContentItemCacheControl$outboundSchema.parse( - chatMessageContentItemCacheControl, - ), + ChatMessageContentItemCacheControl$outboundSchema.parse(chatMessageContentItemCacheControl), ); } export function chatMessageContentItemCacheControlFromJSON( @@ -65,8 +62,7 @@ export function chatMessageContentItemCacheControlFromJSON( ): SafeParseResult { return safeParse( jsonString, - (x) => - ChatMessageContentItemCacheControl$inboundSchema.parse(JSON.parse(x)), + (x) => ChatMessageContentItemCacheControl$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'ChatMessageContentItemCacheControl' from JSON`, ); } diff --git a/src/models/chatmessagecontentitemimage.ts b/src/models/chatmessagecontentitemimage.ts index 2d47383c..926b929b 100644 --- a/src/models/chatmessagecontentitemimage.ts +++ b/src/models/chatmessagecontentitemimage.ts @@ -3,22 +3,21 @@ * @generated-id: 3989cdc41817 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { OpenEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import * as openEnums from '../types/enums.js'; export const ChatMessageContentItemImageDetail = { - Auto: "auto", - Low: "low", - High: "high", + Auto: 'auto', + Low: 'low', + High: 'high', } as const; -export type ChatMessageContentItemImageDetail = OpenEnum< - typeof ChatMessageContentItemImageDetail ->; +export type ChatMessageContentItemImageDetail = OpenEnum; export type ImageUrl = { url: string; @@ -26,7 +25,7 @@ export type ImageUrl = { }; export type ChatMessageContentItemImage = { - type: "image_url"; + type: 'image_url'; imageUrl: ImageUrl; }; @@ -53,11 +52,10 @@ export type ImageUrl$Outbound = { }; /** @internal */ -export const ImageUrl$outboundSchema: z.ZodType = z - .object({ - url: z.string(), - detail: ChatMessageContentItemImageDetail$outboundSchema.optional(), - }); +export const ImageUrl$outboundSchema: z.ZodType = z.object({ + url: z.string(), + detail: ChatMessageContentItemImageDetail$outboundSchema.optional(), +}); export function imageUrlToJSON(imageUrl: ImageUrl): string { return JSON.stringify(ImageUrl$outboundSchema.parse(imageUrl)); @@ -76,17 +74,19 @@ export function imageUrlFromJSON( export const ChatMessageContentItemImage$inboundSchema: z.ZodType< ChatMessageContentItemImage, unknown -> = z.object({ - type: z.literal("image_url"), - image_url: z.lazy(() => ImageUrl$inboundSchema), -}).transform((v) => { - return remap$(v, { - "image_url": "imageUrl", +> = z + .object({ + type: z.literal('image_url'), + image_url: z.lazy(() => ImageUrl$inboundSchema), + }) + .transform((v) => { + return remap$(v, { + image_url: 'imageUrl', + }); }); -}); /** @internal */ export type ChatMessageContentItemImage$Outbound = { - type: "image_url"; + type: 'image_url'; image_url: ImageUrl$Outbound; }; @@ -94,22 +94,22 @@ export type ChatMessageContentItemImage$Outbound = { export const ChatMessageContentItemImage$outboundSchema: z.ZodType< ChatMessageContentItemImage$Outbound, ChatMessageContentItemImage -> = z.object({ - type: z.literal("image_url"), - imageUrl: z.lazy(() => ImageUrl$outboundSchema), -}).transform((v) => { - return remap$(v, { - imageUrl: "image_url", +> = z + .object({ + type: z.literal('image_url'), + imageUrl: z.lazy(() => ImageUrl$outboundSchema), + }) + .transform((v) => { + return remap$(v, { + imageUrl: 'image_url', + }); }); -}); export function chatMessageContentItemImageToJSON( chatMessageContentItemImage: ChatMessageContentItemImage, ): string { return JSON.stringify( - ChatMessageContentItemImage$outboundSchema.parse( - chatMessageContentItemImage, - ), + ChatMessageContentItemImage$outboundSchema.parse(chatMessageContentItemImage), ); } export function chatMessageContentItemImageFromJSON( diff --git a/src/models/chatmessagecontentitemtext.ts b/src/models/chatmessagecontentitemtext.ts index aa527d53..140e5042 100644 --- a/src/models/chatmessagecontentitemtext.ts +++ b/src/models/chatmessagecontentitemtext.ts @@ -3,20 +3,23 @@ * @generated-id: 27089860fd98 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { ChatMessageContentItemCacheControl, - ChatMessageContentItemCacheControl$inboundSchema, ChatMessageContentItemCacheControl$Outbound, +} from './chatmessagecontentitemcachecontrol.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { + ChatMessageContentItemCacheControl$inboundSchema, ChatMessageContentItemCacheControl$outboundSchema, -} from "./chatmessagecontentitemcachecontrol.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +} from './chatmessagecontentitemcachecontrol.js'; export type ChatMessageContentItemText = { - type: "text"; + type: 'text'; text: string; cacheControl?: ChatMessageContentItemCacheControl | undefined; }; @@ -25,18 +28,20 @@ export type ChatMessageContentItemText = { export const ChatMessageContentItemText$inboundSchema: z.ZodType< ChatMessageContentItemText, unknown -> = z.object({ - type: z.literal("text"), - text: z.string(), - cache_control: ChatMessageContentItemCacheControl$inboundSchema.optional(), -}).transform((v) => { - return remap$(v, { - "cache_control": "cacheControl", +> = z + .object({ + type: z.literal('text'), + text: z.string(), + cache_control: ChatMessageContentItemCacheControl$inboundSchema.optional(), + }) + .transform((v) => { + return remap$(v, { + cache_control: 'cacheControl', + }); }); -}); /** @internal */ export type ChatMessageContentItemText$Outbound = { - type: "text"; + type: 'text'; text: string; cache_control?: ChatMessageContentItemCacheControl$Outbound | undefined; }; @@ -45,15 +50,17 @@ export type ChatMessageContentItemText$Outbound = { export const ChatMessageContentItemText$outboundSchema: z.ZodType< ChatMessageContentItemText$Outbound, ChatMessageContentItemText -> = z.object({ - type: z.literal("text"), - text: z.string(), - cacheControl: ChatMessageContentItemCacheControl$outboundSchema.optional(), -}).transform((v) => { - return remap$(v, { - cacheControl: "cache_control", +> = z + .object({ + type: z.literal('text'), + text: z.string(), + cacheControl: ChatMessageContentItemCacheControl$outboundSchema.optional(), + }) + .transform((v) => { + return remap$(v, { + cacheControl: 'cache_control', + }); }); -}); export function chatMessageContentItemTextToJSON( chatMessageContentItemText: ChatMessageContentItemText, diff --git a/src/models/chatmessagecontentitemvideo.ts b/src/models/chatmessagecontentitemvideo.ts index 9847a917..a1cb1bba 100644 --- a/src/models/chatmessagecontentitemvideo.ts +++ b/src/models/chatmessagecontentitemvideo.ts @@ -3,18 +3,19 @@ * @generated-id: 5a81301cb4a7 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; export type VideoUrl2 = { url: string; }; export type ChatMessageContentItemVideoVideoURL = { - type: "video_url"; + type: 'video_url'; videoUrl: VideoUrl2; }; @@ -23,7 +24,7 @@ export type VideoUrl1 = { }; export type ChatMessageContentItemVideoInputVideo = { - type: "input_video"; + type: 'input_video'; videoUrl: VideoUrl1; }; @@ -41,10 +42,7 @@ export type VideoUrl2$Outbound = { }; /** @internal */ -export const VideoUrl2$outboundSchema: z.ZodType< - VideoUrl2$Outbound, - VideoUrl2 -> = z.object({ +export const VideoUrl2$outboundSchema: z.ZodType = z.object({ url: z.string(), }); @@ -65,17 +63,19 @@ export function videoUrl2FromJSON( export const ChatMessageContentItemVideoVideoURL$inboundSchema: z.ZodType< ChatMessageContentItemVideoVideoURL, unknown -> = z.object({ - type: z.literal("video_url"), - video_url: z.lazy(() => VideoUrl2$inboundSchema), -}).transform((v) => { - return remap$(v, { - "video_url": "videoUrl", +> = z + .object({ + type: z.literal('video_url'), + video_url: z.lazy(() => VideoUrl2$inboundSchema), + }) + .transform((v) => { + return remap$(v, { + video_url: 'videoUrl', + }); }); -}); /** @internal */ export type ChatMessageContentItemVideoVideoURL$Outbound = { - type: "video_url"; + type: 'video_url'; video_url: VideoUrl2$Outbound; }; @@ -83,22 +83,22 @@ export type ChatMessageContentItemVideoVideoURL$Outbound = { export const ChatMessageContentItemVideoVideoURL$outboundSchema: z.ZodType< ChatMessageContentItemVideoVideoURL$Outbound, ChatMessageContentItemVideoVideoURL -> = z.object({ - type: z.literal("video_url"), - videoUrl: z.lazy(() => VideoUrl2$outboundSchema), -}).transform((v) => { - return remap$(v, { - videoUrl: "video_url", +> = z + .object({ + type: z.literal('video_url'), + videoUrl: z.lazy(() => VideoUrl2$outboundSchema), + }) + .transform((v) => { + return remap$(v, { + videoUrl: 'video_url', + }); }); -}); export function chatMessageContentItemVideoVideoURLToJSON( chatMessageContentItemVideoVideoURL: ChatMessageContentItemVideoVideoURL, ): string { return JSON.stringify( - ChatMessageContentItemVideoVideoURL$outboundSchema.parse( - chatMessageContentItemVideoVideoURL, - ), + ChatMessageContentItemVideoVideoURL$outboundSchema.parse(chatMessageContentItemVideoVideoURL), ); } export function chatMessageContentItemVideoVideoURLFromJSON( @@ -106,8 +106,7 @@ export function chatMessageContentItemVideoVideoURLFromJSON( ): SafeParseResult { return safeParse( jsonString, - (x) => - ChatMessageContentItemVideoVideoURL$inboundSchema.parse(JSON.parse(x)), + (x) => ChatMessageContentItemVideoVideoURL$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'ChatMessageContentItemVideoVideoURL' from JSON`, ); } @@ -122,10 +121,7 @@ export type VideoUrl1$Outbound = { }; /** @internal */ -export const VideoUrl1$outboundSchema: z.ZodType< - VideoUrl1$Outbound, - VideoUrl1 -> = z.object({ +export const VideoUrl1$outboundSchema: z.ZodType = z.object({ url: z.string(), }); @@ -146,17 +142,19 @@ export function videoUrl1FromJSON( export const ChatMessageContentItemVideoInputVideo$inboundSchema: z.ZodType< ChatMessageContentItemVideoInputVideo, unknown -> = z.object({ - type: z.literal("input_video"), - video_url: z.lazy(() => VideoUrl1$inboundSchema), -}).transform((v) => { - return remap$(v, { - "video_url": "videoUrl", +> = z + .object({ + type: z.literal('input_video'), + video_url: z.lazy(() => VideoUrl1$inboundSchema), + }) + .transform((v) => { + return remap$(v, { + video_url: 'videoUrl', + }); }); -}); /** @internal */ export type ChatMessageContentItemVideoInputVideo$Outbound = { - type: "input_video"; + type: 'input_video'; video_url: VideoUrl1$Outbound; }; @@ -164,14 +162,16 @@ export type ChatMessageContentItemVideoInputVideo$Outbound = { export const ChatMessageContentItemVideoInputVideo$outboundSchema: z.ZodType< ChatMessageContentItemVideoInputVideo$Outbound, ChatMessageContentItemVideoInputVideo -> = z.object({ - type: z.literal("input_video"), - videoUrl: z.lazy(() => VideoUrl1$outboundSchema), -}).transform((v) => { - return remap$(v, { - videoUrl: "video_url", +> = z + .object({ + type: z.literal('input_video'), + videoUrl: z.lazy(() => VideoUrl1$outboundSchema), + }) + .transform((v) => { + return remap$(v, { + videoUrl: 'video_url', + }); }); -}); export function chatMessageContentItemVideoInputVideoToJSON( chatMessageContentItemVideoInputVideo: ChatMessageContentItemVideoInputVideo, @@ -187,8 +187,7 @@ export function chatMessageContentItemVideoInputVideoFromJSON( ): SafeParseResult { return safeParse( jsonString, - (x) => - ChatMessageContentItemVideoInputVideo$inboundSchema.parse(JSON.parse(x)), + (x) => ChatMessageContentItemVideoInputVideo$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'ChatMessageContentItemVideoInputVideo' from JSON`, ); } @@ -219,9 +218,7 @@ export function chatMessageContentItemVideoToJSON( chatMessageContentItemVideo: ChatMessageContentItemVideo, ): string { return JSON.stringify( - ChatMessageContentItemVideo$outboundSchema.parse( - chatMessageContentItemVideo, - ), + ChatMessageContentItemVideo$outboundSchema.parse(chatMessageContentItemVideo), ); } export function chatMessageContentItemVideoFromJSON( diff --git a/src/models/chatmessagetokenlogprob.ts b/src/models/chatmessagetokenlogprob.ts index 327bfbd1..87e2936c 100644 --- a/src/models/chatmessagetokenlogprob.ts +++ b/src/models/chatmessagetokenlogprob.ts @@ -3,11 +3,12 @@ * @generated-id: eed686a58eb1 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; export type TopLogprob = { token: string; @@ -23,12 +24,11 @@ export type ChatMessageTokenLogprob = { }; /** @internal */ -export const TopLogprob$inboundSchema: z.ZodType = z - .object({ - token: z.string(), - logprob: z.number(), - bytes: z.nullable(z.array(z.number())), - }); +export const TopLogprob$inboundSchema: z.ZodType = z.object({ + token: z.string(), + logprob: z.number(), + bytes: z.nullable(z.array(z.number())), +}); export function topLogprobFromJSON( jsonString: string, @@ -41,19 +41,18 @@ export function topLogprobFromJSON( } /** @internal */ -export const ChatMessageTokenLogprob$inboundSchema: z.ZodType< - ChatMessageTokenLogprob, - unknown -> = z.object({ - token: z.string(), - logprob: z.number(), - bytes: z.nullable(z.array(z.number())), - top_logprobs: z.array(z.lazy(() => TopLogprob$inboundSchema)), -}).transform((v) => { - return remap$(v, { - "top_logprobs": "topLogprobs", +export const ChatMessageTokenLogprob$inboundSchema: z.ZodType = z + .object({ + token: z.string(), + logprob: z.number(), + bytes: z.nullable(z.array(z.number())), + top_logprobs: z.array(z.lazy(() => TopLogprob$inboundSchema)), + }) + .transform((v) => { + return remap$(v, { + top_logprobs: 'topLogprobs', + }); }); -}); export function chatMessageTokenLogprobFromJSON( jsonString: string, diff --git a/src/models/chatmessagetokenlogprobs.ts b/src/models/chatmessagetokenlogprobs.ts index d898f22a..3e6de4cb 100644 --- a/src/models/chatmessagetokenlogprobs.ts +++ b/src/models/chatmessagetokenlogprobs.ts @@ -3,14 +3,13 @@ * @generated-id: 2dbd9fc61ed8 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { - ChatMessageTokenLogprob, - ChatMessageTokenLogprob$inboundSchema, -} from "./chatmessagetokenlogprob.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { ChatMessageTokenLogprob } from './chatmessagetokenlogprob.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import { ChatMessageTokenLogprob$inboundSchema } from './chatmessagetokenlogprob.js'; export type ChatMessageTokenLogprobs = { content: Array | null; @@ -18,13 +17,11 @@ export type ChatMessageTokenLogprobs = { }; /** @internal */ -export const ChatMessageTokenLogprobs$inboundSchema: z.ZodType< - ChatMessageTokenLogprobs, - unknown -> = z.object({ - content: z.nullable(z.array(ChatMessageTokenLogprob$inboundSchema)), - refusal: z.nullable(z.array(ChatMessageTokenLogprob$inboundSchema)), -}); +export const ChatMessageTokenLogprobs$inboundSchema: z.ZodType = + z.object({ + content: z.nullable(z.array(ChatMessageTokenLogprob$inboundSchema)), + refusal: z.nullable(z.array(ChatMessageTokenLogprob$inboundSchema)), + }); export function chatMessageTokenLogprobsFromJSON( jsonString: string, diff --git a/src/models/chatmessagetoolcall.ts b/src/models/chatmessagetoolcall.ts index c6678412..09e648b5 100644 --- a/src/models/chatmessagetoolcall.ts +++ b/src/models/chatmessagetoolcall.ts @@ -3,10 +3,11 @@ * @generated-id: b294b44052da */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; export type ChatMessageToolCallFunction = { name: string; @@ -15,7 +16,7 @@ export type ChatMessageToolCallFunction = { export type ChatMessageToolCall = { id: string; - type: "function"; + type: 'function'; function: ChatMessageToolCallFunction; }; @@ -46,9 +47,7 @@ export function chatMessageToolCallFunctionToJSON( chatMessageToolCallFunction: ChatMessageToolCallFunction, ): string { return JSON.stringify( - ChatMessageToolCallFunction$outboundSchema.parse( - chatMessageToolCallFunction, - ), + ChatMessageToolCallFunction$outboundSchema.parse(chatMessageToolCallFunction), ); } export function chatMessageToolCallFunctionFromJSON( @@ -62,18 +61,15 @@ export function chatMessageToolCallFunctionFromJSON( } /** @internal */ -export const ChatMessageToolCall$inboundSchema: z.ZodType< - ChatMessageToolCall, - unknown -> = z.object({ +export const ChatMessageToolCall$inboundSchema: z.ZodType = z.object({ id: z.string(), - type: z.literal("function"), + type: z.literal('function'), function: z.lazy(() => ChatMessageToolCallFunction$inboundSchema), }); /** @internal */ export type ChatMessageToolCall$Outbound = { id: string; - type: "function"; + type: 'function'; function: ChatMessageToolCallFunction$Outbound; }; @@ -83,16 +79,12 @@ export const ChatMessageToolCall$outboundSchema: z.ZodType< ChatMessageToolCall > = z.object({ id: z.string(), - type: z.literal("function"), + type: z.literal('function'), function: z.lazy(() => ChatMessageToolCallFunction$outboundSchema), }); -export function chatMessageToolCallToJSON( - chatMessageToolCall: ChatMessageToolCall, -): string { - return JSON.stringify( - ChatMessageToolCall$outboundSchema.parse(chatMessageToolCall), - ); +export function chatMessageToolCallToJSON(chatMessageToolCall: ChatMessageToolCall): string { + return JSON.stringify(ChatMessageToolCall$outboundSchema.parse(chatMessageToolCall)); } export function chatMessageToolCallFromJSON( jsonString: string, diff --git a/src/models/chatresponse.ts b/src/models/chatresponse.ts index e1e9ede1..823cf3ac 100644 --- a/src/models/chatresponse.ts +++ b/src/models/chatresponse.ts @@ -3,26 +3,23 @@ * @generated-id: 76c3703fa3d5 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { - ChatGenerationTokenUsage, - ChatGenerationTokenUsage$inboundSchema, -} from "./chatgenerationtokenusage.js"; -import { - ChatResponseChoice, - ChatResponseChoice$inboundSchema, -} from "./chatresponsechoice.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { ChatGenerationTokenUsage } from './chatgenerationtokenusage.js'; +import type { ChatResponseChoice } from './chatresponsechoice.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { ChatGenerationTokenUsage$inboundSchema } from './chatgenerationtokenusage.js'; +import { ChatResponseChoice$inboundSchema } from './chatresponsechoice.js'; export type ChatResponse = { id: string; choices: Array; created: number; model: string; - object: "chat.completion"; + object: 'chat.completion'; systemFingerprint?: string | null | undefined; usage?: ChatGenerationTokenUsage | undefined; }; @@ -34,12 +31,13 @@ export const ChatResponse$inboundSchema: z.ZodType = z choices: z.array(ChatResponseChoice$inboundSchema), created: z.number(), model: z.string(), - object: z.literal("chat.completion"), + object: z.literal('chat.completion'), system_fingerprint: z.nullable(z.string()).optional(), usage: ChatGenerationTokenUsage$inboundSchema.optional(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "system_fingerprint": "systemFingerprint", + system_fingerprint: 'systemFingerprint', }); }); diff --git a/src/models/chatresponsechoice.ts b/src/models/chatresponsechoice.ts index cfbb8a52..f4003d64 100644 --- a/src/models/chatresponsechoice.ts +++ b/src/models/chatresponsechoice.ts @@ -3,24 +3,20 @@ * @generated-id: 7db13c3cc866 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { - AssistantMessage, - AssistantMessage$inboundSchema, -} from "./assistantmessage.js"; -import { - ChatCompletionFinishReason, - ChatCompletionFinishReason$inboundSchema, -} from "./chatcompletionfinishreason.js"; -import { - ChatMessageTokenLogprobs, - ChatMessageTokenLogprobs$inboundSchema, -} from "./chatmessagetokenlogprobs.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { Schema3, Schema3$inboundSchema } from "./schema3.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { AssistantMessage } from './assistantmessage.js'; +import type { ChatCompletionFinishReason } from './chatcompletionfinishreason.js'; +import type { ChatMessageTokenLogprobs } from './chatmessagetokenlogprobs.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { Schema3 } from './schema3.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { AssistantMessage$inboundSchema } from './assistantmessage.js'; +import { ChatCompletionFinishReason$inboundSchema } from './chatcompletionfinishreason.js'; +import { ChatMessageTokenLogprobs$inboundSchema } from './chatmessagetokenlogprobs.js'; +import { Schema3$inboundSchema } from './schema3.js'; export type ChatResponseChoice = { finishReason: ChatCompletionFinishReason | null; @@ -31,21 +27,20 @@ export type ChatResponseChoice = { }; /** @internal */ -export const ChatResponseChoice$inboundSchema: z.ZodType< - ChatResponseChoice, - unknown -> = z.object({ - finish_reason: z.nullable(ChatCompletionFinishReason$inboundSchema), - index: z.number(), - message: AssistantMessage$inboundSchema, - reasoning_details: z.array(Schema3$inboundSchema).optional(), - logprobs: z.nullable(ChatMessageTokenLogprobs$inboundSchema).optional(), -}).transform((v) => { - return remap$(v, { - "finish_reason": "finishReason", - "reasoning_details": "reasoningDetails", +export const ChatResponseChoice$inboundSchema: z.ZodType = z + .object({ + finish_reason: z.nullable(ChatCompletionFinishReason$inboundSchema), + index: z.number(), + message: AssistantMessage$inboundSchema, + reasoning_details: z.array(Schema3$inboundSchema).optional(), + logprobs: z.nullable(ChatMessageTokenLogprobs$inboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + finish_reason: 'finishReason', + reasoning_details: 'reasoningDetails', + }); }); -}); export function chatResponseChoiceFromJSON( jsonString: string, diff --git a/src/models/chatstreamingchoice.ts b/src/models/chatstreamingchoice.ts index 43fa1d4c..8b4edb71 100644 --- a/src/models/chatstreamingchoice.ts +++ b/src/models/chatstreamingchoice.ts @@ -3,23 +3,18 @@ * @generated-id: 15346f0b1bc4 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { - ChatCompletionFinishReason, - ChatCompletionFinishReason$inboundSchema, -} from "./chatcompletionfinishreason.js"; -import { - ChatMessageTokenLogprobs, - ChatMessageTokenLogprobs$inboundSchema, -} from "./chatmessagetokenlogprobs.js"; -import { - ChatStreamingMessageChunk, - ChatStreamingMessageChunk$inboundSchema, -} from "./chatstreamingmessagechunk.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { ChatCompletionFinishReason } from './chatcompletionfinishreason.js'; +import type { ChatMessageTokenLogprobs } from './chatmessagetokenlogprobs.js'; +import type { ChatStreamingMessageChunk } from './chatstreamingmessagechunk.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { ChatCompletionFinishReason$inboundSchema } from './chatcompletionfinishreason.js'; +import { ChatMessageTokenLogprobs$inboundSchema } from './chatmessagetokenlogprobs.js'; +import { ChatStreamingMessageChunk$inboundSchema } from './chatstreamingmessagechunk.js'; export type ChatStreamingChoice = { delta: ChatStreamingMessageChunk; @@ -29,19 +24,18 @@ export type ChatStreamingChoice = { }; /** @internal */ -export const ChatStreamingChoice$inboundSchema: z.ZodType< - ChatStreamingChoice, - unknown -> = z.object({ - delta: ChatStreamingMessageChunk$inboundSchema, - finish_reason: z.nullable(ChatCompletionFinishReason$inboundSchema), - index: z.number(), - logprobs: z.nullable(ChatMessageTokenLogprobs$inboundSchema).optional(), -}).transform((v) => { - return remap$(v, { - "finish_reason": "finishReason", +export const ChatStreamingChoice$inboundSchema: z.ZodType = z + .object({ + delta: ChatStreamingMessageChunk$inboundSchema, + finish_reason: z.nullable(ChatCompletionFinishReason$inboundSchema), + index: z.number(), + logprobs: z.nullable(ChatMessageTokenLogprobs$inboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + finish_reason: 'finishReason', + }); }); -}); export function chatStreamingChoiceFromJSON( jsonString: string, diff --git a/src/models/chatstreamingmessagechunk.ts b/src/models/chatstreamingmessagechunk.ts index 9e132964..dcb992fe 100644 --- a/src/models/chatstreamingmessagechunk.ts +++ b/src/models/chatstreamingmessagechunk.ts @@ -3,24 +3,22 @@ * @generated-id: 339ee7e4b920 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { - ChatStreamingMessageToolCall, - ChatStreamingMessageToolCall$inboundSchema, -} from "./chatstreamingmessagetoolcall.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { Schema3, Schema3$inboundSchema } from "./schema3.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { ChatStreamingMessageToolCall } from './chatstreamingmessagetoolcall.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { Schema3 } from './schema3.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { ChatStreamingMessageToolCall$inboundSchema } from './chatstreamingmessagetoolcall.js'; +import { Schema3$inboundSchema } from './schema3.js'; export const ChatStreamingMessageChunkRole = { - Assistant: "assistant", + Assistant: 'assistant', } as const; -export type ChatStreamingMessageChunkRole = ClosedEnum< - typeof ChatStreamingMessageChunkRole ->; +export type ChatStreamingMessageChunkRole = ClosedEnum; export type ChatStreamingMessageChunk = { role?: ChatStreamingMessageChunkRole | undefined; @@ -40,19 +38,21 @@ export const ChatStreamingMessageChunkRole$inboundSchema: z.ZodEnum< export const ChatStreamingMessageChunk$inboundSchema: z.ZodType< ChatStreamingMessageChunk, unknown -> = z.object({ - role: ChatStreamingMessageChunkRole$inboundSchema.optional(), - content: z.nullable(z.string()).optional(), - reasoning: z.nullable(z.string()).optional(), - refusal: z.nullable(z.string()).optional(), - tool_calls: z.array(ChatStreamingMessageToolCall$inboundSchema).optional(), - reasoning_details: z.array(Schema3$inboundSchema).optional(), -}).transform((v) => { - return remap$(v, { - "tool_calls": "toolCalls", - "reasoning_details": "reasoningDetails", +> = z + .object({ + role: ChatStreamingMessageChunkRole$inboundSchema.optional(), + content: z.nullable(z.string()).optional(), + reasoning: z.nullable(z.string()).optional(), + refusal: z.nullable(z.string()).optional(), + tool_calls: z.array(ChatStreamingMessageToolCall$inboundSchema).optional(), + reasoning_details: z.array(Schema3$inboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + tool_calls: 'toolCalls', + reasoning_details: 'reasoningDetails', + }); }); -}); export function chatStreamingMessageChunkFromJSON( jsonString: string, diff --git a/src/models/chatstreamingmessagetoolcall.ts b/src/models/chatstreamingmessagetoolcall.ts index fc2c3662..ba55a4cf 100644 --- a/src/models/chatstreamingmessagetoolcall.ts +++ b/src/models/chatstreamingmessagetoolcall.ts @@ -3,10 +3,11 @@ * @generated-id: 74ba154581ba */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; export type ChatStreamingMessageToolCallFunction = { name?: string | undefined; @@ -16,7 +17,7 @@ export type ChatStreamingMessageToolCallFunction = { export type ChatStreamingMessageToolCall = { index: number; id?: string | undefined; - type?: "function" | undefined; + type?: 'function' | undefined; function?: ChatStreamingMessageToolCallFunction | undefined; }; @@ -34,8 +35,7 @@ export function chatStreamingMessageToolCallFunctionFromJSON( ): SafeParseResult { return safeParse( jsonString, - (x) => - ChatStreamingMessageToolCallFunction$inboundSchema.parse(JSON.parse(x)), + (x) => ChatStreamingMessageToolCallFunction$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'ChatStreamingMessageToolCallFunction' from JSON`, ); } @@ -47,9 +47,8 @@ export const ChatStreamingMessageToolCall$inboundSchema: z.ZodType< > = z.object({ index: z.number(), id: z.string().optional(), - type: z.literal("function").optional(), - function: z.lazy(() => ChatStreamingMessageToolCallFunction$inboundSchema) - .optional(), + type: z.literal('function').optional(), + function: z.lazy(() => ChatStreamingMessageToolCallFunction$inboundSchema).optional(), }); export function chatStreamingMessageToolCallFromJSON( diff --git a/src/models/chatstreamingresponsechunk.ts b/src/models/chatstreamingresponsechunk.ts index b3e9a660..62af4f21 100644 --- a/src/models/chatstreamingresponsechunk.ts +++ b/src/models/chatstreamingresponsechunk.ts @@ -3,19 +3,16 @@ * @generated-id: 00bf2ea52439 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { - ChatGenerationTokenUsage, - ChatGenerationTokenUsage$inboundSchema, -} from "./chatgenerationtokenusage.js"; -import { - ChatStreamingChoice, - ChatStreamingChoice$inboundSchema, -} from "./chatstreamingchoice.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { ChatGenerationTokenUsage } from './chatgenerationtokenusage.js'; +import type { ChatStreamingChoice } from './chatstreamingchoice.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { ChatGenerationTokenUsage$inboundSchema } from './chatgenerationtokenusage.js'; +import { ChatStreamingChoice$inboundSchema } from './chatstreamingchoice.js'; export type ChatStreamingResponseChunkError = { message: string; @@ -27,7 +24,7 @@ export type ChatStreamingResponseChunkData = { choices: Array; created: number; model: string; - object: "chat.completion.chunk"; + object: 'chat.completion.chunk'; systemFingerprint?: string | null | undefined; error?: ChatStreamingResponseChunkError | undefined; usage?: ChatGenerationTokenUsage | undefined; @@ -60,20 +57,22 @@ export function chatStreamingResponseChunkErrorFromJSON( export const ChatStreamingResponseChunkData$inboundSchema: z.ZodType< ChatStreamingResponseChunkData, unknown -> = z.object({ - id: z.string(), - choices: z.array(ChatStreamingChoice$inboundSchema), - created: z.number(), - model: z.string(), - object: z.literal("chat.completion.chunk"), - system_fingerprint: z.nullable(z.string()).optional(), - error: z.lazy(() => ChatStreamingResponseChunkError$inboundSchema).optional(), - usage: ChatGenerationTokenUsage$inboundSchema.optional(), -}).transform((v) => { - return remap$(v, { - "system_fingerprint": "systemFingerprint", +> = z + .object({ + id: z.string(), + choices: z.array(ChatStreamingChoice$inboundSchema), + created: z.number(), + model: z.string(), + object: z.literal('chat.completion.chunk'), + system_fingerprint: z.nullable(z.string()).optional(), + error: z.lazy(() => ChatStreamingResponseChunkError$inboundSchema).optional(), + usage: ChatGenerationTokenUsage$inboundSchema.optional(), + }) + .transform((v) => { + return remap$(v, { + system_fingerprint: 'systemFingerprint', + }); }); -}); export function chatStreamingResponseChunkDataFromJSON( jsonString: string, @@ -90,18 +89,21 @@ export const ChatStreamingResponseChunk$inboundSchema: z.ZodType< ChatStreamingResponseChunk, unknown > = z.object({ - data: z.string().transform((v, ctx) => { - try { - return JSON.parse(v); - } catch (err) { - ctx.addIssue({ - input: v, - code: "custom", - message: `malformed json: ${err}`, - }); - return z.NEVER; - } - }).pipe(z.lazy(() => ChatStreamingResponseChunkData$inboundSchema)), + data: z + .string() + .transform((v, ctx) => { + try { + return JSON.parse(v); + } catch (err) { + ctx.addIssue({ + input: v, + code: 'custom', + message: `malformed json: ${err}`, + }); + return z.NEVER; + } + }) + .pipe(z.lazy(() => ChatStreamingResponseChunkData$inboundSchema)), }); export function chatStreamingResponseChunkFromJSON( diff --git a/src/models/chatstreamoptions.ts b/src/models/chatstreamoptions.ts index aee57eed..06163fa6 100644 --- a/src/models/chatstreamoptions.ts +++ b/src/models/chatstreamoptions.ts @@ -3,8 +3,8 @@ * @generated-id: 83ba1c3db4bb */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; export type ChatStreamOptions = { includeUsage?: boolean | undefined; @@ -19,18 +19,16 @@ export type ChatStreamOptions$Outbound = { export const ChatStreamOptions$outboundSchema: z.ZodType< ChatStreamOptions$Outbound, ChatStreamOptions -> = z.object({ - includeUsage: z.boolean().optional(), -}).transform((v) => { - return remap$(v, { - includeUsage: "include_usage", +> = z + .object({ + includeUsage: z.boolean().optional(), + }) + .transform((v) => { + return remap$(v, { + includeUsage: 'include_usage', + }); }); -}); -export function chatStreamOptionsToJSON( - chatStreamOptions: ChatStreamOptions, -): string { - return JSON.stringify( - ChatStreamOptions$outboundSchema.parse(chatStreamOptions), - ); +export function chatStreamOptionsToJSON(chatStreamOptions: ChatStreamOptions): string { + return JSON.stringify(ChatStreamOptions$outboundSchema.parse(chatStreamOptions)); } diff --git a/src/models/claude-message.ts b/src/models/claude-message.ts index d714c97e..1c1136d3 100644 --- a/src/models/claude-message.ts +++ b/src/models/claude-message.ts @@ -7,18 +7,18 @@ * Reason why the model stopped generating. */ export type ClaudeStopReason = - | "end_turn" - | "max_tokens" - | "stop_sequence" - | "tool_use" - | "pause_turn" - | "refusal"; + | 'end_turn' + | 'max_tokens' + | 'stop_sequence' + | 'tool_use' + | 'pause_turn' + | 'refusal'; /** * Character-level citation location within a document. */ export type ClaudeCitationCharLocation = { - type: "char_location"; + type: 'char_location'; cited_text: string; document_index: number; document_title: string; @@ -31,7 +31,7 @@ export type ClaudeCitationCharLocation = { * Page-level citation location within a document. */ export type ClaudeCitationPageLocation = { - type: "page_location"; + type: 'page_location'; cited_text: string; document_index: number; document_title: string; @@ -44,7 +44,7 @@ export type ClaudeCitationPageLocation = { * Content block citation location within a document. */ export type ClaudeCitationContentBlockLocation = { - type: "content_block_location"; + type: 'content_block_location'; cited_text: string; document_index: number; document_title: string; @@ -57,7 +57,7 @@ export type ClaudeCitationContentBlockLocation = { * Web search result citation location. */ export type ClaudeCitationWebSearchResultLocation = { - type: "web_search_result_location"; + type: 'web_search_result_location'; cited_text: string; title: string; url: string; @@ -68,7 +68,7 @@ export type ClaudeCitationWebSearchResultLocation = { * Search result citation location. */ export type ClaudeCitationSearchResultLocation = { - type: "search_result_location"; + type: 'search_result_location'; cited_text: string; title: string; source: string; @@ -91,7 +91,7 @@ export type ClaudeTextCitation = * Text content block. */ export type ClaudeTextBlock = { - type: "text"; + type: 'text'; text: string; citations?: ClaudeTextCitation[]; }; @@ -100,7 +100,7 @@ export type ClaudeTextBlock = { * Extended thinking content block. */ export type ClaudeThinkingBlock = { - type: "thinking"; + type: 'thinking'; thinking: string; signature: string; }; @@ -109,7 +109,7 @@ export type ClaudeThinkingBlock = { * Redacted thinking content block. */ export type ClaudeRedactedThinkingBlock = { - type: "redacted_thinking"; + type: 'redacted_thinking'; data: string; }; @@ -117,7 +117,7 @@ export type ClaudeRedactedThinkingBlock = { * Tool use content block. */ export type ClaudeToolUseBlock = { - type: "tool_use"; + type: 'tool_use'; id: string; name: string; input: Record; @@ -127,9 +127,9 @@ export type ClaudeToolUseBlock = { * Server-side tool use content block (e.g., web_search). */ export type ClaudeServerToolUseBlock = { - type: "server_tool_use"; + type: 'server_tool_use'; id: string; - name: "web_search"; + name: 'web_search'; input: Record; }; @@ -159,8 +159,8 @@ export type ClaudeUsage = { */ export type ClaudeMessage = { id: string; - type: "message"; - role: "assistant"; + type: 'message'; + role: 'assistant'; model: string; content: ClaudeContentBlock[]; stop_reason: ClaudeStopReason | null; @@ -177,14 +177,14 @@ export type ClaudeMessage = { * Cache control for prompt caching. */ export type ClaudeCacheControl = { - type: "ephemeral"; + type: 'ephemeral'; }; /** * Text content block parameter for input. */ export type ClaudeTextBlockParam = { - type: "text"; + type: 'text'; text: string; cache_control?: ClaudeCacheControl | null; }; @@ -193,8 +193,8 @@ export type ClaudeTextBlockParam = { * Base64-encoded image source. */ export type ClaudeBase64ImageSource = { - type: "base64"; - media_type: "image/jpeg" | "image/png" | "image/gif" | "image/webp"; + type: 'base64'; + media_type: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp'; data: string; }; @@ -202,7 +202,7 @@ export type ClaudeBase64ImageSource = { * URL-based image source. */ export type ClaudeURLImageSource = { - type: "url"; + type: 'url'; url: string; }; @@ -210,7 +210,7 @@ export type ClaudeURLImageSource = { * Image content block parameter for input. */ export type ClaudeImageBlockParam = { - type: "image"; + type: 'image'; source: ClaudeBase64ImageSource | ClaudeURLImageSource; cache_control?: ClaudeCacheControl | null; }; @@ -219,7 +219,7 @@ export type ClaudeImageBlockParam = { * Tool use content block parameter for input (when passing assistant's tool use back). */ export type ClaudeToolUseBlockParam = { - type: "tool_use"; + type: 'tool_use'; id: string; name: string; input: Record; @@ -230,7 +230,7 @@ export type ClaudeToolUseBlockParam = { * Tool result content block parameter for input. */ export type ClaudeToolResultBlockParam = { - type: "tool_result"; + type: 'tool_result'; tool_use_id: string; content: string | Array; is_error?: boolean; @@ -251,7 +251,7 @@ export type ClaudeContentBlockParam = * This represents a message in a conversation for the Claude API. */ export type ClaudeMessageParam = { - role: "user" | "assistant"; + role: 'user' | 'assistant'; content: string | Array; }; diff --git a/src/models/completionchoice.ts b/src/models/completionchoice.ts index db6b2a5d..2d6a2339 100644 --- a/src/models/completionchoice.ts +++ b/src/models/completionchoice.ts @@ -3,22 +3,21 @@ * @generated-id: 86092a0ff4c4 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { - CompletionLogprobs, - CompletionLogprobs$inboundSchema, -} from "./completionlogprobs.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { OpenEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { CompletionLogprobs } from './completionlogprobs.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import * as openEnums from '../types/enums.js'; +import { CompletionLogprobs$inboundSchema } from './completionlogprobs.js'; export const CompletionFinishReason = { - Stop: "stop", - Length: "length", - ContentFilter: "content_filter", + Stop: 'stop', + Length: 'length', + ContentFilter: 'content_filter', } as const; export type CompletionFinishReason = OpenEnum; @@ -32,28 +31,25 @@ export type CompletionChoice = { }; /** @internal */ -export const CompletionFinishReason$inboundSchema: z.ZodType< - CompletionFinishReason, - unknown -> = openEnums.inboundSchema(CompletionFinishReason); +export const CompletionFinishReason$inboundSchema: z.ZodType = + openEnums.inboundSchema(CompletionFinishReason); /** @internal */ -export const CompletionChoice$inboundSchema: z.ZodType< - CompletionChoice, - unknown -> = z.object({ - text: z.string(), - index: z.number(), - logprobs: z.nullable(CompletionLogprobs$inboundSchema), - finish_reason: z.nullable(CompletionFinishReason$inboundSchema), - native_finish_reason: z.string().optional(), - reasoning: z.nullable(z.string()).optional(), -}).transform((v) => { - return remap$(v, { - "finish_reason": "finishReason", - "native_finish_reason": "nativeFinishReason", +export const CompletionChoice$inboundSchema: z.ZodType = z + .object({ + text: z.string(), + index: z.number(), + logprobs: z.nullable(CompletionLogprobs$inboundSchema), + finish_reason: z.nullable(CompletionFinishReason$inboundSchema), + native_finish_reason: z.string().optional(), + reasoning: z.nullable(z.string()).optional(), + }) + .transform((v) => { + return remap$(v, { + finish_reason: 'finishReason', + native_finish_reason: 'nativeFinishReason', + }); }); -}); export function completionChoiceFromJSON( jsonString: string, diff --git a/src/models/completioncreateparams.ts b/src/models/completioncreateparams.ts index 0c5a338c..9cadce3e 100644 --- a/src/models/completioncreateparams.ts +++ b/src/models/completioncreateparams.ts @@ -3,24 +3,21 @@ * @generated-id: 44cc0c9c4c06 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { +import type { ResponseFormatJSONSchema, ResponseFormatJSONSchema$Outbound, - ResponseFormatJSONSchema$outboundSchema, -} from "./responseformatjsonschema.js"; -import { +} from './responseformatjsonschema.js'; +import type { ResponseFormatTextGrammar, ResponseFormatTextGrammar$Outbound, - ResponseFormatTextGrammar$outboundSchema, -} from "./responseformattextgrammar.js"; +} from './responseformattextgrammar.js'; -export type Prompt = - | string - | Array - | Array - | Array>; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { ResponseFormatJSONSchema$outboundSchema } from './responseformatjsonschema.js'; +import { ResponseFormatTextGrammar$outboundSchema } from './responseformattextgrammar.js'; + +export type Prompt = string | Array | Array | Array>; export type CompletionCreateParamsStop = string | Array; @@ -29,15 +26,15 @@ export type StreamOptions = { }; export type CompletionCreateParamsResponseFormatPython = { - type: "python"; + type: 'python'; }; export type CompletionCreateParamsResponseFormatJSONObject = { - type: "json_object"; + type: 'json_object'; }; export type CompletionCreateParamsResponseFormatText = { - type: "text"; + type: 'text'; }; export type CompletionCreateParamsResponseFormatUnion = @@ -54,7 +51,12 @@ export type CompletionCreateParams = { bestOf?: number | null | undefined; echo?: boolean | null | undefined; frequencyPenalty?: number | null | undefined; - logitBias?: { [k: string]: number } | null | undefined; + logitBias?: + | { + [k: string]: number; + } + | null + | undefined; logprobs?: number | null | undefined; maxTokens?: number | null | undefined; n?: number | null | undefined; @@ -67,7 +69,12 @@ export type CompletionCreateParams = { temperature?: number | null | undefined; topP?: number | null | undefined; user?: string | undefined; - metadata?: { [k: string]: string } | null | undefined; + metadata?: + | { + [k: string]: string; + } + | null + | undefined; responseFormat?: | CompletionCreateParamsResponseFormatText | CompletionCreateParamsResponseFormatJSONObject @@ -79,20 +86,15 @@ export type CompletionCreateParams = { }; /** @internal */ -export type Prompt$Outbound = - | string - | Array - | Array - | Array>; +export type Prompt$Outbound = string | Array | Array | Array>; /** @internal */ -export const Prompt$outboundSchema: z.ZodType = z - .union([ - z.string(), - z.array(z.string()), - z.array(z.number()), - z.array(z.array(z.number())), - ]); +export const Prompt$outboundSchema: z.ZodType = z.union([ + z.string(), + z.array(z.string()), + z.array(z.number()), + z.array(z.array(z.number())), +]); export function promptToJSON(prompt: Prompt): string { return JSON.stringify(Prompt$outboundSchema.parse(prompt)); @@ -105,7 +107,10 @@ export type CompletionCreateParamsStop$Outbound = string | Array; export const CompletionCreateParamsStop$outboundSchema: z.ZodType< CompletionCreateParamsStop$Outbound, CompletionCreateParamsStop -> = z.union([z.string(), z.array(z.string())]); +> = z.union([ + z.string(), + z.array(z.string()), +]); export function completionCreateParamsStopToJSON( completionCreateParamsStop: CompletionCreateParamsStop, @@ -121,16 +126,15 @@ export type StreamOptions$Outbound = { }; /** @internal */ -export const StreamOptions$outboundSchema: z.ZodType< - StreamOptions$Outbound, - StreamOptions -> = z.object({ - includeUsage: z.nullable(z.boolean()).optional(), -}).transform((v) => { - return remap$(v, { - includeUsage: "include_usage", +export const StreamOptions$outboundSchema: z.ZodType = z + .object({ + includeUsage: z.nullable(z.boolean()).optional(), + }) + .transform((v) => { + return remap$(v, { + includeUsage: 'include_usage', + }); }); -}); export function streamOptionsToJSON(streamOptions: StreamOptions): string { return JSON.stringify(StreamOptions$outboundSchema.parse(streamOptions)); @@ -138,21 +142,19 @@ export function streamOptionsToJSON(streamOptions: StreamOptions): string { /** @internal */ export type CompletionCreateParamsResponseFormatPython$Outbound = { - type: "python"; + type: 'python'; }; /** @internal */ -export const CompletionCreateParamsResponseFormatPython$outboundSchema: - z.ZodType< - CompletionCreateParamsResponseFormatPython$Outbound, - CompletionCreateParamsResponseFormatPython - > = z.object({ - type: z.literal("python"), - }); +export const CompletionCreateParamsResponseFormatPython$outboundSchema: z.ZodType< + CompletionCreateParamsResponseFormatPython$Outbound, + CompletionCreateParamsResponseFormatPython +> = z.object({ + type: z.literal('python'), +}); export function completionCreateParamsResponseFormatPythonToJSON( - completionCreateParamsResponseFormatPython: - CompletionCreateParamsResponseFormatPython, + completionCreateParamsResponseFormatPython: CompletionCreateParamsResponseFormatPython, ): string { return JSON.stringify( CompletionCreateParamsResponseFormatPython$outboundSchema.parse( @@ -163,21 +165,19 @@ export function completionCreateParamsResponseFormatPythonToJSON( /** @internal */ export type CompletionCreateParamsResponseFormatJSONObject$Outbound = { - type: "json_object"; + type: 'json_object'; }; /** @internal */ -export const CompletionCreateParamsResponseFormatJSONObject$outboundSchema: - z.ZodType< - CompletionCreateParamsResponseFormatJSONObject$Outbound, - CompletionCreateParamsResponseFormatJSONObject - > = z.object({ - type: z.literal("json_object"), - }); +export const CompletionCreateParamsResponseFormatJSONObject$outboundSchema: z.ZodType< + CompletionCreateParamsResponseFormatJSONObject$Outbound, + CompletionCreateParamsResponseFormatJSONObject +> = z.object({ + type: z.literal('json_object'), +}); export function completionCreateParamsResponseFormatJSONObjectToJSON( - completionCreateParamsResponseFormatJSONObject: - CompletionCreateParamsResponseFormatJSONObject, + completionCreateParamsResponseFormatJSONObject: CompletionCreateParamsResponseFormatJSONObject, ): string { return JSON.stringify( CompletionCreateParamsResponseFormatJSONObject$outboundSchema.parse( @@ -188,7 +188,7 @@ export function completionCreateParamsResponseFormatJSONObjectToJSON( /** @internal */ export type CompletionCreateParamsResponseFormatText$Outbound = { - type: "text"; + type: 'text'; }; /** @internal */ @@ -196,12 +196,11 @@ export const CompletionCreateParamsResponseFormatText$outboundSchema: z.ZodType< CompletionCreateParamsResponseFormatText$Outbound, CompletionCreateParamsResponseFormatText > = z.object({ - type: z.literal("text"), + type: z.literal('text'), }); export function completionCreateParamsResponseFormatTextToJSON( - completionCreateParamsResponseFormatText: - CompletionCreateParamsResponseFormatText, + completionCreateParamsResponseFormatText: CompletionCreateParamsResponseFormatText, ): string { return JSON.stringify( CompletionCreateParamsResponseFormatText$outboundSchema.parse( @@ -219,21 +218,19 @@ export type CompletionCreateParamsResponseFormatUnion$Outbound = | CompletionCreateParamsResponseFormatPython$Outbound; /** @internal */ -export const CompletionCreateParamsResponseFormatUnion$outboundSchema: - z.ZodType< - CompletionCreateParamsResponseFormatUnion$Outbound, - CompletionCreateParamsResponseFormatUnion - > = z.union([ - z.lazy(() => CompletionCreateParamsResponseFormatText$outboundSchema), - z.lazy(() => CompletionCreateParamsResponseFormatJSONObject$outboundSchema), - ResponseFormatJSONSchema$outboundSchema, - ResponseFormatTextGrammar$outboundSchema, - z.lazy(() => CompletionCreateParamsResponseFormatPython$outboundSchema), - ]); +export const CompletionCreateParamsResponseFormatUnion$outboundSchema: z.ZodType< + CompletionCreateParamsResponseFormatUnion$Outbound, + CompletionCreateParamsResponseFormatUnion +> = z.union([ + z.lazy(() => CompletionCreateParamsResponseFormatText$outboundSchema), + z.lazy(() => CompletionCreateParamsResponseFormatJSONObject$outboundSchema), + ResponseFormatJSONSchema$outboundSchema, + ResponseFormatTextGrammar$outboundSchema, + z.lazy(() => CompletionCreateParamsResponseFormatPython$outboundSchema), +]); export function completionCreateParamsResponseFormatUnionToJSON( - completionCreateParamsResponseFormatUnion: - CompletionCreateParamsResponseFormatUnion, + completionCreateParamsResponseFormatUnion: CompletionCreateParamsResponseFormatUnion, ): string { return JSON.stringify( CompletionCreateParamsResponseFormatUnion$outboundSchema.parse( @@ -250,7 +247,12 @@ export type CompletionCreateParams$Outbound = { best_of?: number | null | undefined; echo?: boolean | null | undefined; frequency_penalty?: number | null | undefined; - logit_bias?: { [k: string]: number } | null | undefined; + logit_bias?: + | { + [k: string]: number; + } + | null + | undefined; logprobs?: number | null | undefined; max_tokens?: number | null | undefined; n?: number | null | undefined; @@ -263,7 +265,12 @@ export type CompletionCreateParams$Outbound = { temperature?: number | null | undefined; top_p?: number | null | undefined; user?: string | undefined; - metadata?: { [k: string]: string } | null | undefined; + metadata?: + | { + [k: string]: string; + } + | null + | undefined; response_format?: | CompletionCreateParamsResponseFormatText$Outbound | CompletionCreateParamsResponseFormatJSONObject$Outbound @@ -278,61 +285,67 @@ export type CompletionCreateParams$Outbound = { export const CompletionCreateParams$outboundSchema: z.ZodType< CompletionCreateParams$Outbound, CompletionCreateParams -> = z.object({ - model: z.string().optional(), - models: z.array(z.string()).optional(), - prompt: z.union([ - z.string(), - z.array(z.string()), - z.array(z.number()), - z.array(z.array(z.number())), - ]), - bestOf: z.nullable(z.int()).optional(), - echo: z.nullable(z.boolean()).optional(), - frequencyPenalty: z.nullable(z.number()).optional(), - logitBias: z.nullable(z.record(z.string(), z.number())).optional(), - logprobs: z.nullable(z.int()).optional(), - maxTokens: z.nullable(z.int()).optional(), - n: z.nullable(z.int()).optional(), - presencePenalty: z.nullable(z.number()).optional(), - seed: z.nullable(z.int()).optional(), - stop: z.nullable(z.union([z.string(), z.array(z.string())])).optional(), - stream: z.boolean().default(false), - streamOptions: z.nullable(z.lazy(() => StreamOptions$outboundSchema)) - .optional(), - suffix: z.nullable(z.string()).optional(), - temperature: z.nullable(z.number()).optional(), - topP: z.nullable(z.number()).optional(), - user: z.string().optional(), - metadata: z.nullable(z.record(z.string(), z.string())).optional(), - responseFormat: z.nullable( - z.union([ - z.lazy(() => CompletionCreateParamsResponseFormatText$outboundSchema), - z.lazy(() => - CompletionCreateParamsResponseFormatJSONObject$outboundSchema - ), - ResponseFormatJSONSchema$outboundSchema, - ResponseFormatTextGrammar$outboundSchema, - z.lazy(() => CompletionCreateParamsResponseFormatPython$outboundSchema), +> = z + .object({ + model: z.string().optional(), + models: z.array(z.string()).optional(), + prompt: z.union([ + z.string(), + z.array(z.string()), + z.array(z.number()), + z.array(z.array(z.number())), ]), - ).optional(), -}).transform((v) => { - return remap$(v, { - bestOf: "best_of", - frequencyPenalty: "frequency_penalty", - logitBias: "logit_bias", - maxTokens: "max_tokens", - presencePenalty: "presence_penalty", - streamOptions: "stream_options", - topP: "top_p", - responseFormat: "response_format", + bestOf: z.nullable(z.int()).optional(), + echo: z.nullable(z.boolean()).optional(), + frequencyPenalty: z.nullable(z.number()).optional(), + logitBias: z.nullable(z.record(z.string(), z.number())).optional(), + logprobs: z.nullable(z.int()).optional(), + maxTokens: z.nullable(z.int()).optional(), + n: z.nullable(z.int()).optional(), + presencePenalty: z.nullable(z.number()).optional(), + seed: z.nullable(z.int()).optional(), + stop: z + .nullable( + z.union([ + z.string(), + z.array(z.string()), + ]), + ) + .optional(), + stream: z.boolean().default(false), + streamOptions: z.nullable(z.lazy(() => StreamOptions$outboundSchema)).optional(), + suffix: z.nullable(z.string()).optional(), + temperature: z.nullable(z.number()).optional(), + topP: z.nullable(z.number()).optional(), + user: z.string().optional(), + metadata: z.nullable(z.record(z.string(), z.string())).optional(), + responseFormat: z + .nullable( + z.union([ + z.lazy(() => CompletionCreateParamsResponseFormatText$outboundSchema), + z.lazy(() => CompletionCreateParamsResponseFormatJSONObject$outboundSchema), + ResponseFormatJSONSchema$outboundSchema, + ResponseFormatTextGrammar$outboundSchema, + z.lazy(() => CompletionCreateParamsResponseFormatPython$outboundSchema), + ]), + ) + .optional(), + }) + .transform((v) => { + return remap$(v, { + bestOf: 'best_of', + frequencyPenalty: 'frequency_penalty', + logitBias: 'logit_bias', + maxTokens: 'max_tokens', + presencePenalty: 'presence_penalty', + streamOptions: 'stream_options', + topP: 'top_p', + responseFormat: 'response_format', + }); }); -}); export function completionCreateParamsToJSON( completionCreateParams: CompletionCreateParams, ): string { - return JSON.stringify( - CompletionCreateParams$outboundSchema.parse(completionCreateParams), - ); + return JSON.stringify(CompletionCreateParams$outboundSchema.parse(completionCreateParams)); } diff --git a/src/models/completionlogprobs.ts b/src/models/completionlogprobs.ts index 17fb1848..af2258cf 100644 --- a/src/models/completionlogprobs.ts +++ b/src/models/completionlogprobs.ts @@ -3,35 +3,37 @@ * @generated-id: b6552175348e */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; export type CompletionLogprobs = { tokens: Array; tokenLogprobs: Array; - topLogprobs: Array<{ [k: string]: number }> | null; + topLogprobs: Array<{ + [k: string]: number; + }> | null; textOffset: Array; }; /** @internal */ -export const CompletionLogprobs$inboundSchema: z.ZodType< - CompletionLogprobs, - unknown -> = z.object({ - tokens: z.array(z.string()), - token_logprobs: z.array(z.number()), - top_logprobs: z.nullable(z.array(z.record(z.string(), z.number()))), - text_offset: z.array(z.number()), -}).transform((v) => { - return remap$(v, { - "token_logprobs": "tokenLogprobs", - "top_logprobs": "topLogprobs", - "text_offset": "textOffset", +export const CompletionLogprobs$inboundSchema: z.ZodType = z + .object({ + tokens: z.array(z.string()), + token_logprobs: z.array(z.number()), + top_logprobs: z.nullable(z.array(z.record(z.string(), z.number()))), + text_offset: z.array(z.number()), + }) + .transform((v) => { + return remap$(v, { + token_logprobs: 'tokenLogprobs', + top_logprobs: 'topLogprobs', + text_offset: 'textOffset', + }); }); -}); export function completionLogprobsFromJSON( jsonString: string, diff --git a/src/models/completionresponse.ts b/src/models/completionresponse.ts index 242ad6bd..7dd41d50 100644 --- a/src/models/completionresponse.ts +++ b/src/models/completionresponse.ts @@ -3,23 +3,20 @@ * @generated-id: 316ab9f7e558 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { - CompletionChoice, - CompletionChoice$inboundSchema, -} from "./completionchoice.js"; -import { - CompletionUsage, - CompletionUsage$inboundSchema, -} from "./completionusage.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { CompletionChoice } from './completionchoice.js'; +import type { CompletionUsage } from './completionusage.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { CompletionChoice$inboundSchema } from './completionchoice.js'; +import { CompletionUsage$inboundSchema } from './completionusage.js'; export type CompletionResponse = { id: string; - object: "text_completion"; + object: 'text_completion'; created: number; model: string; provider?: string | undefined; @@ -29,23 +26,22 @@ export type CompletionResponse = { }; /** @internal */ -export const CompletionResponse$inboundSchema: z.ZodType< - CompletionResponse, - unknown -> = z.object({ - id: z.string(), - object: z.literal("text_completion"), - created: z.number(), - model: z.string(), - provider: z.string().optional(), - system_fingerprint: z.string().optional(), - choices: z.array(CompletionChoice$inboundSchema), - usage: CompletionUsage$inboundSchema.optional(), -}).transform((v) => { - return remap$(v, { - "system_fingerprint": "systemFingerprint", +export const CompletionResponse$inboundSchema: z.ZodType = z + .object({ + id: z.string(), + object: z.literal('text_completion'), + created: z.number(), + model: z.string(), + provider: z.string().optional(), + system_fingerprint: z.string().optional(), + choices: z.array(CompletionChoice$inboundSchema), + usage: CompletionUsage$inboundSchema.optional(), + }) + .transform((v) => { + return remap$(v, { + system_fingerprint: 'systemFingerprint', + }); }); -}); export function completionResponseFromJSON( jsonString: string, diff --git a/src/models/completionusage.ts b/src/models/completionusage.ts index d278ff1d..086c16c6 100644 --- a/src/models/completionusage.ts +++ b/src/models/completionusage.ts @@ -3,11 +3,12 @@ * @generated-id: 4a222248409d */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; export type CompletionUsage = { promptTokens: number; @@ -16,20 +17,19 @@ export type CompletionUsage = { }; /** @internal */ -export const CompletionUsage$inboundSchema: z.ZodType< - CompletionUsage, - unknown -> = z.object({ - prompt_tokens: z.number(), - completion_tokens: z.number(), - total_tokens: z.number(), -}).transform((v) => { - return remap$(v, { - "prompt_tokens": "promptTokens", - "completion_tokens": "completionTokens", - "total_tokens": "totalTokens", +export const CompletionUsage$inboundSchema: z.ZodType = z + .object({ + prompt_tokens: z.number(), + completion_tokens: z.number(), + total_tokens: z.number(), + }) + .transform((v) => { + return remap$(v, { + prompt_tokens: 'promptTokens', + completion_tokens: 'completionTokens', + total_tokens: 'totalTokens', + }); }); -}); export function completionUsageFromJSON( jsonString: string, diff --git a/src/models/createchargerequest.ts b/src/models/createchargerequest.ts index bd6860c3..7676ac0d 100644 --- a/src/models/createchargerequest.ts +++ b/src/models/createchargerequest.ts @@ -3,10 +3,11 @@ * @generated-id: c342dc72d1f4 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type { OpenEnum } from '../types/enums.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import * as openEnums from '../types/enums.js'; export const ChainId = { One: 1, @@ -25,8 +26,8 @@ export type CreateChargeRequest = { }; /** @internal */ -export const ChainId$outboundSchema: z.ZodType = openEnums - .outboundSchemaInt(ChainId); +export const ChainId$outboundSchema: z.ZodType = + openEnums.outboundSchemaInt(ChainId); /** @internal */ export type CreateChargeRequest$Outbound = { @@ -39,20 +40,18 @@ export type CreateChargeRequest$Outbound = { export const CreateChargeRequest$outboundSchema: z.ZodType< CreateChargeRequest$Outbound, CreateChargeRequest -> = z.object({ - amount: z.number(), - sender: z.string(), - chainId: ChainId$outboundSchema, -}).transform((v) => { - return remap$(v, { - chainId: "chain_id", +> = z + .object({ + amount: z.number(), + sender: z.string(), + chainId: ChainId$outboundSchema, + }) + .transform((v) => { + return remap$(v, { + chainId: 'chain_id', + }); }); -}); - -export function createChargeRequestToJSON( - createChargeRequest: CreateChargeRequest, -): string { - return JSON.stringify( - CreateChargeRequest$outboundSchema.parse(createChargeRequest), - ); + +export function createChargeRequestToJSON(createChargeRequest: CreateChargeRequest): string { + return JSON.stringify(CreateChargeRequest$outboundSchema.parse(createChargeRequest)); } diff --git a/src/models/datacollection.ts b/src/models/datacollection.ts index e075ba95..9f268b95 100644 --- a/src/models/datacollection.ts +++ b/src/models/datacollection.ts @@ -3,9 +3,10 @@ * @generated-id: fa417e9ad79a */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; /** * Data collection setting. If no available model provider meets the requirement, your request will return an error. @@ -16,8 +17,8 @@ import { OpenEnum } from "../types/enums.js"; * - deny: use only providers which do not collect user data. */ export const DataCollection = { - Deny: "deny", - Allow: "allow", + Deny: 'deny', + Allow: 'allow', } as const; /** * Data collection setting. If no available model provider meets the requirement, your request will return an error. diff --git a/src/models/defaultparameters.ts b/src/models/defaultparameters.ts index 25444216..880f0d8c 100644 --- a/src/models/defaultparameters.ts +++ b/src/models/defaultparameters.ts @@ -3,11 +3,12 @@ * @generated-id: 8da6fac53cb5 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * Default parameters for this model @@ -19,19 +20,18 @@ export type DefaultParameters = { }; /** @internal */ -export const DefaultParameters$inboundSchema: z.ZodType< - DefaultParameters, - unknown -> = z.object({ - temperature: z.nullable(z.number()).optional(), - top_p: z.nullable(z.number()).optional(), - frequency_penalty: z.nullable(z.number()).optional(), -}).transform((v) => { - return remap$(v, { - "top_p": "topP", - "frequency_penalty": "frequencyPenalty", +export const DefaultParameters$inboundSchema: z.ZodType = z + .object({ + temperature: z.nullable(z.number()).optional(), + top_p: z.nullable(z.number()).optional(), + frequency_penalty: z.nullable(z.number()).optional(), + }) + .transform((v) => { + return remap$(v, { + top_p: 'topP', + frequency_penalty: 'frequencyPenalty', + }); }); -}); export function defaultParametersFromJSON( jsonString: string, diff --git a/src/models/edgenetworktimeoutresponseerrordata.ts b/src/models/edgenetworktimeoutresponseerrordata.ts index 913dc5af..0ae8009a 100644 --- a/src/models/edgenetworktimeoutresponseerrordata.ts +++ b/src/models/edgenetworktimeoutresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: d86e84250105 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for EdgeNetworkTimeoutResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type EdgeNetworkTimeoutResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ @@ -32,8 +38,7 @@ export function edgeNetworkTimeoutResponseErrorDataFromJSON( ): SafeParseResult { return safeParse( jsonString, - (x) => - EdgeNetworkTimeoutResponseErrorData$inboundSchema.parse(JSON.parse(x)), + (x) => EdgeNetworkTimeoutResponseErrorData$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'EdgeNetworkTimeoutResponseErrorData' from JSON`, ); } diff --git a/src/models/endpointstatus.ts b/src/models/endpointstatus.ts index afd9fedd..abab782a 100644 --- a/src/models/endpointstatus.ts +++ b/src/models/endpointstatus.ts @@ -3,9 +3,10 @@ * @generated-id: 83efda25dcf0 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const EndpointStatus = { Zero: 0, diff --git a/src/models/errors/badgatewayresponseerror.ts b/src/models/errors/badgatewayresponseerror.ts index b958b87c..a519c995 100644 --- a/src/models/errors/badgatewayresponseerror.ts +++ b/src/models/errors/badgatewayresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: 6264bb9f01d6 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Bad Gateway - Provider/upstream API failure @@ -34,33 +34,34 @@ export class BadGatewayResponseError extends OpenRouterError { constructor( err: BadGatewayResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "BadGatewayResponseError"; + this.name = 'BadGatewayResponseError'; } } /** @internal */ -export const BadGatewayResponseError$inboundSchema: z.ZodType< - BadGatewayResponseError, - unknown -> = z.object({ - error: models.BadGatewayResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +export const BadGatewayResponseError$inboundSchema: z.ZodType = z + .object({ + error: models.BadGatewayResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new BadGatewayResponseError(remapped, { diff --git a/src/models/errors/badrequestresponseerror.ts b/src/models/errors/badrequestresponseerror.ts index 7d2b7ba7..ed0a624a 100644 --- a/src/models/errors/badrequestresponseerror.ts +++ b/src/models/errors/badrequestresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: beddfd22a313 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Bad Request - Invalid request parameters or malformed input @@ -34,33 +34,34 @@ export class BadRequestResponseError extends OpenRouterError { constructor( err: BadRequestResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "BadRequestResponseError"; + this.name = 'BadRequestResponseError'; } } /** @internal */ -export const BadRequestResponseError$inboundSchema: z.ZodType< - BadRequestResponseError, - unknown -> = z.object({ - error: models.BadRequestResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +export const BadRequestResponseError$inboundSchema: z.ZodType = z + .object({ + error: models.BadRequestResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new BadRequestResponseError(remapped, { diff --git a/src/models/errors/chaterror.ts b/src/models/errors/chaterror.ts index 33cb7e5a..1a7f1725 100644 --- a/src/models/errors/chaterror.ts +++ b/src/models/errors/chaterror.ts @@ -3,9 +3,9 @@ * @generated-id: a3b18e48f494 */ -import * as z from "zod/v4"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; export type ChatErrorData = { error: models.ChatErrorError; @@ -19,25 +19,29 @@ export class ChatError extends OpenRouterError { constructor( err: ChatErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; - this.name = "ChatError"; + this.name = 'ChatError'; } } /** @internal */ -export const ChatError$inboundSchema: z.ZodType = z.object({ - error: z.lazy(() => models.ChatErrorError$inboundSchema), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +export const ChatError$inboundSchema: z.ZodType = z + .object({ + error: z.lazy(() => models.ChatErrorError$inboundSchema), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { return new ChatError(v, { request: v.request$, diff --git a/src/models/errors/edgenetworktimeoutresponseerror.ts b/src/models/errors/edgenetworktimeoutresponseerror.ts index 6bd7dedf..aaeafd94 100644 --- a/src/models/errors/edgenetworktimeoutresponseerror.ts +++ b/src/models/errors/edgenetworktimeoutresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: da53f308c771 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Infrastructure Timeout - Provider request timed out at edge network @@ -34,16 +34,19 @@ export class EdgeNetworkTimeoutResponseError extends OpenRouterError { constructor( err: EdgeNetworkTimeoutResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "EdgeNetworkTimeoutResponseError"; + this.name = 'EdgeNetworkTimeoutResponseError'; } } @@ -51,16 +54,17 @@ export class EdgeNetworkTimeoutResponseError extends OpenRouterError { export const EdgeNetworkTimeoutResponseError$inboundSchema: z.ZodType< EdgeNetworkTimeoutResponseError, unknown -> = z.object({ - error: models.EdgeNetworkTimeoutResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +> = z + .object({ + error: models.EdgeNetworkTimeoutResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new EdgeNetworkTimeoutResponseError(remapped, { diff --git a/src/models/errors/forbiddenresponseerror.ts b/src/models/errors/forbiddenresponseerror.ts index 1d464f8b..1f36e10b 100644 --- a/src/models/errors/forbiddenresponseerror.ts +++ b/src/models/errors/forbiddenresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: d08a9d9ee588 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Forbidden - Authentication successful but insufficient permissions @@ -34,33 +34,34 @@ export class ForbiddenResponseError extends OpenRouterError { constructor( err: ForbiddenResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "ForbiddenResponseError"; + this.name = 'ForbiddenResponseError'; } } /** @internal */ -export const ForbiddenResponseError$inboundSchema: z.ZodType< - ForbiddenResponseError, - unknown -> = z.object({ - error: models.ForbiddenResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +export const ForbiddenResponseError$inboundSchema: z.ZodType = z + .object({ + error: models.ForbiddenResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new ForbiddenResponseError(remapped, { diff --git a/src/models/errors/httpclienterrors.ts b/src/models/errors/httpclienterrors.ts index 53bb3cfa..12aa015a 100644 --- a/src/models/errors/httpclienterrors.ts +++ b/src/models/errors/httpclienterrors.ts @@ -9,8 +9,13 @@ export class HTTPClientError extends Error { /** The underlying cause of the error. */ override readonly cause: unknown; - override name = "HTTPClientError"; - constructor(message: string, opts?: { cause?: unknown }) { + override name = 'HTTPClientError'; + constructor( + message: string, + opts?: { + cause?: unknown; + }, + ) { let msg = message; if (opts?.cause) { msg += `: ${opts.cause}`; @@ -19,7 +24,7 @@ export class HTTPClientError extends Error { super(msg, opts); // In older runtimes, the cause field would not have been assigned through // the super() call. - if (typeof this.cause === "undefined") { + if (typeof this.cause === 'undefined') { this.cause = opts?.cause; } } @@ -29,21 +34,21 @@ export class HTTPClientError extends Error { * An error to capture unrecognised or unexpected errors when making HTTP calls. */ export class UnexpectedClientError extends HTTPClientError { - override name = "UnexpectedClientError"; + override name = 'UnexpectedClientError'; } /** * An error that is raised when any inputs used to create a request are invalid. */ export class InvalidRequestError extends HTTPClientError { - override name = "InvalidRequestError"; + override name = 'InvalidRequestError'; } /** * An error that is raised when a HTTP request was aborted by the client error. */ export class RequestAbortedError extends HTTPClientError { - override readonly name = "RequestAbortedError"; + override readonly name = 'RequestAbortedError'; } /** @@ -51,7 +56,7 @@ export class RequestAbortedError extends HTTPClientError { * signal timeout. */ export class RequestTimeoutError extends HTTPClientError { - override readonly name = "RequestTimeoutError"; + override readonly name = 'RequestTimeoutError'; } /** @@ -59,5 +64,5 @@ export class RequestTimeoutError extends HTTPClientError { * a server. */ export class ConnectionError extends HTTPClientError { - override readonly name = "ConnectionError"; + override readonly name = 'ConnectionError'; } diff --git a/src/models/errors/index.ts b/src/models/errors/index.ts index c5ddaff0..689c18ce 100644 --- a/src/models/errors/index.ts +++ b/src/models/errors/index.ts @@ -3,23 +3,23 @@ * @generated-id: c4e22507cb83 */ -export * from "./badgatewayresponseerror.js"; -export * from "./badrequestresponseerror.js"; -export * from "./chaterror.js"; -export * from "./edgenetworktimeoutresponseerror.js"; -export * from "./forbiddenresponseerror.js"; -export * from "./httpclienterrors.js"; -export * from "./internalserverresponseerror.js"; -export * from "./notfoundresponseerror.js"; -export * from "./openrouterdefaulterror.js"; -export * from "./openroutererror.js"; -export * from "./payloadtoolargeresponseerror.js"; -export * from "./paymentrequiredresponseerror.js"; -export * from "./provideroverloadedresponseerror.js"; -export * from "./requesttimeoutresponseerror.js"; -export * from "./responsevalidationerror.js"; -export * from "./sdkvalidationerror.js"; -export * from "./serviceunavailableresponseerror.js"; -export * from "./toomanyrequestsresponseerror.js"; -export * from "./unauthorizedresponseerror.js"; -export * from "./unprocessableentityresponseerror.js"; +export * from './badgatewayresponseerror.js'; +export * from './badrequestresponseerror.js'; +export * from './chaterror.js'; +export * from './edgenetworktimeoutresponseerror.js'; +export * from './forbiddenresponseerror.js'; +export * from './httpclienterrors.js'; +export * from './internalserverresponseerror.js'; +export * from './notfoundresponseerror.js'; +export * from './openrouterdefaulterror.js'; +export * from './openroutererror.js'; +export * from './payloadtoolargeresponseerror.js'; +export * from './paymentrequiredresponseerror.js'; +export * from './provideroverloadedresponseerror.js'; +export * from './requesttimeoutresponseerror.js'; +export * from './responsevalidationerror.js'; +export * from './sdkvalidationerror.js'; +export * from './serviceunavailableresponseerror.js'; +export * from './toomanyrequestsresponseerror.js'; +export * from './unauthorizedresponseerror.js'; +export * from './unprocessableentityresponseerror.js'; diff --git a/src/models/errors/internalserverresponseerror.ts b/src/models/errors/internalserverresponseerror.ts index c55187c8..47665606 100644 --- a/src/models/errors/internalserverresponseerror.ts +++ b/src/models/errors/internalserverresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: 02b76cec85f0 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Internal Server Error - Unexpected server error @@ -34,16 +34,19 @@ export class InternalServerResponseError extends OpenRouterError { constructor( err: InternalServerResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "InternalServerResponseError"; + this.name = 'InternalServerResponseError'; } } @@ -51,16 +54,17 @@ export class InternalServerResponseError extends OpenRouterError { export const InternalServerResponseError$inboundSchema: z.ZodType< InternalServerResponseError, unknown -> = z.object({ - error: models.InternalServerResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +> = z + .object({ + error: models.InternalServerResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new InternalServerResponseError(remapped, { diff --git a/src/models/errors/notfoundresponseerror.ts b/src/models/errors/notfoundresponseerror.ts index 012d7fc7..c6017dd2 100644 --- a/src/models/errors/notfoundresponseerror.ts +++ b/src/models/errors/notfoundresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: 1914d6d7fbaf */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Not Found - Resource does not exist @@ -34,33 +34,34 @@ export class NotFoundResponseError extends OpenRouterError { constructor( err: NotFoundResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "NotFoundResponseError"; + this.name = 'NotFoundResponseError'; } } /** @internal */ -export const NotFoundResponseError$inboundSchema: z.ZodType< - NotFoundResponseError, - unknown -> = z.object({ - error: models.NotFoundResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +export const NotFoundResponseError$inboundSchema: z.ZodType = z + .object({ + error: models.NotFoundResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new NotFoundResponseError(remapped, { diff --git a/src/models/errors/openrouterdefaulterror.ts b/src/models/errors/openrouterdefaulterror.ts index ed1b4f73..486fd572 100644 --- a/src/models/errors/openrouterdefaulterror.ts +++ b/src/models/errors/openrouterdefaulterror.ts @@ -3,7 +3,7 @@ * @generated-id: 8a3f2faf1848 */ -import { OpenRouterError } from "./openroutererror.js"; +import { OpenRouterError } from './openroutererror.js'; /** The fallback error class if no more specific error class is matched */ export class OpenRouterDefaultError extends OpenRouterError { @@ -16,17 +16,15 @@ export class OpenRouterDefaultError extends OpenRouterError { }, ) { if (message) { - message += `: `; + message += ': '; } message += `Status ${httpMeta.response.status}`; - const contentType = httpMeta.response.headers.get("content-type") || `""`; - if (contentType !== "application/json") { - message += ` Content-Type ${ - contentType.includes(" ") ? `"${contentType}"` : contentType - }`; + const contentType = httpMeta.response.headers.get('content-type') || `""`; + if (contentType !== 'application/json') { + message += ` Content-Type ${contentType.includes(' ') ? `"${contentType}"` : contentType}`; } const body = httpMeta.body || `""`; - message += body.length > 100 ? "\n" : ". "; + message += body.length > 100 ? '\n' : '. '; let bodyDisplay = body; if (body.length > 10000) { const truncated = body.substring(0, 10000); @@ -36,6 +34,6 @@ export class OpenRouterDefaultError extends OpenRouterError { message += `Body: ${bodyDisplay}`; message = message.trim(); super(message, httpMeta); - this.name = "OpenRouterDefaultError"; + this.name = 'OpenRouterDefaultError'; } } diff --git a/src/models/errors/openroutererror.ts b/src/models/errors/openroutererror.ts index 2c0023c4..b14ca3dd 100644 --- a/src/models/errors/openroutererror.ts +++ b/src/models/errors/openroutererror.ts @@ -28,9 +28,9 @@ export class OpenRouterError extends Error { this.statusCode = httpMeta.response.status; this.body = httpMeta.body; this.headers = httpMeta.response.headers; - this.contentType = httpMeta.response.headers.get("content-type") || ""; + this.contentType = httpMeta.response.headers.get('content-type') || ''; this.rawResponse = httpMeta.response; - this.name = "OpenRouterError"; + this.name = 'OpenRouterError'; } } diff --git a/src/models/errors/payloadtoolargeresponseerror.ts b/src/models/errors/payloadtoolargeresponseerror.ts index ad0ab4bd..aa7b40b9 100644 --- a/src/models/errors/payloadtoolargeresponseerror.ts +++ b/src/models/errors/payloadtoolargeresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: f1e472cb7b51 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Payload Too Large - Request payload exceeds size limits @@ -34,16 +34,19 @@ export class PayloadTooLargeResponseError extends OpenRouterError { constructor( err: PayloadTooLargeResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "PayloadTooLargeResponseError"; + this.name = 'PayloadTooLargeResponseError'; } } @@ -51,16 +54,17 @@ export class PayloadTooLargeResponseError extends OpenRouterError { export const PayloadTooLargeResponseError$inboundSchema: z.ZodType< PayloadTooLargeResponseError, unknown -> = z.object({ - error: models.PayloadTooLargeResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +> = z + .object({ + error: models.PayloadTooLargeResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new PayloadTooLargeResponseError(remapped, { diff --git a/src/models/errors/paymentrequiredresponseerror.ts b/src/models/errors/paymentrequiredresponseerror.ts index 70f8350e..eef74b72 100644 --- a/src/models/errors/paymentrequiredresponseerror.ts +++ b/src/models/errors/paymentrequiredresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: f70439757fb9 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Payment Required - Insufficient credits or quota to complete request @@ -34,16 +34,19 @@ export class PaymentRequiredResponseError extends OpenRouterError { constructor( err: PaymentRequiredResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "PaymentRequiredResponseError"; + this.name = 'PaymentRequiredResponseError'; } } @@ -51,16 +54,17 @@ export class PaymentRequiredResponseError extends OpenRouterError { export const PaymentRequiredResponseError$inboundSchema: z.ZodType< PaymentRequiredResponseError, unknown -> = z.object({ - error: models.PaymentRequiredResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +> = z + .object({ + error: models.PaymentRequiredResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new PaymentRequiredResponseError(remapped, { diff --git a/src/models/errors/provideroverloadedresponseerror.ts b/src/models/errors/provideroverloadedresponseerror.ts index 6af814f9..776fb039 100644 --- a/src/models/errors/provideroverloadedresponseerror.ts +++ b/src/models/errors/provideroverloadedresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: ba8edf813fa0 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Provider Overloaded - Provider is temporarily overloaded @@ -34,16 +34,19 @@ export class ProviderOverloadedResponseError extends OpenRouterError { constructor( err: ProviderOverloadedResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "ProviderOverloadedResponseError"; + this.name = 'ProviderOverloadedResponseError'; } } @@ -51,16 +54,17 @@ export class ProviderOverloadedResponseError extends OpenRouterError { export const ProviderOverloadedResponseError$inboundSchema: z.ZodType< ProviderOverloadedResponseError, unknown -> = z.object({ - error: models.ProviderOverloadedResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +> = z + .object({ + error: models.ProviderOverloadedResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new ProviderOverloadedResponseError(remapped, { diff --git a/src/models/errors/requesttimeoutresponseerror.ts b/src/models/errors/requesttimeoutresponseerror.ts index b30969db..43e1af1b 100644 --- a/src/models/errors/requesttimeoutresponseerror.ts +++ b/src/models/errors/requesttimeoutresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: 3a4a755c8536 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Request Timeout - Operation exceeded time limit @@ -34,16 +34,19 @@ export class RequestTimeoutResponseError extends OpenRouterError { constructor( err: RequestTimeoutResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "RequestTimeoutResponseError"; + this.name = 'RequestTimeoutResponseError'; } } @@ -51,16 +54,17 @@ export class RequestTimeoutResponseError extends OpenRouterError { export const RequestTimeoutResponseError$inboundSchema: z.ZodType< RequestTimeoutResponseError, unknown -> = z.object({ - error: models.RequestTimeoutResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +> = z + .object({ + error: models.RequestTimeoutResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new RequestTimeoutResponseError(remapped, { diff --git a/src/models/errors/responsevalidationerror.ts b/src/models/errors/responsevalidationerror.ts index be62cb8a..2ae12c65 100644 --- a/src/models/errors/responsevalidationerror.ts +++ b/src/models/errors/responsevalidationerror.ts @@ -3,9 +3,9 @@ * @generated-id: 88ff98a41be9 */ -import * as z from "zod/v4/core"; -import { OpenRouterError } from "./openroutererror.js"; -import { formatZodError } from "./sdkvalidationerror.js"; +import * as z from 'zod/v4/core'; +import { OpenRouterError } from './openroutererror.js'; +import { formatZodError } from './sdkvalidationerror.js'; export class ResponseValidationError extends OpenRouterError { /** @@ -30,7 +30,7 @@ export class ResponseValidationError extends OpenRouterError { }, ) { super(message, extra); - this.name = "ResponseValidationError"; + this.name = 'ResponseValidationError'; this.cause = extra.cause; this.rawValue = extra.rawValue; this.rawMessage = extra.rawMessage; @@ -44,8 +44,7 @@ export class ResponseValidationError extends OpenRouterError { public pretty(): string { if (this.cause instanceof z.$ZodError) { return `${this.rawMessage}\n${formatZodError(this.cause)}`; - } else { - return this.toString(); } + return this.toString(); } } diff --git a/src/models/errors/sdkvalidationerror.ts b/src/models/errors/sdkvalidationerror.ts index 35e71438..b64e5760 100644 --- a/src/models/errors/sdkvalidationerror.ts +++ b/src/models/errors/sdkvalidationerror.ts @@ -3,7 +3,7 @@ * @generated-id: fb6b2b49c445 */ -import * as z from "zod/v4/core"; +import * as z from 'zod/v4/core'; export class SDKValidationError extends Error { /** @@ -17,20 +17,18 @@ export class SDKValidationError extends Error { public readonly rawMessage: unknown; // Allows for backwards compatibility for `instanceof` checks of `ResponseValidationError` - static override [Symbol.hasInstance]( - instance: unknown, - ): instance is SDKValidationError { + static override [Symbol.hasInstance](instance: unknown): instance is SDKValidationError { if (!(instance instanceof Error)) return false; - if (!("rawValue" in instance)) return false; - if (!("rawMessage" in instance)) return false; - if (!("pretty" in instance)) return false; - if (typeof instance.pretty !== "function") return false; + if (!('rawValue' in instance)) return false; + if (!('rawMessage' in instance)) return false; + if (!('pretty' in instance)) return false; + if (typeof instance.pretty !== 'function') return false; return true; } constructor(message: string, cause: unknown, rawValue: unknown) { super(`${message}: ${cause}`); - this.name = "SDKValidationError"; + this.name = 'SDKValidationError'; this.cause = cause; this.rawValue = rawValue; this.rawMessage = message; @@ -44,9 +42,8 @@ export class SDKValidationError extends Error { public pretty(): string { if (this.cause instanceof z.$ZodError) { return `${this.rawMessage}\n${formatZodError(this.cause)}`; - } else { - return this.toString(); } + return this.toString(); } } diff --git a/src/models/errors/serviceunavailableresponseerror.ts b/src/models/errors/serviceunavailableresponseerror.ts index 1b11022a..20fb0c2f 100644 --- a/src/models/errors/serviceunavailableresponseerror.ts +++ b/src/models/errors/serviceunavailableresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: 1259f9d051c8 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Service Unavailable - Service temporarily unavailable @@ -34,16 +34,19 @@ export class ServiceUnavailableResponseError extends OpenRouterError { constructor( err: ServiceUnavailableResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "ServiceUnavailableResponseError"; + this.name = 'ServiceUnavailableResponseError'; } } @@ -51,16 +54,17 @@ export class ServiceUnavailableResponseError extends OpenRouterError { export const ServiceUnavailableResponseError$inboundSchema: z.ZodType< ServiceUnavailableResponseError, unknown -> = z.object({ - error: models.ServiceUnavailableResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +> = z + .object({ + error: models.ServiceUnavailableResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new ServiceUnavailableResponseError(remapped, { diff --git a/src/models/errors/toomanyrequestsresponseerror.ts b/src/models/errors/toomanyrequestsresponseerror.ts index c67e4d84..97547752 100644 --- a/src/models/errors/toomanyrequestsresponseerror.ts +++ b/src/models/errors/toomanyrequestsresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: ab15bfa145f3 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Too Many Requests - Rate limit exceeded @@ -34,16 +34,19 @@ export class TooManyRequestsResponseError extends OpenRouterError { constructor( err: TooManyRequestsResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "TooManyRequestsResponseError"; + this.name = 'TooManyRequestsResponseError'; } } @@ -51,16 +54,17 @@ export class TooManyRequestsResponseError extends OpenRouterError { export const TooManyRequestsResponseError$inboundSchema: z.ZodType< TooManyRequestsResponseError, unknown -> = z.object({ - error: models.TooManyRequestsResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +> = z + .object({ + error: models.TooManyRequestsResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new TooManyRequestsResponseError(remapped, { diff --git a/src/models/errors/unauthorizedresponseerror.ts b/src/models/errors/unauthorizedresponseerror.ts index d6258e10..f1b4fd15 100644 --- a/src/models/errors/unauthorizedresponseerror.ts +++ b/src/models/errors/unauthorizedresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: 79ab0861cf08 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Unauthorized - Authentication required or invalid credentials @@ -34,16 +34,19 @@ export class UnauthorizedResponseError extends OpenRouterError { constructor( err: UnauthorizedResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "UnauthorizedResponseError"; + this.name = 'UnauthorizedResponseError'; } } @@ -51,16 +54,17 @@ export class UnauthorizedResponseError extends OpenRouterError { export const UnauthorizedResponseError$inboundSchema: z.ZodType< UnauthorizedResponseError, unknown -> = z.object({ - error: models.UnauthorizedResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +> = z + .object({ + error: models.UnauthorizedResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new UnauthorizedResponseError(remapped, { diff --git a/src/models/errors/unprocessableentityresponseerror.ts b/src/models/errors/unprocessableentityresponseerror.ts index 4ece53ed..c3639553 100644 --- a/src/models/errors/unprocessableentityresponseerror.ts +++ b/src/models/errors/unprocessableentityresponseerror.ts @@ -3,10 +3,10 @@ * @generated-id: d81e01bbb5e3 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import * as models from "../index.js"; -import { OpenRouterError } from "./openroutererror.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import * as models from '../index.js'; +import { OpenRouterError } from './openroutererror.js'; /** * Unprocessable Entity - Semantic validation failure @@ -34,16 +34,19 @@ export class UnprocessableEntityResponseError extends OpenRouterError { constructor( err: UnprocessableEntityResponseErrorData, - httpMeta: { response: Response; request: Request; body: string }, + httpMeta: { + response: Response; + request: Request; + body: string; + }, ) { - const message = err.error?.message - || `API error occurred: ${JSON.stringify(err)}`; + const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`; super(message, httpMeta); this.data$ = err; this.error = err.error; if (err.userId != null) this.userId = err.userId; - this.name = "UnprocessableEntityResponseError"; + this.name = 'UnprocessableEntityResponseError'; } } @@ -51,16 +54,17 @@ export class UnprocessableEntityResponseError extends OpenRouterError { export const UnprocessableEntityResponseError$inboundSchema: z.ZodType< UnprocessableEntityResponseError, unknown -> = z.object({ - error: models.UnprocessableEntityResponseErrorData$inboundSchema, - user_id: z.nullable(z.string()).optional(), - request$: z.custom(x => x instanceof Request), - response$: z.custom(x => x instanceof Response), - body$: z.string(), -}) +> = z + .object({ + error: models.UnprocessableEntityResponseErrorData$inboundSchema, + user_id: z.nullable(z.string()).optional(), + request$: z.custom((x) => x instanceof Request), + response$: z.custom((x) => x instanceof Response), + body$: z.string(), + }) .transform((v) => { const remapped = remap$(v, { - "user_id": "userId", + user_id: 'userId', }); return new UnprocessableEntityResponseError(remapped, { diff --git a/src/models/filecitation.ts b/src/models/filecitation.ts index 665445c5..348ece14 100644 --- a/src/models/filecitation.ts +++ b/src/models/filecitation.ts @@ -3,14 +3,15 @@ * @generated-id: 0e609723dbc8 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; export type FileCitation = { - type: "file_citation"; + type: 'file_citation'; fileId: string; filename: string; index: number; @@ -19,37 +20,37 @@ export type FileCitation = { /** @internal */ export const FileCitation$inboundSchema: z.ZodType = z .object({ - type: z.literal("file_citation"), + type: z.literal('file_citation'), file_id: z.string(), filename: z.string(), index: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "file_id": "fileId", + file_id: 'fileId', }); }); /** @internal */ export type FileCitation$Outbound = { - type: "file_citation"; + type: 'file_citation'; file_id: string; filename: string; index: number; }; /** @internal */ -export const FileCitation$outboundSchema: z.ZodType< - FileCitation$Outbound, - FileCitation -> = z.object({ - type: z.literal("file_citation"), - fileId: z.string(), - filename: z.string(), - index: z.number(), -}).transform((v) => { - return remap$(v, { - fileId: "file_id", +export const FileCitation$outboundSchema: z.ZodType = z + .object({ + type: z.literal('file_citation'), + fileId: z.string(), + filename: z.string(), + index: z.number(), + }) + .transform((v) => { + return remap$(v, { + fileId: 'file_id', + }); }); -}); export function fileCitationToJSON(fileCitation: FileCitation): string { return JSON.stringify(FileCitation$outboundSchema.parse(fileCitation)); diff --git a/src/models/filepath.ts b/src/models/filepath.ts index 90ff601b..9e880064 100644 --- a/src/models/filepath.ts +++ b/src/models/filepath.ts @@ -3,31 +3,34 @@ * @generated-id: 0f8d4008ed8e */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; export type FilePath = { - type: "file_path"; + type: 'file_path'; fileId: string; index: number; }; /** @internal */ -export const FilePath$inboundSchema: z.ZodType = z.object({ - type: z.literal("file_path"), - file_id: z.string(), - index: z.number(), -}).transform((v) => { - return remap$(v, { - "file_id": "fileId", +export const FilePath$inboundSchema: z.ZodType = z + .object({ + type: z.literal('file_path'), + file_id: z.string(), + index: z.number(), + }) + .transform((v) => { + return remap$(v, { + file_id: 'fileId', + }); }); -}); /** @internal */ export type FilePath$Outbound = { - type: "file_path"; + type: 'file_path'; file_id: string; index: number; }; @@ -35,12 +38,13 @@ export type FilePath$Outbound = { /** @internal */ export const FilePath$outboundSchema: z.ZodType = z .object({ - type: z.literal("file_path"), + type: z.literal('file_path'), fileId: z.string(), index: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - fileId: "file_id", + fileId: 'file_id', }); }); diff --git a/src/models/forbiddenresponseerrordata.ts b/src/models/forbiddenresponseerrordata.ts index 2d84cb3d..73212129 100644 --- a/src/models/forbiddenresponseerrordata.ts +++ b/src/models/forbiddenresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: cc3fdc45a2fd */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for ForbiddenResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type ForbiddenResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ diff --git a/src/models/imagegenerationstatus.ts b/src/models/imagegenerationstatus.ts index db61647c..bc13ecd3 100644 --- a/src/models/imagegenerationstatus.ts +++ b/src/models/imagegenerationstatus.ts @@ -3,25 +3,22 @@ * @generated-id: 2a72a5923e5a */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const ImageGenerationStatus = { - InProgress: "in_progress", - Completed: "completed", - Generating: "generating", - Failed: "failed", + InProgress: 'in_progress', + Completed: 'completed', + Generating: 'generating', + Failed: 'failed', } as const; export type ImageGenerationStatus = OpenEnum; /** @internal */ -export const ImageGenerationStatus$inboundSchema: z.ZodType< - ImageGenerationStatus, - unknown -> = openEnums.inboundSchema(ImageGenerationStatus); +export const ImageGenerationStatus$inboundSchema: z.ZodType = + openEnums.inboundSchema(ImageGenerationStatus); /** @internal */ -export const ImageGenerationStatus$outboundSchema: z.ZodType< - string, - ImageGenerationStatus -> = openEnums.outboundSchema(ImageGenerationStatus); +export const ImageGenerationStatus$outboundSchema: z.ZodType = + openEnums.outboundSchema(ImageGenerationStatus); diff --git a/src/models/index.ts b/src/models/index.ts index f8e040d1..28a24e09 100644 --- a/src/models/index.ts +++ b/src/models/index.ts @@ -3,156 +3,156 @@ * @generated-id: f93644b0f37e */ -export * from "./activityitem.js"; -export * from "./assistantmessage.js"; -export * from "./badgatewayresponseerrordata.js"; -export * from "./badrequestresponseerrordata.js"; -export * from "./chatcompletionfinishreason.js"; -export * from "./chaterror.js"; -export * from "./chatgenerationparams.js"; -export * from "./chatgenerationtokenusage.js"; -export * from "./chatmessagecontentitem.js"; -export * from "./chatmessagecontentitemaudio.js"; -export * from "./chatmessagecontentitemcachecontrol.js"; -export * from "./chatmessagecontentitemimage.js"; -export * from "./chatmessagecontentitemtext.js"; -export * from "./chatmessagecontentitemvideo.js"; -export * from "./chatmessagetokenlogprob.js"; -export * from "./chatmessagetokenlogprobs.js"; -export * from "./chatmessagetoolcall.js"; -export * from "./chatresponse.js"; -export * from "./chatresponsechoice.js"; -export * from "./chatstreamingchoice.js"; -export * from "./chatstreamingmessagechunk.js"; -export * from "./chatstreamingmessagetoolcall.js"; -export * from "./chatstreamingresponsechunk.js"; -export * from "./chatstreamoptions.js"; -export * from "./completionchoice.js"; -export * from "./completioncreateparams.js"; -export * from "./completionlogprobs.js"; -export * from "./completionresponse.js"; -export * from "./completionusage.js"; -export * from "./createchargerequest.js"; -export * from "./datacollection.js"; -export * from "./defaultparameters.js"; -export * from "./edgenetworktimeoutresponseerrordata.js"; -export * from "./endpointstatus.js"; -export * from "./filecitation.js"; -export * from "./filepath.js"; -export * from "./forbiddenresponseerrordata.js"; -export * from "./imagegenerationstatus.js"; -export * from "./inputmodality.js"; -export * from "./instructtype.js"; -export * from "./internalserverresponseerrordata.js"; -export * from "./jsonschemaconfig.js"; -export * from "./listendpointsresponse.js"; -export * from "./message.js"; -export * from "./model.js"; -export * from "./modelarchitecture.js"; -export * from "./modelgroup.js"; -export * from "./modelscountresponse.js"; -export * from "./modelslistresponse.js"; -export * from "./namedtoolchoice.js"; -export * from "./notfoundresponseerrordata.js"; -export * from "./openairesponsesannotation.js"; -export * from "./openairesponsesincludable.js"; -export * from "./openairesponsesincompletedetails.js"; -export * from "./openairesponsesinputunion.js"; -export * from "./openairesponsesprompt.js"; -export * from "./openairesponsesreasoningconfig.js"; -export * from "./openairesponsesreasoningeffort.js"; -export * from "./openairesponsesrefusalcontent.js"; -export * from "./openairesponsesresponsestatus.js"; -export * from "./openairesponsesservicetier.js"; -export * from "./openairesponsestoolchoiceunion.js"; -export * from "./openairesponsestruncation.js"; -export * from "./openresponseseasyinputmessage.js"; -export * from "./openresponseserrorevent.js"; -export * from "./openresponsesfunctioncalloutput.js"; -export * from "./openresponsesfunctiontoolcall.js"; -export * from "./openresponsesimagegencallcompleted.js"; -export * from "./openresponsesimagegencallgenerating.js"; -export * from "./openresponsesimagegencallinprogress.js"; -export * from "./openresponsesimagegencallpartialimage.js"; -export * from "./openresponsesinput.js"; -export * from "./openresponsesinputmessageitem.js"; -export * from "./openresponseslogprobs.js"; -export * from "./openresponsesnonstreamingresponse.js"; -export * from "./openresponsesreasoning.js"; -export * from "./openresponsesreasoningconfig.js"; -export * from "./openresponsesreasoningdeltaevent.js"; -export * from "./openresponsesreasoningdoneevent.js"; -export * from "./openresponsesreasoningsummarypartaddedevent.js"; -export * from "./openresponsesreasoningsummarytextdeltaevent.js"; -export * from "./openresponsesreasoningsummarytextdoneevent.js"; -export * from "./openresponsesrequest.js"; -export * from "./openresponsesresponsetext.js"; -export * from "./openresponsesstreamevent.js"; -export * from "./openresponsestoplogprobs.js"; -export * from "./openresponsesusage.js"; -export * from "./openresponseswebsearch20250826tool.js"; -export * from "./openresponseswebsearchpreview20250311tool.js"; -export * from "./openresponseswebsearchpreviewtool.js"; -export * from "./openresponseswebsearchtool.js"; -export * from "./outputitemimagegenerationcall.js"; -export * from "./outputmessage.js"; -export * from "./outputmodality.js"; -export * from "./parameter.js"; -export * from "./payloadtoolargeresponseerrordata.js"; -export * from "./paymentrequiredresponseerrordata.js"; -export * from "./pdfparserengine.js"; -export * from "./pdfparseroptions.js"; -export * from "./perrequestlimits.js"; -export * from "./providername.js"; -export * from "./provideroverloadedresponseerrordata.js"; -export * from "./providerpreferences.js"; -export * from "./providersort.js"; -export * from "./providersortconfig.js"; -export * from "./providersortunion.js"; -export * from "./publicendpoint.js"; -export * from "./publicpricing.js"; -export * from "./quantization.js"; -export * from "./reasoningsummarytext.js"; -export * from "./reasoningsummaryverbosity.js"; -export * from "./reasoningtextcontent.js"; -export * from "./requesttimeoutresponseerrordata.js"; -export * from "./responseformatjsonschema.js"; -export * from "./responseformattextconfig.js"; -export * from "./responseformattextgrammar.js"; -export * from "./responseinputaudio.js"; -export * from "./responseinputfile.js"; -export * from "./responseinputimage.js"; -export * from "./responseinputtext.js"; -export * from "./responseoutputtext.js"; -export * from "./responseserrorfield.js"; -export * from "./responsesformatjsonobject.js"; -export * from "./responsesformattext.js"; -export * from "./responsesformattextjsonschemaconfig.js"; -export * from "./responsesimagegenerationcall.js"; -export * from "./responsesoutputitem.js"; -export * from "./responsesoutputitemfilesearchcall.js"; -export * from "./responsesoutputitemfunctioncall.js"; -export * from "./responsesoutputitemreasoning.js"; -export * from "./responsesoutputmessage.js"; -export * from "./responsessearchcontextsize.js"; -export * from "./responseswebsearchcalloutput.js"; -export * from "./responseswebsearchuserlocation.js"; -export * from "./responsetextconfig.js"; -export * from "./schema0.js"; -export * from "./schema3.js"; -export * from "./security.js"; -export * from "./serviceunavailableresponseerrordata.js"; -export * from "./systemmessage.js"; -export * from "./toolcallstatus.js"; -export * from "./tooldefinitionjson.js"; -export * from "./toolresponsemessage.js"; -export * from "./toomanyrequestsresponseerrordata.js"; -export * from "./topproviderinfo.js"; -export * from "./unauthorizedresponseerrordata.js"; -export * from "./unprocessableentityresponseerrordata.js"; -export * from "./urlcitation.js"; -export * from "./usermessage.js"; -export * from "./websearchengine.js"; -export * from "./websearchpreviewtooluserlocation.js"; -export * from "./websearchstatus.js"; -export * from "./claude-message.js"; +export * from './activityitem.js'; +export * from './assistantmessage.js'; +export * from './badgatewayresponseerrordata.js'; +export * from './badrequestresponseerrordata.js'; +export * from './chatcompletionfinishreason.js'; +export * from './chaterror.js'; +export * from './chatgenerationparams.js'; +export * from './chatgenerationtokenusage.js'; +export * from './chatmessagecontentitem.js'; +export * from './chatmessagecontentitemaudio.js'; +export * from './chatmessagecontentitemcachecontrol.js'; +export * from './chatmessagecontentitemimage.js'; +export * from './chatmessagecontentitemtext.js'; +export * from './chatmessagecontentitemvideo.js'; +export * from './chatmessagetokenlogprob.js'; +export * from './chatmessagetokenlogprobs.js'; +export * from './chatmessagetoolcall.js'; +export * from './chatresponse.js'; +export * from './chatresponsechoice.js'; +export * from './chatstreamingchoice.js'; +export * from './chatstreamingmessagechunk.js'; +export * from './chatstreamingmessagetoolcall.js'; +export * from './chatstreamingresponsechunk.js'; +export * from './chatstreamoptions.js'; +export * from './claude-message.js'; +export * from './completionchoice.js'; +export * from './completioncreateparams.js'; +export * from './completionlogprobs.js'; +export * from './completionresponse.js'; +export * from './completionusage.js'; +export * from './createchargerequest.js'; +export * from './datacollection.js'; +export * from './defaultparameters.js'; +export * from './edgenetworktimeoutresponseerrordata.js'; +export * from './endpointstatus.js'; +export * from './filecitation.js'; +export * from './filepath.js'; +export * from './forbiddenresponseerrordata.js'; +export * from './imagegenerationstatus.js'; +export * from './inputmodality.js'; +export * from './instructtype.js'; +export * from './internalserverresponseerrordata.js'; +export * from './jsonschemaconfig.js'; +export * from './listendpointsresponse.js'; +export * from './message.js'; +export * from './model.js'; +export * from './modelarchitecture.js'; +export * from './modelgroup.js'; +export * from './modelscountresponse.js'; +export * from './modelslistresponse.js'; +export * from './namedtoolchoice.js'; +export * from './notfoundresponseerrordata.js'; +export * from './openairesponsesannotation.js'; +export * from './openairesponsesincludable.js'; +export * from './openairesponsesincompletedetails.js'; +export * from './openairesponsesinputunion.js'; +export * from './openairesponsesprompt.js'; +export * from './openairesponsesreasoningconfig.js'; +export * from './openairesponsesreasoningeffort.js'; +export * from './openairesponsesrefusalcontent.js'; +export * from './openairesponsesresponsestatus.js'; +export * from './openairesponsesservicetier.js'; +export * from './openairesponsestoolchoiceunion.js'; +export * from './openairesponsestruncation.js'; +export * from './openresponseseasyinputmessage.js'; +export * from './openresponseserrorevent.js'; +export * from './openresponsesfunctioncalloutput.js'; +export * from './openresponsesfunctiontoolcall.js'; +export * from './openresponsesimagegencallcompleted.js'; +export * from './openresponsesimagegencallgenerating.js'; +export * from './openresponsesimagegencallinprogress.js'; +export * from './openresponsesimagegencallpartialimage.js'; +export * from './openresponsesinput.js'; +export * from './openresponsesinputmessageitem.js'; +export * from './openresponseslogprobs.js'; +export * from './openresponsesnonstreamingresponse.js'; +export * from './openresponsesreasoning.js'; +export * from './openresponsesreasoningconfig.js'; +export * from './openresponsesreasoningdeltaevent.js'; +export * from './openresponsesreasoningdoneevent.js'; +export * from './openresponsesreasoningsummarypartaddedevent.js'; +export * from './openresponsesreasoningsummarytextdeltaevent.js'; +export * from './openresponsesreasoningsummarytextdoneevent.js'; +export * from './openresponsesrequest.js'; +export * from './openresponsesresponsetext.js'; +export * from './openresponsesstreamevent.js'; +export * from './openresponsestoplogprobs.js'; +export * from './openresponsesusage.js'; +export * from './openresponseswebsearch20250826tool.js'; +export * from './openresponseswebsearchpreview20250311tool.js'; +export * from './openresponseswebsearchpreviewtool.js'; +export * from './openresponseswebsearchtool.js'; +export * from './outputitemimagegenerationcall.js'; +export * from './outputmessage.js'; +export * from './outputmodality.js'; +export * from './parameter.js'; +export * from './payloadtoolargeresponseerrordata.js'; +export * from './paymentrequiredresponseerrordata.js'; +export * from './pdfparserengine.js'; +export * from './pdfparseroptions.js'; +export * from './perrequestlimits.js'; +export * from './providername.js'; +export * from './provideroverloadedresponseerrordata.js'; +export * from './providerpreferences.js'; +export * from './providersort.js'; +export * from './providersortconfig.js'; +export * from './providersortunion.js'; +export * from './publicendpoint.js'; +export * from './publicpricing.js'; +export * from './quantization.js'; +export * from './reasoningsummarytext.js'; +export * from './reasoningsummaryverbosity.js'; +export * from './reasoningtextcontent.js'; +export * from './requesttimeoutresponseerrordata.js'; +export * from './responseformatjsonschema.js'; +export * from './responseformattextconfig.js'; +export * from './responseformattextgrammar.js'; +export * from './responseinputaudio.js'; +export * from './responseinputfile.js'; +export * from './responseinputimage.js'; +export * from './responseinputtext.js'; +export * from './responseoutputtext.js'; +export * from './responseserrorfield.js'; +export * from './responsesformatjsonobject.js'; +export * from './responsesformattext.js'; +export * from './responsesformattextjsonschemaconfig.js'; +export * from './responsesimagegenerationcall.js'; +export * from './responsesoutputitem.js'; +export * from './responsesoutputitemfilesearchcall.js'; +export * from './responsesoutputitemfunctioncall.js'; +export * from './responsesoutputitemreasoning.js'; +export * from './responsesoutputmessage.js'; +export * from './responsessearchcontextsize.js'; +export * from './responseswebsearchcalloutput.js'; +export * from './responseswebsearchuserlocation.js'; +export * from './responsetextconfig.js'; +export * from './schema0.js'; +export * from './schema3.js'; +export * from './security.js'; +export * from './serviceunavailableresponseerrordata.js'; +export * from './systemmessage.js'; +export * from './toolcallstatus.js'; +export * from './tooldefinitionjson.js'; +export * from './toolresponsemessage.js'; +export * from './toomanyrequestsresponseerrordata.js'; +export * from './topproviderinfo.js'; +export * from './unauthorizedresponseerrordata.js'; +export * from './unprocessableentityresponseerrordata.js'; +export * from './urlcitation.js'; +export * from './usermessage.js'; +export * from './websearchengine.js'; +export * from './websearchpreviewtooluserlocation.js'; +export * from './websearchstatus.js'; diff --git a/src/models/inputmodality.ts b/src/models/inputmodality.ts index a92bcc40..1be048bb 100644 --- a/src/models/inputmodality.ts +++ b/src/models/inputmodality.ts @@ -3,16 +3,17 @@ * @generated-id: 771d5d4c91ec */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const InputModality = { - Text: "text", - Image: "image", - File: "file", - Audio: "audio", - Video: "video", + Text: 'text', + Image: 'image', + File: 'file', + Audio: 'audio', + Video: 'video', } as const; export type InputModality = OpenEnum; diff --git a/src/models/instructtype.ts b/src/models/instructtype.ts index 339d2ae8..14406b51 100644 --- a/src/models/instructtype.ts +++ b/src/models/instructtype.ts @@ -3,36 +3,37 @@ * @generated-id: 970f140dadec */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; /** * Instruction format type */ export const InstructType = { - None: "none", - Airoboros: "airoboros", - Alpaca: "alpaca", - AlpacaModif: "alpaca-modif", - Chatml: "chatml", - Claude: "claude", - CodeLlama: "code-llama", - Gemma: "gemma", - Llama2: "llama2", - Llama3: "llama3", - Mistral: "mistral", - Nemotron: "nemotron", - Neural: "neural", - Openchat: "openchat", - Phi3: "phi3", - Rwkv: "rwkv", - Vicuna: "vicuna", - Zephyr: "zephyr", - DeepseekR1: "deepseek-r1", - DeepseekV31: "deepseek-v3.1", - Qwq: "qwq", - Qwen3: "qwen3", + None: 'none', + Airoboros: 'airoboros', + Alpaca: 'alpaca', + AlpacaModif: 'alpaca-modif', + Chatml: 'chatml', + Claude: 'claude', + CodeLlama: 'code-llama', + Gemma: 'gemma', + Llama2: 'llama2', + Llama3: 'llama3', + Mistral: 'mistral', + Nemotron: 'nemotron', + Neural: 'neural', + Openchat: 'openchat', + Phi3: 'phi3', + Rwkv: 'rwkv', + Vicuna: 'vicuna', + Zephyr: 'zephyr', + DeepseekR1: 'deepseek-r1', + DeepseekV31: 'deepseek-v3.1', + Qwq: 'qwq', + Qwen3: 'qwen3', } as const; /** * Instruction format type diff --git a/src/models/internalserverresponseerrordata.ts b/src/models/internalserverresponseerrordata.ts index 1676c40a..ae9f1125 100644 --- a/src/models/internalserverresponseerrordata.ts +++ b/src/models/internalserverresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: 48c17eec376a */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for InternalServerResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type InternalServerResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ diff --git a/src/models/jsonschemaconfig.ts b/src/models/jsonschemaconfig.ts index 4ea4757a..d9c0b2a8 100644 --- a/src/models/jsonschemaconfig.ts +++ b/src/models/jsonschemaconfig.ts @@ -3,12 +3,16 @@ * @generated-id: a5dbdd0305ec */ -import * as z from "zod/v4"; +import * as z from 'zod/v4'; export type JSONSchemaConfig = { name: string; description?: string | undefined; - schema?: { [k: string]: any } | undefined; + schema?: + | { + [k: string]: any; + } + | undefined; strict?: boolean | null | undefined; }; @@ -16,7 +20,11 @@ export type JSONSchemaConfig = { export type JSONSchemaConfig$Outbound = { name: string; description?: string | undefined; - schema?: { [k: string]: any } | undefined; + schema?: + | { + [k: string]: any; + } + | undefined; strict?: boolean | null | undefined; }; @@ -31,10 +39,6 @@ export const JSONSchemaConfig$outboundSchema: z.ZodType< strict: z.nullable(z.boolean()).optional(), }); -export function jsonSchemaConfigToJSON( - jsonSchemaConfig: JSONSchemaConfig, -): string { - return JSON.stringify( - JSONSchemaConfig$outboundSchema.parse(jsonSchemaConfig), - ); +export function jsonSchemaConfigToJSON(jsonSchemaConfig: JSONSchemaConfig): string { + return JSON.stringify(JSONSchemaConfig$outboundSchema.parse(jsonSchemaConfig)); } diff --git a/src/models/listendpointsresponse.ts b/src/models/listendpointsresponse.ts index b6d6af83..65c11fb6 100644 --- a/src/models/listendpointsresponse.ts +++ b/src/models/listendpointsresponse.ts @@ -3,47 +3,46 @@ * @generated-id: 5178e92a44ba */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { InputModality, InputModality$inboundSchema } from "./inputmodality.js"; -import { InstructType, InstructType$inboundSchema } from "./instructtype.js"; -import { - OutputModality, - OutputModality$inboundSchema, -} from "./outputmodality.js"; -import { - PublicEndpoint, - PublicEndpoint$inboundSchema, -} from "./publicendpoint.js"; +import type { OpenEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { InputModality } from './inputmodality.js'; +import type { InstructType } from './instructtype.js'; +import type { OutputModality } from './outputmodality.js'; +import type { PublicEndpoint } from './publicendpoint.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import * as openEnums from '../types/enums.js'; +import { InputModality$inboundSchema } from './inputmodality.js'; +import { InstructType$inboundSchema } from './instructtype.js'; +import { OutputModality$inboundSchema } from './outputmodality.js'; +import { PublicEndpoint$inboundSchema } from './publicendpoint.js'; /** * Tokenizer type used by the model */ export const Tokenizer = { - Router: "Router", - Media: "Media", - Other: "Other", - Gpt: "GPT", - Claude: "Claude", - Gemini: "Gemini", - Grok: "Grok", - Cohere: "Cohere", - Nova: "Nova", - Qwen: "Qwen", - Yi: "Yi", - DeepSeek: "DeepSeek", - Mistral: "Mistral", - Llama2: "Llama2", - Llama3: "Llama3", - Llama4: "Llama4", - PaLM: "PaLM", - Rwkv: "RWKV", - Qwen3: "Qwen3", + Router: 'Router', + Media: 'Media', + Other: 'Other', + Gpt: 'GPT', + Claude: 'Claude', + Gemini: 'Gemini', + Grok: 'Grok', + Cohere: 'Cohere', + Nova: 'Nova', + Qwen: 'Qwen', + Yi: 'Yi', + DeepSeek: 'DeepSeek', + Mistral: 'Mistral', + Llama2: 'Llama2', + Llama3: 'Llama3', + Llama4: 'Llama4', + PaLM: 'PaLM', + Rwkv: 'RWKV', + Qwen3: 'Qwen3', } as const; /** * Tokenizer type used by the model @@ -101,8 +100,8 @@ export type ListEndpointsResponse = { }; /** @internal */ -export const Tokenizer$inboundSchema: z.ZodType = openEnums - .inboundSchema(Tokenizer); +export const Tokenizer$inboundSchema: z.ZodType = + openEnums.inboundSchema(Tokenizer); /** @internal */ export const Architecture$inboundSchema: z.ZodType = z @@ -112,11 +111,12 @@ export const Architecture$inboundSchema: z.ZodType = z modality: z.nullable(z.string()), input_modalities: z.array(InputModality$inboundSchema), output_modalities: z.array(OutputModality$inboundSchema), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "instruct_type": "instructType", - "input_modalities": "inputModalities", - "output_modalities": "outputModalities", + instruct_type: 'instructType', + input_modalities: 'inputModalities', + output_modalities: 'outputModalities', }); }); @@ -131,17 +131,15 @@ export function architectureFromJSON( } /** @internal */ -export const ListEndpointsResponse$inboundSchema: z.ZodType< - ListEndpointsResponse, - unknown -> = z.object({ - id: z.string(), - name: z.string(), - created: z.number(), - description: z.string(), - architecture: z.lazy(() => Architecture$inboundSchema), - endpoints: z.array(PublicEndpoint$inboundSchema), -}); +export const ListEndpointsResponse$inboundSchema: z.ZodType = + z.object({ + id: z.string(), + name: z.string(), + created: z.number(), + description: z.string(), + architecture: z.lazy(() => Architecture$inboundSchema), + endpoints: z.array(PublicEndpoint$inboundSchema), + }); export function listEndpointsResponseFromJSON( jsonString: string, diff --git a/src/models/message.ts b/src/models/message.ts index 9c6974a6..0be754c0 100644 --- a/src/models/message.ts +++ b/src/models/message.ts @@ -3,37 +3,26 @@ * @generated-id: 34645e53d993 */ -import * as z from "zod/v4"; -import { - AssistantMessage, - AssistantMessage$Outbound, - AssistantMessage$outboundSchema, -} from "./assistantmessage.js"; -import { +import type { AssistantMessage, AssistantMessage$Outbound } from './assistantmessage.js'; +import type { ChatMessageContentItemText, ChatMessageContentItemText$Outbound, - ChatMessageContentItemText$outboundSchema, -} from "./chatmessagecontentitemtext.js"; -import { - SystemMessage, - SystemMessage$Outbound, - SystemMessage$outboundSchema, -} from "./systemmessage.js"; -import { - ToolResponseMessage, - ToolResponseMessage$Outbound, - ToolResponseMessage$outboundSchema, -} from "./toolresponsemessage.js"; -import { - UserMessage, - UserMessage$Outbound, - UserMessage$outboundSchema, -} from "./usermessage.js"; +} from './chatmessagecontentitemtext.js'; +import type { SystemMessage, SystemMessage$Outbound } from './systemmessage.js'; +import type { ToolResponseMessage, ToolResponseMessage$Outbound } from './toolresponsemessage.js'; +import type { UserMessage, UserMessage$Outbound } from './usermessage.js'; + +import * as z from 'zod/v4'; +import { AssistantMessage$outboundSchema } from './assistantmessage.js'; +import { ChatMessageContentItemText$outboundSchema } from './chatmessagecontentitemtext.js'; +import { SystemMessage$outboundSchema } from './systemmessage.js'; +import { ToolResponseMessage$outboundSchema } from './toolresponsemessage.js'; +import { UserMessage$outboundSchema } from './usermessage.js'; export type MessageContent = string | Array; export type MessageDeveloper = { - role: "developer"; + role: 'developer'; content: string | Array; name?: string | undefined; }; @@ -46,15 +35,14 @@ export type Message = | ToolResponseMessage; /** @internal */ -export type MessageContent$Outbound = - | string - | Array; +export type MessageContent$Outbound = string | Array; /** @internal */ -export const MessageContent$outboundSchema: z.ZodType< - MessageContent$Outbound, - MessageContent -> = z.union([z.string(), z.array(ChatMessageContentItemText$outboundSchema)]); +export const MessageContent$outboundSchema: z.ZodType = + z.union([ + z.string(), + z.array(ChatMessageContentItemText$outboundSchema), + ]); export function messageContentToJSON(messageContent: MessageContent): string { return JSON.stringify(MessageContent$outboundSchema.parse(messageContent)); @@ -62,7 +50,7 @@ export function messageContentToJSON(messageContent: MessageContent): string { /** @internal */ export type MessageDeveloper$Outbound = { - role: "developer"; + role: 'developer'; content: string | Array; name?: string | undefined; }; @@ -72,7 +60,7 @@ export const MessageDeveloper$outboundSchema: z.ZodType< MessageDeveloper$Outbound, MessageDeveloper > = z.object({ - role: z.literal("developer"), + role: z.literal('developer'), content: z.union([ z.string(), z.array(ChatMessageContentItemText$outboundSchema), @@ -80,12 +68,8 @@ export const MessageDeveloper$outboundSchema: z.ZodType< name: z.string().optional(), }); -export function messageDeveloperToJSON( - messageDeveloper: MessageDeveloper, -): string { - return JSON.stringify( - MessageDeveloper$outboundSchema.parse(messageDeveloper), - ); +export function messageDeveloperToJSON(messageDeveloper: MessageDeveloper): string { + return JSON.stringify(MessageDeveloper$outboundSchema.parse(messageDeveloper)); } /** @internal */ @@ -97,14 +81,13 @@ export type Message$Outbound = | ToolResponseMessage$Outbound; /** @internal */ -export const Message$outboundSchema: z.ZodType = z - .union([ - SystemMessage$outboundSchema, - UserMessage$outboundSchema, - z.lazy(() => MessageDeveloper$outboundSchema), - AssistantMessage$outboundSchema, - ToolResponseMessage$outboundSchema, - ]); +export const Message$outboundSchema: z.ZodType = z.union([ + SystemMessage$outboundSchema, + UserMessage$outboundSchema, + z.lazy(() => MessageDeveloper$outboundSchema), + AssistantMessage$outboundSchema, + ToolResponseMessage$outboundSchema, +]); export function messageToJSON(message: Message): string { return JSON.stringify(Message$outboundSchema.parse(message)); diff --git a/src/models/model.ts b/src/models/model.ts index 6248dbe4..031e1de5 100644 --- a/src/models/model.ts +++ b/src/models/model.ts @@ -3,29 +3,24 @@ * @generated-id: b99d4c14e794 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { - DefaultParameters, - DefaultParameters$inboundSchema, -} from "./defaultparameters.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { - ModelArchitecture, - ModelArchitecture$inboundSchema, -} from "./modelarchitecture.js"; -import { Parameter, Parameter$inboundSchema } from "./parameter.js"; -import { - PerRequestLimits, - PerRequestLimits$inboundSchema, -} from "./perrequestlimits.js"; -import { PublicPricing, PublicPricing$inboundSchema } from "./publicpricing.js"; -import { - TopProviderInfo, - TopProviderInfo$inboundSchema, -} from "./topproviderinfo.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { DefaultParameters } from './defaultparameters.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { ModelArchitecture } from './modelarchitecture.js'; +import type { Parameter } from './parameter.js'; +import type { PerRequestLimits } from './perrequestlimits.js'; +import type { PublicPricing } from './publicpricing.js'; +import type { TopProviderInfo } from './topproviderinfo.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { DefaultParameters$inboundSchema } from './defaultparameters.js'; +import { ModelArchitecture$inboundSchema } from './modelarchitecture.js'; +import { Parameter$inboundSchema } from './parameter.js'; +import { PerRequestLimits$inboundSchema } from './perrequestlimits.js'; +import { PublicPricing$inboundSchema } from './publicpricing.js'; +import { TopProviderInfo$inboundSchema } from './topproviderinfo.js'; /** * Information about an AI model available on OpenRouter @@ -86,35 +81,35 @@ export type Model = { }; /** @internal */ -export const Model$inboundSchema: z.ZodType = z.object({ - id: z.string(), - canonical_slug: z.string(), - hugging_face_id: z.nullable(z.string()).optional(), - name: z.string(), - created: z.number(), - description: z.string().optional(), - pricing: PublicPricing$inboundSchema, - context_length: z.nullable(z.number()), - architecture: ModelArchitecture$inboundSchema, - top_provider: TopProviderInfo$inboundSchema, - per_request_limits: z.nullable(PerRequestLimits$inboundSchema), - supported_parameters: z.array(Parameter$inboundSchema), - default_parameters: z.nullable(DefaultParameters$inboundSchema), -}).transform((v) => { - return remap$(v, { - "canonical_slug": "canonicalSlug", - "hugging_face_id": "huggingFaceId", - "context_length": "contextLength", - "top_provider": "topProvider", - "per_request_limits": "perRequestLimits", - "supported_parameters": "supportedParameters", - "default_parameters": "defaultParameters", +export const Model$inboundSchema: z.ZodType = z + .object({ + id: z.string(), + canonical_slug: z.string(), + hugging_face_id: z.nullable(z.string()).optional(), + name: z.string(), + created: z.number(), + description: z.string().optional(), + pricing: PublicPricing$inboundSchema, + context_length: z.nullable(z.number()), + architecture: ModelArchitecture$inboundSchema, + top_provider: TopProviderInfo$inboundSchema, + per_request_limits: z.nullable(PerRequestLimits$inboundSchema), + supported_parameters: z.array(Parameter$inboundSchema), + default_parameters: z.nullable(DefaultParameters$inboundSchema), + }) + .transform((v) => { + return remap$(v, { + canonical_slug: 'canonicalSlug', + hugging_face_id: 'huggingFaceId', + context_length: 'contextLength', + top_provider: 'topProvider', + per_request_limits: 'perRequestLimits', + supported_parameters: 'supportedParameters', + default_parameters: 'defaultParameters', + }); }); -}); -export function modelFromJSON( - jsonString: string, -): SafeParseResult { +export function modelFromJSON(jsonString: string): SafeParseResult { return safeParse( jsonString, (x) => Model$inboundSchema.parse(JSON.parse(x)), diff --git a/src/models/modelarchitecture.ts b/src/models/modelarchitecture.ts index 7b404df1..d2262e9d 100644 --- a/src/models/modelarchitecture.ts +++ b/src/models/modelarchitecture.ts @@ -3,53 +3,52 @@ * @generated-id: 57607576095f */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { InputModality, InputModality$inboundSchema } from "./inputmodality.js"; -import { ModelGroup, ModelGroup$inboundSchema } from "./modelgroup.js"; -import { - OutputModality, - OutputModality$inboundSchema, -} from "./outputmodality.js"; +import type { OpenEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { InputModality } from './inputmodality.js'; +import type { ModelGroup } from './modelgroup.js'; +import type { OutputModality } from './outputmodality.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import * as openEnums from '../types/enums.js'; +import { InputModality$inboundSchema } from './inputmodality.js'; +import { ModelGroup$inboundSchema } from './modelgroup.js'; +import { OutputModality$inboundSchema } from './outputmodality.js'; /** * Instruction format type */ export const ModelArchitectureInstructType = { - None: "none", - Airoboros: "airoboros", - Alpaca: "alpaca", - AlpacaModif: "alpaca-modif", - Chatml: "chatml", - Claude: "claude", - CodeLlama: "code-llama", - Gemma: "gemma", - Llama2: "llama2", - Llama3: "llama3", - Mistral: "mistral", - Nemotron: "nemotron", - Neural: "neural", - Openchat: "openchat", - Phi3: "phi3", - Rwkv: "rwkv", - Vicuna: "vicuna", - Zephyr: "zephyr", - DeepseekR1: "deepseek-r1", - DeepseekV31: "deepseek-v3.1", - Qwq: "qwq", - Qwen3: "qwen3", + None: 'none', + Airoboros: 'airoboros', + Alpaca: 'alpaca', + AlpacaModif: 'alpaca-modif', + Chatml: 'chatml', + Claude: 'claude', + CodeLlama: 'code-llama', + Gemma: 'gemma', + Llama2: 'llama2', + Llama3: 'llama3', + Mistral: 'mistral', + Nemotron: 'nemotron', + Neural: 'neural', + Openchat: 'openchat', + Phi3: 'phi3', + Rwkv: 'rwkv', + Vicuna: 'vicuna', + Zephyr: 'zephyr', + DeepseekR1: 'deepseek-r1', + DeepseekV31: 'deepseek-v3.1', + Qwq: 'qwq', + Qwen3: 'qwen3', } as const; /** * Instruction format type */ -export type ModelArchitectureInstructType = OpenEnum< - typeof ModelArchitectureInstructType ->; +export type ModelArchitectureInstructType = OpenEnum; /** * Model architecture information @@ -84,23 +83,21 @@ export const ModelArchitectureInstructType$inboundSchema: z.ZodType< > = openEnums.inboundSchema(ModelArchitectureInstructType); /** @internal */ -export const ModelArchitecture$inboundSchema: z.ZodType< - ModelArchitecture, - unknown -> = z.object({ - tokenizer: ModelGroup$inboundSchema.optional(), - instruct_type: z.nullable(ModelArchitectureInstructType$inboundSchema) - .optional(), - modality: z.nullable(z.string()), - input_modalities: z.array(InputModality$inboundSchema), - output_modalities: z.array(OutputModality$inboundSchema), -}).transform((v) => { - return remap$(v, { - "instruct_type": "instructType", - "input_modalities": "inputModalities", - "output_modalities": "outputModalities", +export const ModelArchitecture$inboundSchema: z.ZodType = z + .object({ + tokenizer: ModelGroup$inboundSchema.optional(), + instruct_type: z.nullable(ModelArchitectureInstructType$inboundSchema).optional(), + modality: z.nullable(z.string()), + input_modalities: z.array(InputModality$inboundSchema), + output_modalities: z.array(OutputModality$inboundSchema), + }) + .transform((v) => { + return remap$(v, { + instruct_type: 'instructType', + input_modalities: 'inputModalities', + output_modalities: 'outputModalities', + }); }); -}); export function modelArchitectureFromJSON( jsonString: string, diff --git a/src/models/modelgroup.ts b/src/models/modelgroup.ts index 9c40d281..8553de18 100644 --- a/src/models/modelgroup.ts +++ b/src/models/modelgroup.ts @@ -3,33 +3,34 @@ * @generated-id: b65482ec4223 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; /** * Tokenizer type used by the model */ export const ModelGroup = { - Router: "Router", - Media: "Media", - Other: "Other", - Gpt: "GPT", - Claude: "Claude", - Gemini: "Gemini", - Grok: "Grok", - Cohere: "Cohere", - Nova: "Nova", - Qwen: "Qwen", - Yi: "Yi", - DeepSeek: "DeepSeek", - Mistral: "Mistral", - Llama2: "Llama2", - Llama3: "Llama3", - Llama4: "Llama4", - PaLM: "PaLM", - Rwkv: "RWKV", - Qwen3: "Qwen3", + Router: 'Router', + Media: 'Media', + Other: 'Other', + Gpt: 'GPT', + Claude: 'Claude', + Gemini: 'Gemini', + Grok: 'Grok', + Cohere: 'Cohere', + Nova: 'Nova', + Qwen: 'Qwen', + Yi: 'Yi', + DeepSeek: 'DeepSeek', + Mistral: 'Mistral', + Llama2: 'Llama2', + Llama3: 'Llama3', + Llama4: 'Llama4', + PaLM: 'PaLM', + Rwkv: 'RWKV', + Qwen3: 'Qwen3', } as const; /** * Tokenizer type used by the model diff --git a/src/models/modelscountresponse.ts b/src/models/modelscountresponse.ts index cb6c47ea..e0522e7a 100644 --- a/src/models/modelscountresponse.ts +++ b/src/models/modelscountresponse.ts @@ -3,10 +3,11 @@ * @generated-id: cf41f6279453 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Model count data @@ -29,12 +30,10 @@ export type ModelsCountResponse = { }; /** @internal */ -export const ModelsCountResponseData$inboundSchema: z.ZodType< - ModelsCountResponseData, - unknown -> = z.object({ - count: z.number(), -}); +export const ModelsCountResponseData$inboundSchema: z.ZodType = + z.object({ + count: z.number(), + }); export function modelsCountResponseDataFromJSON( jsonString: string, @@ -47,10 +46,7 @@ export function modelsCountResponseDataFromJSON( } /** @internal */ -export const ModelsCountResponse$inboundSchema: z.ZodType< - ModelsCountResponse, - unknown -> = z.object({ +export const ModelsCountResponse$inboundSchema: z.ZodType = z.object({ data: z.lazy(() => ModelsCountResponseData$inboundSchema), }); diff --git a/src/models/modelslistresponse.ts b/src/models/modelslistresponse.ts index f3fae481..d0c76d32 100644 --- a/src/models/modelslistresponse.ts +++ b/src/models/modelslistresponse.ts @@ -3,11 +3,13 @@ * @generated-id: ea0e62a13d8d */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { Model, Model$inboundSchema } from "./model.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { Model } from './model.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import { Model$inboundSchema } from './model.js'; /** * List of available models @@ -20,10 +22,7 @@ export type ModelsListResponse = { }; /** @internal */ -export const ModelsListResponse$inboundSchema: z.ZodType< - ModelsListResponse, - unknown -> = z.object({ +export const ModelsListResponse$inboundSchema: z.ZodType = z.object({ data: z.array(Model$inboundSchema), }); diff --git a/src/models/namedtoolchoice.ts b/src/models/namedtoolchoice.ts index 1603f2c8..2b61e48b 100644 --- a/src/models/namedtoolchoice.ts +++ b/src/models/namedtoolchoice.ts @@ -3,14 +3,14 @@ * @generated-id: db68e36b6a77 */ -import * as z from "zod/v4"; +import * as z from 'zod/v4'; export type NamedToolChoiceFunction = { name: string; }; export type NamedToolChoice = { - type: "function"; + type: 'function'; function: NamedToolChoiceFunction; }; @@ -30,28 +30,22 @@ export const NamedToolChoiceFunction$outboundSchema: z.ZodType< export function namedToolChoiceFunctionToJSON( namedToolChoiceFunction: NamedToolChoiceFunction, ): string { - return JSON.stringify( - NamedToolChoiceFunction$outboundSchema.parse(namedToolChoiceFunction), - ); + return JSON.stringify(NamedToolChoiceFunction$outboundSchema.parse(namedToolChoiceFunction)); } /** @internal */ export type NamedToolChoice$Outbound = { - type: "function"; + type: 'function'; function: NamedToolChoiceFunction$Outbound; }; /** @internal */ -export const NamedToolChoice$outboundSchema: z.ZodType< - NamedToolChoice$Outbound, - NamedToolChoice -> = z.object({ - type: z.literal("function"), - function: z.lazy(() => NamedToolChoiceFunction$outboundSchema), -}); +export const NamedToolChoice$outboundSchema: z.ZodType = + z.object({ + type: z.literal('function'), + function: z.lazy(() => NamedToolChoiceFunction$outboundSchema), + }); -export function namedToolChoiceToJSON( - namedToolChoice: NamedToolChoice, -): string { +export function namedToolChoiceToJSON(namedToolChoice: NamedToolChoice): string { return JSON.stringify(NamedToolChoice$outboundSchema.parse(namedToolChoice)); } diff --git a/src/models/notfoundresponseerrordata.ts b/src/models/notfoundresponseerrordata.ts index aa237f7f..06bbe895 100644 --- a/src/models/notfoundresponseerrordata.ts +++ b/src/models/notfoundresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: 6c2943dd4f02 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for NotFoundResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type NotFoundResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ diff --git a/src/models/openairesponsesannotation.ts b/src/models/openairesponsesannotation.ts index c402006e..96bde29b 100644 --- a/src/models/openairesponsesannotation.ts +++ b/src/models/openairesponsesannotation.ts @@ -3,28 +3,17 @@ * @generated-id: 5828fa2314e3 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { - FileCitation, - FileCitation$inboundSchema, - FileCitation$Outbound, - FileCitation$outboundSchema, -} from "./filecitation.js"; -import { - FilePath, - FilePath$inboundSchema, - FilePath$Outbound, - FilePath$outboundSchema, -} from "./filepath.js"; -import { - URLCitation, - URLCitation$inboundSchema, - URLCitation$Outbound, - URLCitation$outboundSchema, -} from "./urlcitation.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { FileCitation, FileCitation$Outbound } from './filecitation.js'; +import type { FilePath, FilePath$Outbound } from './filepath.js'; +import type { URLCitation, URLCitation$Outbound } from './urlcitation.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import { FileCitation$inboundSchema, FileCitation$outboundSchema } from './filecitation.js'; +import { FilePath$inboundSchema, FilePath$outboundSchema } from './filepath.js'; +import { URLCitation$inboundSchema, URLCitation$outboundSchema } from './urlcitation.js'; export type OpenAIResponsesAnnotation = FileCitation | URLCitation | FilePath; @@ -56,9 +45,7 @@ export const OpenAIResponsesAnnotation$outboundSchema: z.ZodType< export function openAIResponsesAnnotationToJSON( openAIResponsesAnnotation: OpenAIResponsesAnnotation, ): string { - return JSON.stringify( - OpenAIResponsesAnnotation$outboundSchema.parse(openAIResponsesAnnotation), - ); + return JSON.stringify(OpenAIResponsesAnnotation$outboundSchema.parse(openAIResponsesAnnotation)); } export function openAIResponsesAnnotationFromJSON( jsonString: string, diff --git a/src/models/openairesponsesincludable.ts b/src/models/openairesponsesincludable.ts index ca3d42fe..c46313db 100644 --- a/src/models/openairesponsesincludable.ts +++ b/src/models/openairesponsesincludable.ts @@ -3,20 +3,19 @@ * @generated-id: 3b5ed15267fc */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const OpenAIResponsesIncludable = { - FileSearchCallResults: "file_search_call.results", - MessageInputImageImageUrl: "message.input_image.image_url", - ComputerCallOutputOutputImageUrl: "computer_call_output.output.image_url", - ReasoningEncryptedContent: "reasoning.encrypted_content", - CodeInterpreterCallOutputs: "code_interpreter_call.outputs", + FileSearchCallResults: 'file_search_call.results', + MessageInputImageImageUrl: 'message.input_image.image_url', + ComputerCallOutputOutputImageUrl: 'computer_call_output.output.image_url', + ReasoningEncryptedContent: 'reasoning.encrypted_content', + CodeInterpreterCallOutputs: 'code_interpreter_call.outputs', } as const; -export type OpenAIResponsesIncludable = OpenEnum< - typeof OpenAIResponsesIncludable ->; +export type OpenAIResponsesIncludable = OpenEnum; /** @internal */ export const OpenAIResponsesIncludable$outboundSchema: z.ZodType< diff --git a/src/models/openairesponsesincompletedetails.ts b/src/models/openairesponsesincompletedetails.ts index 0e524e09..c33615c7 100644 --- a/src/models/openairesponsesincompletedetails.ts +++ b/src/models/openairesponsesincompletedetails.ts @@ -3,16 +3,17 @@ * @generated-id: f2aabee6a438 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { OpenEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import * as openEnums from '../types/enums.js'; export const Reason = { - MaxOutputTokens: "max_output_tokens", - ContentFilter: "content_filter", + MaxOutputTokens: 'max_output_tokens', + ContentFilter: 'content_filter', } as const; export type Reason = OpenEnum; @@ -21,8 +22,7 @@ export type OpenAIResponsesIncompleteDetails = { }; /** @internal */ -export const Reason$inboundSchema: z.ZodType = openEnums - .inboundSchema(Reason); +export const Reason$inboundSchema: z.ZodType = openEnums.inboundSchema(Reason); /** @internal */ export const OpenAIResponsesIncompleteDetails$inboundSchema: z.ZodType< diff --git a/src/models/openairesponsesinputunion.ts b/src/models/openairesponsesinputunion.ts index b840e414..c41ab9d6 100644 --- a/src/models/openairesponsesinputunion.ts +++ b/src/models/openairesponsesinputunion.ts @@ -3,40 +3,30 @@ * @generated-id: 0b061e126936 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { - OutputItemImageGenerationCall, - OutputItemImageGenerationCall$inboundSchema, -} from "./outputitemimagegenerationcall.js"; -import { OutputMessage, OutputMessage$inboundSchema } from "./outputmessage.js"; -import { - ResponseInputAudio, - ResponseInputAudio$inboundSchema, -} from "./responseinputaudio.js"; -import { - ResponseInputFile, - ResponseInputFile$inboundSchema, -} from "./responseinputfile.js"; -import { - ResponseInputImage, - ResponseInputImage$inboundSchema, -} from "./responseinputimage.js"; -import { - ResponseInputText, - ResponseInputText$inboundSchema, -} from "./responseinputtext.js"; -import { - ToolCallStatus, - ToolCallStatus$inboundSchema, -} from "./toolcallstatus.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { OutputItemImageGenerationCall } from './outputitemimagegenerationcall.js'; +import type { OutputMessage } from './outputmessage.js'; +import type { ResponseInputAudio } from './responseinputaudio.js'; +import type { ResponseInputFile } from './responseinputfile.js'; +import type { ResponseInputImage } from './responseinputimage.js'; +import type { ResponseInputText } from './responseinputtext.js'; +import type { ToolCallStatus } from './toolcallstatus.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { OutputItemImageGenerationCall$inboundSchema } from './outputitemimagegenerationcall.js'; +import { OutputMessage$inboundSchema } from './outputmessage.js'; +import { ResponseInputAudio$inboundSchema } from './responseinputaudio.js'; +import { ResponseInputFile$inboundSchema } from './responseinputfile.js'; +import { ResponseInputImage$inboundSchema } from './responseinputimage.js'; +import { ResponseInputText$inboundSchema } from './responseinputtext.js'; +import { ToolCallStatus$inboundSchema } from './toolcallstatus.js'; export const OpenAIResponsesInputTypeFunctionCall = { - FunctionCall: "function_call", + FunctionCall: 'function_call', } as const; export type OpenAIResponsesInputTypeFunctionCall = ClosedEnum< typeof OpenAIResponsesInputTypeFunctionCall @@ -52,7 +42,7 @@ export type OpenAIResponsesInputFunctionCall = { }; export const OpenAIResponsesInputTypeFunctionCallOutput = { - FunctionCallOutput: "function_call_output", + FunctionCallOutput: 'function_call_output', } as const; export type OpenAIResponsesInputTypeFunctionCallOutput = ClosedEnum< typeof OpenAIResponsesInputTypeFunctionCallOutput @@ -67,32 +57,26 @@ export type OpenAIResponsesInputFunctionCallOutput = { }; export const OpenAIResponsesInputTypeMessage2 = { - Message: "message", + Message: 'message', } as const; -export type OpenAIResponsesInputTypeMessage2 = ClosedEnum< - typeof OpenAIResponsesInputTypeMessage2 ->; +export type OpenAIResponsesInputTypeMessage2 = ClosedEnum; export const OpenAIResponsesInputRoleDeveloper2 = { - Developer: "developer", + Developer: 'developer', } as const; export type OpenAIResponsesInputRoleDeveloper2 = ClosedEnum< typeof OpenAIResponsesInputRoleDeveloper2 >; export const OpenAIResponsesInputRoleSystem2 = { - System: "system", + System: 'system', } as const; -export type OpenAIResponsesInputRoleSystem2 = ClosedEnum< - typeof OpenAIResponsesInputRoleSystem2 ->; +export type OpenAIResponsesInputRoleSystem2 = ClosedEnum; export const OpenAIResponsesInputRoleUser2 = { - User: "user", + User: 'user', } as const; -export type OpenAIResponsesInputRoleUser2 = ClosedEnum< - typeof OpenAIResponsesInputRoleUser2 ->; +export type OpenAIResponsesInputRoleUser2 = ClosedEnum; export type OpenAIResponsesInputRoleUnion2 = | OpenAIResponsesInputRoleUser2 @@ -112,48 +96,37 @@ export type OpenAIResponsesInputMessage2 = { | OpenAIResponsesInputRoleUser2 | OpenAIResponsesInputRoleSystem2 | OpenAIResponsesInputRoleDeveloper2; - content: Array< - | ResponseInputText - | ResponseInputImage - | ResponseInputFile - | ResponseInputAudio - >; + content: Array; }; export const OpenAIResponsesInputTypeMessage1 = { - Message: "message", + Message: 'message', } as const; -export type OpenAIResponsesInputTypeMessage1 = ClosedEnum< - typeof OpenAIResponsesInputTypeMessage1 ->; +export type OpenAIResponsesInputTypeMessage1 = ClosedEnum; export const OpenAIResponsesInputRoleDeveloper1 = { - Developer: "developer", + Developer: 'developer', } as const; export type OpenAIResponsesInputRoleDeveloper1 = ClosedEnum< typeof OpenAIResponsesInputRoleDeveloper1 >; export const OpenAIResponsesInputRoleAssistant = { - Assistant: "assistant", + Assistant: 'assistant', } as const; export type OpenAIResponsesInputRoleAssistant = ClosedEnum< typeof OpenAIResponsesInputRoleAssistant >; export const OpenAIResponsesInputRoleSystem1 = { - System: "system", + System: 'system', } as const; -export type OpenAIResponsesInputRoleSystem1 = ClosedEnum< - typeof OpenAIResponsesInputRoleSystem1 ->; +export type OpenAIResponsesInputRoleSystem1 = ClosedEnum; export const OpenAIResponsesInputRoleUser1 = { - User: "user", + User: 'user', } as const; -export type OpenAIResponsesInputRoleUser1 = ClosedEnum< - typeof OpenAIResponsesInputRoleUser1 ->; +export type OpenAIResponsesInputRoleUser1 = ClosedEnum; export type OpenAIResponsesInputRoleUnion1 = | OpenAIResponsesInputRoleUser1 @@ -168,12 +141,7 @@ export type OpenAIResponsesInputContent1 = | ResponseInputAudio; export type OpenAIResponsesInputContent2 = - | Array< - | ResponseInputText - | ResponseInputImage - | ResponseInputFile - | ResponseInputAudio - > + | Array | string; export type OpenAIResponsesInputMessage1 = { @@ -184,12 +152,7 @@ export type OpenAIResponsesInputMessage1 = { | OpenAIResponsesInputRoleAssistant | OpenAIResponsesInputRoleDeveloper1; content: - | Array< - | ResponseInputText - | ResponseInputImage - | ResponseInputFile - | ResponseInputAudio - > + | Array | string; }; @@ -204,13 +167,13 @@ export type OpenAIResponsesInputUnion1 = export type OpenAIResponsesInputUnion = | string | Array< - | OpenAIResponsesInputFunctionCall - | OutputMessage - | OpenAIResponsesInputMessage2 - | OpenAIResponsesInputFunctionCallOutput - | OutputItemImageGenerationCall - | OpenAIResponsesInputMessage1 - > + | OpenAIResponsesInputFunctionCall + | OutputMessage + | OpenAIResponsesInputMessage2 + | OpenAIResponsesInputFunctionCallOutput + | OutputItemImageGenerationCall + | OpenAIResponsesInputMessage1 + > | any; /** @internal */ @@ -222,18 +185,20 @@ export const OpenAIResponsesInputTypeFunctionCall$inboundSchema: z.ZodEnum< export const OpenAIResponsesInputFunctionCall$inboundSchema: z.ZodType< OpenAIResponsesInputFunctionCall, unknown -> = z.object({ - type: OpenAIResponsesInputTypeFunctionCall$inboundSchema, - call_id: z.string(), - name: z.string(), - arguments: z.string(), - id: z.string().optional(), - status: z.nullable(ToolCallStatus$inboundSchema).optional(), -}).transform((v) => { - return remap$(v, { - "call_id": "callId", +> = z + .object({ + type: OpenAIResponsesInputTypeFunctionCall$inboundSchema, + call_id: z.string(), + name: z.string(), + arguments: z.string(), + id: z.string().optional(), + status: z.nullable(ToolCallStatus$inboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + call_id: 'callId', + }); }); -}); export function openAIResponsesInputFunctionCallFromJSON( jsonString: string, @@ -246,34 +211,34 @@ export function openAIResponsesInputFunctionCallFromJSON( } /** @internal */ -export const OpenAIResponsesInputTypeFunctionCallOutput$inboundSchema: - z.ZodEnum = z.enum( - OpenAIResponsesInputTypeFunctionCallOutput, - ); +export const OpenAIResponsesInputTypeFunctionCallOutput$inboundSchema: z.ZodEnum< + typeof OpenAIResponsesInputTypeFunctionCallOutput +> = z.enum(OpenAIResponsesInputTypeFunctionCallOutput); /** @internal */ export const OpenAIResponsesInputFunctionCallOutput$inboundSchema: z.ZodType< OpenAIResponsesInputFunctionCallOutput, unknown -> = z.object({ - type: OpenAIResponsesInputTypeFunctionCallOutput$inboundSchema, - id: z.nullable(z.string()).optional(), - call_id: z.string(), - output: z.string(), - status: z.nullable(ToolCallStatus$inboundSchema).optional(), -}).transform((v) => { - return remap$(v, { - "call_id": "callId", +> = z + .object({ + type: OpenAIResponsesInputTypeFunctionCallOutput$inboundSchema, + id: z.nullable(z.string()).optional(), + call_id: z.string(), + output: z.string(), + status: z.nullable(ToolCallStatus$inboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + call_id: 'callId', + }); }); -}); export function openAIResponsesInputFunctionCallOutputFromJSON( jsonString: string, ): SafeParseResult { return safeParse( jsonString, - (x) => - OpenAIResponsesInputFunctionCallOutput$inboundSchema.parse(JSON.parse(x)), + (x) => OpenAIResponsesInputFunctionCallOutput$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenAIResponsesInputFunctionCallOutput' from JSON`, ); } @@ -528,14 +493,16 @@ export const OpenAIResponsesInputUnion$inboundSchema: z.ZodType< unknown > = z.union([ z.string(), - z.array(z.union([ - z.lazy(() => OpenAIResponsesInputFunctionCall$inboundSchema), - OutputMessage$inboundSchema, - z.lazy(() => OpenAIResponsesInputMessage2$inboundSchema), - z.lazy(() => OpenAIResponsesInputFunctionCallOutput$inboundSchema), - OutputItemImageGenerationCall$inboundSchema, - z.lazy(() => OpenAIResponsesInputMessage1$inboundSchema), - ])), + z.array( + z.union([ + z.lazy(() => OpenAIResponsesInputFunctionCall$inboundSchema), + OutputMessage$inboundSchema, + z.lazy(() => OpenAIResponsesInputMessage2$inboundSchema), + z.lazy(() => OpenAIResponsesInputFunctionCallOutput$inboundSchema), + OutputItemImageGenerationCall$inboundSchema, + z.lazy(() => OpenAIResponsesInputMessage1$inboundSchema), + ]), + ), z.any(), ]); diff --git a/src/models/openairesponsesprompt.ts b/src/models/openairesponsesprompt.ts index faf39e85..20d73e51 100644 --- a/src/models/openairesponsesprompt.ts +++ b/src/models/openairesponsesprompt.ts @@ -3,45 +3,35 @@ * @generated-id: c583d897e9d2 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { ResponseInputFile, ResponseInputFile$Outbound } from './responseinputfile.js'; +import type { ResponseInputImage, ResponseInputImage$Outbound } from './responseinputimage.js'; +import type { ResponseInputText, ResponseInputText$Outbound } from './responseinputtext.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; import { - ResponseInputFile, ResponseInputFile$inboundSchema, - ResponseInputFile$Outbound, ResponseInputFile$outboundSchema, -} from "./responseinputfile.js"; +} from './responseinputfile.js'; import { - ResponseInputImage, ResponseInputImage$inboundSchema, - ResponseInputImage$Outbound, ResponseInputImage$outboundSchema, -} from "./responseinputimage.js"; +} from './responseinputimage.js'; import { - ResponseInputText, ResponseInputText$inboundSchema, - ResponseInputText$Outbound, ResponseInputText$outboundSchema, -} from "./responseinputtext.js"; +} from './responseinputtext.js'; -export type Variables = - | ResponseInputText - | ResponseInputImage - | ResponseInputFile - | string; +export type Variables = ResponseInputText | ResponseInputImage | ResponseInputFile | string; export type OpenAIResponsesPrompt = { id: string; variables?: | { - [k: string]: - | ResponseInputText - | ResponseInputImage - | ResponseInputFile - | string; - } + [k: string]: ResponseInputText | ResponseInputImage | ResponseInputFile | string; + } | null | undefined; }; @@ -61,10 +51,7 @@ export type Variables$Outbound = | string; /** @internal */ -export const Variables$outboundSchema: z.ZodType< - Variables$Outbound, - Variables -> = z.union([ +export const Variables$outboundSchema: z.ZodType = z.union([ ResponseInputText$outboundSchema, ResponseInputImage$outboundSchema, ResponseInputFile$outboundSchema, @@ -85,34 +72,34 @@ export function variablesFromJSON( } /** @internal */ -export const OpenAIResponsesPrompt$inboundSchema: z.ZodType< - OpenAIResponsesPrompt, - unknown -> = z.object({ - id: z.string(), - variables: z.nullable( - z.record( - z.string(), - z.union([ - ResponseInputText$inboundSchema, - ResponseInputImage$inboundSchema, - ResponseInputFile$inboundSchema, - z.string(), - ]), - ), - ).optional(), -}); +export const OpenAIResponsesPrompt$inboundSchema: z.ZodType = + z.object({ + id: z.string(), + variables: z + .nullable( + z.record( + z.string(), + z.union([ + ResponseInputText$inboundSchema, + ResponseInputImage$inboundSchema, + ResponseInputFile$inboundSchema, + z.string(), + ]), + ), + ) + .optional(), + }); /** @internal */ export type OpenAIResponsesPrompt$Outbound = { id: string; variables?: | { - [k: string]: - | ResponseInputText$Outbound - | ResponseInputImage$Outbound - | ResponseInputFile$Outbound - | string; - } + [k: string]: + | ResponseInputText$Outbound + | ResponseInputImage$Outbound + | ResponseInputFile$Outbound + | string; + } | null | undefined; }; @@ -123,25 +110,23 @@ export const OpenAIResponsesPrompt$outboundSchema: z.ZodType< OpenAIResponsesPrompt > = z.object({ id: z.string(), - variables: z.nullable( - z.record( - z.string(), - z.union([ - ResponseInputText$outboundSchema, - ResponseInputImage$outboundSchema, - ResponseInputFile$outboundSchema, + variables: z + .nullable( + z.record( z.string(), - ]), - ), - ).optional(), + z.union([ + ResponseInputText$outboundSchema, + ResponseInputImage$outboundSchema, + ResponseInputFile$outboundSchema, + z.string(), + ]), + ), + ) + .optional(), }); -export function openAIResponsesPromptToJSON( - openAIResponsesPrompt: OpenAIResponsesPrompt, -): string { - return JSON.stringify( - OpenAIResponsesPrompt$outboundSchema.parse(openAIResponsesPrompt), - ); +export function openAIResponsesPromptToJSON(openAIResponsesPrompt: OpenAIResponsesPrompt): string { + return JSON.stringify(OpenAIResponsesPrompt$outboundSchema.parse(openAIResponsesPrompt)); } export function openAIResponsesPromptFromJSON( jsonString: string, diff --git a/src/models/openairesponsesreasoningconfig.ts b/src/models/openairesponsesreasoningconfig.ts index eeea2c05..94d83a49 100644 --- a/src/models/openairesponsesreasoningconfig.ts +++ b/src/models/openairesponsesreasoningconfig.ts @@ -3,18 +3,15 @@ * @generated-id: 60a66fbc6068 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { - OpenAIResponsesReasoningEffort, - OpenAIResponsesReasoningEffort$inboundSchema, -} from "./openairesponsesreasoningeffort.js"; -import { - ReasoningSummaryVerbosity, - ReasoningSummaryVerbosity$inboundSchema, -} from "./reasoningsummaryverbosity.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { OpenAIResponsesReasoningEffort } from './openairesponsesreasoningeffort.js'; +import type { ReasoningSummaryVerbosity } from './reasoningsummaryverbosity.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import { OpenAIResponsesReasoningEffort$inboundSchema } from './openairesponsesreasoningeffort.js'; +import { ReasoningSummaryVerbosity$inboundSchema } from './reasoningsummaryverbosity.js'; export type OpenAIResponsesReasoningConfig = { effort?: OpenAIResponsesReasoningEffort | null | undefined; diff --git a/src/models/openairesponsesreasoningeffort.ts b/src/models/openairesponsesreasoningeffort.ts index 9d53b5f5..a8ef3c9c 100644 --- a/src/models/openairesponsesreasoningeffort.ts +++ b/src/models/openairesponsesreasoningeffort.ts @@ -3,21 +3,20 @@ * @generated-id: af69873eff63 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const OpenAIResponsesReasoningEffort = { - Xhigh: "xhigh", - High: "high", - Medium: "medium", - Low: "low", - Minimal: "minimal", - None: "none", + Xhigh: 'xhigh', + High: 'high', + Medium: 'medium', + Low: 'low', + Minimal: 'minimal', + None: 'none', } as const; -export type OpenAIResponsesReasoningEffort = OpenEnum< - typeof OpenAIResponsesReasoningEffort ->; +export type OpenAIResponsesReasoningEffort = OpenEnum; /** @internal */ export const OpenAIResponsesReasoningEffort$inboundSchema: z.ZodType< diff --git a/src/models/openairesponsesrefusalcontent.ts b/src/models/openairesponsesrefusalcontent.ts index 2252e00a..6df11851 100644 --- a/src/models/openairesponsesrefusalcontent.ts +++ b/src/models/openairesponsesrefusalcontent.ts @@ -3,13 +3,14 @@ * @generated-id: 5445ae4a5385 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; export type OpenAIResponsesRefusalContent = { - type: "refusal"; + type: 'refusal'; refusal: string; }; @@ -18,12 +19,12 @@ export const OpenAIResponsesRefusalContent$inboundSchema: z.ZodType< OpenAIResponsesRefusalContent, unknown > = z.object({ - type: z.literal("refusal"), + type: z.literal('refusal'), refusal: z.string(), }); /** @internal */ export type OpenAIResponsesRefusalContent$Outbound = { - type: "refusal"; + type: 'refusal'; refusal: string; }; @@ -32,7 +33,7 @@ export const OpenAIResponsesRefusalContent$outboundSchema: z.ZodType< OpenAIResponsesRefusalContent$Outbound, OpenAIResponsesRefusalContent > = z.object({ - type: z.literal("refusal"), + type: z.literal('refusal'), refusal: z.string(), }); @@ -40,9 +41,7 @@ export function openAIResponsesRefusalContentToJSON( openAIResponsesRefusalContent: OpenAIResponsesRefusalContent, ): string { return JSON.stringify( - OpenAIResponsesRefusalContent$outboundSchema.parse( - openAIResponsesRefusalContent, - ), + OpenAIResponsesRefusalContent$outboundSchema.parse(openAIResponsesRefusalContent), ); } export function openAIResponsesRefusalContentFromJSON( diff --git a/src/models/openairesponsesresponsestatus.ts b/src/models/openairesponsesresponsestatus.ts index aea8bf92..8023fe83 100644 --- a/src/models/openairesponsesresponsestatus.ts +++ b/src/models/openairesponsesresponsestatus.ts @@ -3,21 +3,20 @@ * @generated-id: b721d7085e40 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const OpenAIResponsesResponseStatus = { - Completed: "completed", - Incomplete: "incomplete", - InProgress: "in_progress", - Failed: "failed", - Cancelled: "cancelled", - Queued: "queued", + Completed: 'completed', + Incomplete: 'incomplete', + InProgress: 'in_progress', + Failed: 'failed', + Cancelled: 'cancelled', + Queued: 'queued', } as const; -export type OpenAIResponsesResponseStatus = OpenEnum< - typeof OpenAIResponsesResponseStatus ->; +export type OpenAIResponsesResponseStatus = OpenEnum; /** @internal */ export const OpenAIResponsesResponseStatus$inboundSchema: z.ZodType< diff --git a/src/models/openairesponsesservicetier.ts b/src/models/openairesponsesservicetier.ts index 8299718d..90e9057e 100644 --- a/src/models/openairesponsesservicetier.ts +++ b/src/models/openairesponsesservicetier.ts @@ -3,20 +3,19 @@ * @generated-id: 88b4cb1f9919 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const OpenAIResponsesServiceTier = { - Auto: "auto", - Default: "default", - Flex: "flex", - Priority: "priority", - Scale: "scale", + Auto: 'auto', + Default: 'default', + Flex: 'flex', + Priority: 'priority', + Scale: 'scale', } as const; -export type OpenAIResponsesServiceTier = OpenEnum< - typeof OpenAIResponsesServiceTier ->; +export type OpenAIResponsesServiceTier = OpenEnum; /** @internal */ export const OpenAIResponsesServiceTier$inboundSchema: z.ZodType< diff --git a/src/models/openairesponsestoolchoiceunion.ts b/src/models/openairesponsestoolchoiceunion.ts index f35263df..dc929210 100644 --- a/src/models/openairesponsestoolchoiceunion.ts +++ b/src/models/openairesponsestoolchoiceunion.ts @@ -3,21 +3,22 @@ * @generated-id: 73d80db9cd46 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; export const OpenAIResponsesToolChoiceTypeWebSearchPreview = { - WebSearchPreview: "web_search_preview", + WebSearchPreview: 'web_search_preview', } as const; export type OpenAIResponsesToolChoiceTypeWebSearchPreview = ClosedEnum< typeof OpenAIResponsesToolChoiceTypeWebSearchPreview >; export const OpenAIResponsesToolChoiceTypeWebSearchPreview20250311 = { - WebSearchPreview20250311: "web_search_preview_2025_03_11", + WebSearchPreview20250311: 'web_search_preview_2025_03_11', } as const; export type OpenAIResponsesToolChoiceTypeWebSearchPreview20250311 = ClosedEnum< typeof OpenAIResponsesToolChoiceTypeWebSearchPreview20250311 @@ -34,7 +35,7 @@ export type OpenAIResponsesToolChoice = { }; export const OpenAIResponsesToolChoiceTypeFunction = { - Function: "function", + Function: 'function', } as const; export type OpenAIResponsesToolChoiceTypeFunction = ClosedEnum< typeof OpenAIResponsesToolChoiceTypeFunction @@ -46,25 +47,21 @@ export type OpenAIResponsesToolChoiceFunction = { }; export const OpenAIResponsesToolChoiceRequired = { - Required: "required", + Required: 'required', } as const; export type OpenAIResponsesToolChoiceRequired = ClosedEnum< typeof OpenAIResponsesToolChoiceRequired >; export const OpenAIResponsesToolChoiceNone = { - None: "none", + None: 'none', } as const; -export type OpenAIResponsesToolChoiceNone = ClosedEnum< - typeof OpenAIResponsesToolChoiceNone ->; +export type OpenAIResponsesToolChoiceNone = ClosedEnum; export const OpenAIResponsesToolChoiceAuto = { - Auto: "auto", + Auto: 'auto', } as const; -export type OpenAIResponsesToolChoiceAuto = ClosedEnum< - typeof OpenAIResponsesToolChoiceAuto ->; +export type OpenAIResponsesToolChoiceAuto = ClosedEnum; export type OpenAIResponsesToolChoiceUnion = | OpenAIResponsesToolChoiceFunction @@ -74,23 +71,22 @@ export type OpenAIResponsesToolChoiceUnion = | OpenAIResponsesToolChoiceRequired; /** @internal */ -export const OpenAIResponsesToolChoiceTypeWebSearchPreview$inboundSchema: - z.ZodEnum = z.enum( - OpenAIResponsesToolChoiceTypeWebSearchPreview, - ); +export const OpenAIResponsesToolChoiceTypeWebSearchPreview$inboundSchema: z.ZodEnum< + typeof OpenAIResponsesToolChoiceTypeWebSearchPreview +> = z.enum(OpenAIResponsesToolChoiceTypeWebSearchPreview); /** @internal */ -export const OpenAIResponsesToolChoiceTypeWebSearchPreview$outboundSchema: - z.ZodEnum = - OpenAIResponsesToolChoiceTypeWebSearchPreview$inboundSchema; +export const OpenAIResponsesToolChoiceTypeWebSearchPreview$outboundSchema: z.ZodEnum< + typeof OpenAIResponsesToolChoiceTypeWebSearchPreview +> = OpenAIResponsesToolChoiceTypeWebSearchPreview$inboundSchema; /** @internal */ -export const OpenAIResponsesToolChoiceTypeWebSearchPreview20250311$inboundSchema: - z.ZodEnum = z - .enum(OpenAIResponsesToolChoiceTypeWebSearchPreview20250311); +export const OpenAIResponsesToolChoiceTypeWebSearchPreview20250311$inboundSchema: z.ZodEnum< + typeof OpenAIResponsesToolChoiceTypeWebSearchPreview20250311 +> = z.enum(OpenAIResponsesToolChoiceTypeWebSearchPreview20250311); /** @internal */ -export const OpenAIResponsesToolChoiceTypeWebSearchPreview20250311$outboundSchema: - z.ZodEnum = - OpenAIResponsesToolChoiceTypeWebSearchPreview20250311$inboundSchema; +export const OpenAIResponsesToolChoiceTypeWebSearchPreview20250311$outboundSchema: z.ZodEnum< + typeof OpenAIResponsesToolChoiceTypeWebSearchPreview20250311 +> = OpenAIResponsesToolChoiceTypeWebSearchPreview20250311$inboundSchema; /** @internal */ export const Type$inboundSchema: z.ZodType = z.union([ @@ -109,9 +105,7 @@ export const Type$outboundSchema: z.ZodType = z.union([ export function typeToJSON(type: Type): string { return JSON.stringify(Type$outboundSchema.parse(type)); } -export function typeFromJSON( - jsonString: string, -): SafeParseResult { +export function typeFromJSON(jsonString: string): SafeParseResult { return safeParse( jsonString, (x) => Type$inboundSchema.parse(JSON.parse(x)), @@ -148,9 +142,7 @@ export const OpenAIResponsesToolChoice$outboundSchema: z.ZodType< export function openAIResponsesToolChoiceToJSON( openAIResponsesToolChoice: OpenAIResponsesToolChoice, ): string { - return JSON.stringify( - OpenAIResponsesToolChoice$outboundSchema.parse(openAIResponsesToolChoice), - ); + return JSON.stringify(OpenAIResponsesToolChoice$outboundSchema.parse(openAIResponsesToolChoice)); } export function openAIResponsesToolChoiceFromJSON( jsonString: string, @@ -198,9 +190,7 @@ export function openAIResponsesToolChoiceFunctionToJSON( openAIResponsesToolChoiceFunction: OpenAIResponsesToolChoiceFunction, ): string { return JSON.stringify( - OpenAIResponsesToolChoiceFunction$outboundSchema.parse( - openAIResponsesToolChoiceFunction, - ), + OpenAIResponsesToolChoiceFunction$outboundSchema.parse(openAIResponsesToolChoiceFunction), ); } export function openAIResponsesToolChoiceFunctionFromJSON( @@ -275,9 +265,7 @@ export function openAIResponsesToolChoiceUnionToJSON( openAIResponsesToolChoiceUnion: OpenAIResponsesToolChoiceUnion, ): string { return JSON.stringify( - OpenAIResponsesToolChoiceUnion$outboundSchema.parse( - openAIResponsesToolChoiceUnion, - ), + OpenAIResponsesToolChoiceUnion$outboundSchema.parse(openAIResponsesToolChoiceUnion), ); } export function openAIResponsesToolChoiceUnionFromJSON( diff --git a/src/models/openairesponsestruncation.ts b/src/models/openairesponsestruncation.ts index b307aa9d..9ec94dc9 100644 --- a/src/models/openairesponsestruncation.ts +++ b/src/models/openairesponsestruncation.ts @@ -3,17 +3,16 @@ * @generated-id: 03de9ac74888 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const OpenAIResponsesTruncation = { - Auto: "auto", - Disabled: "disabled", + Auto: 'auto', + Disabled: 'disabled', } as const; -export type OpenAIResponsesTruncation = OpenEnum< - typeof OpenAIResponsesTruncation ->; +export type OpenAIResponsesTruncation = OpenEnum; /** @internal */ export const OpenAIResponsesTruncation$inboundSchema: z.ZodType< diff --git a/src/models/openresponseseasyinputmessage.ts b/src/models/openresponseseasyinputmessage.ts index dedeed37..a11fae88 100644 --- a/src/models/openresponseseasyinputmessage.ts +++ b/src/models/openresponseseasyinputmessage.ts @@ -3,59 +3,48 @@ * @generated-id: 9cae543ceb47 */ -import * as z from "zod/v4"; -import { ClosedEnum } from "../types/enums.js"; -import { - ResponseInputAudio, - ResponseInputAudio$Outbound, - ResponseInputAudio$outboundSchema, -} from "./responseinputaudio.js"; -import { - ResponseInputFile, - ResponseInputFile$Outbound, - ResponseInputFile$outboundSchema, -} from "./responseinputfile.js"; -import { - ResponseInputImage, - ResponseInputImage$Outbound, - ResponseInputImage$outboundSchema, -} from "./responseinputimage.js"; -import { - ResponseInputText, - ResponseInputText$Outbound, - ResponseInputText$outboundSchema, -} from "./responseinputtext.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { ResponseInputAudio, ResponseInputAudio$Outbound } from './responseinputaudio.js'; +import type { ResponseInputFile, ResponseInputFile$Outbound } from './responseinputfile.js'; +import type { ResponseInputImage, ResponseInputImage$Outbound } from './responseinputimage.js'; +import type { ResponseInputText, ResponseInputText$Outbound } from './responseinputtext.js'; + +import * as z from 'zod/v4'; +import { ResponseInputAudio$outboundSchema } from './responseinputaudio.js'; +import { ResponseInputFile$outboundSchema } from './responseinputfile.js'; +import { ResponseInputImage$outboundSchema } from './responseinputimage.js'; +import { ResponseInputText$outboundSchema } from './responseinputtext.js'; export const OpenResponsesEasyInputMessageType = { - Message: "message", + Message: 'message', } as const; export type OpenResponsesEasyInputMessageType = ClosedEnum< typeof OpenResponsesEasyInputMessageType >; export const OpenResponsesEasyInputMessageRoleDeveloper = { - Developer: "developer", + Developer: 'developer', } as const; export type OpenResponsesEasyInputMessageRoleDeveloper = ClosedEnum< typeof OpenResponsesEasyInputMessageRoleDeveloper >; export const OpenResponsesEasyInputMessageRoleAssistant = { - Assistant: "assistant", + Assistant: 'assistant', } as const; export type OpenResponsesEasyInputMessageRoleAssistant = ClosedEnum< typeof OpenResponsesEasyInputMessageRoleAssistant >; export const OpenResponsesEasyInputMessageRoleSystem = { - System: "system", + System: 'system', } as const; export type OpenResponsesEasyInputMessageRoleSystem = ClosedEnum< typeof OpenResponsesEasyInputMessageRoleSystem >; export const OpenResponsesEasyInputMessageRoleUser = { - User: "user", + User: 'user', } as const; export type OpenResponsesEasyInputMessageRoleUser = ClosedEnum< typeof OpenResponsesEasyInputMessageRoleUser @@ -74,12 +63,7 @@ export type OpenResponsesEasyInputMessageContent1 = | ResponseInputAudio; export type OpenResponsesEasyInputMessageContent2 = - | Array< - | ResponseInputText - | ResponseInputImage - | ResponseInputFile - | ResponseInputAudio - > + | Array | string; export type OpenResponsesEasyInputMessage = { @@ -90,12 +74,7 @@ export type OpenResponsesEasyInputMessage = { | OpenResponsesEasyInputMessageRoleAssistant | OpenResponsesEasyInputMessageRoleDeveloper; content: - | Array< - | ResponseInputText - | ResponseInputImage - | ResponseInputFile - | ResponseInputAudio - > + | Array | string; }; @@ -105,16 +84,14 @@ export const OpenResponsesEasyInputMessageType$outboundSchema: z.ZodEnum< > = z.enum(OpenResponsesEasyInputMessageType); /** @internal */ -export const OpenResponsesEasyInputMessageRoleDeveloper$outboundSchema: - z.ZodEnum = z.enum( - OpenResponsesEasyInputMessageRoleDeveloper, - ); +export const OpenResponsesEasyInputMessageRoleDeveloper$outboundSchema: z.ZodEnum< + typeof OpenResponsesEasyInputMessageRoleDeveloper +> = z.enum(OpenResponsesEasyInputMessageRoleDeveloper); /** @internal */ -export const OpenResponsesEasyInputMessageRoleAssistant$outboundSchema: - z.ZodEnum = z.enum( - OpenResponsesEasyInputMessageRoleAssistant, - ); +export const OpenResponsesEasyInputMessageRoleAssistant$outboundSchema: z.ZodEnum< + typeof OpenResponsesEasyInputMessageRoleAssistant +> = z.enum(OpenResponsesEasyInputMessageRoleAssistant); /** @internal */ export const OpenResponsesEasyInputMessageRoleSystem$outboundSchema: z.ZodEnum< @@ -127,11 +104,7 @@ export const OpenResponsesEasyInputMessageRoleUser$outboundSchema: z.ZodEnum< > = z.enum(OpenResponsesEasyInputMessageRoleUser); /** @internal */ -export type OpenResponsesEasyInputMessageRoleUnion$Outbound = - | string - | string - | string - | string; +export type OpenResponsesEasyInputMessageRoleUnion$Outbound = string | string | string | string; /** @internal */ export const OpenResponsesEasyInputMessageRoleUnion$outboundSchema: z.ZodType< @@ -145,8 +118,7 @@ export const OpenResponsesEasyInputMessageRoleUnion$outboundSchema: z.ZodType< ]); export function openResponsesEasyInputMessageRoleUnionToJSON( - openResponsesEasyInputMessageRoleUnion: - OpenResponsesEasyInputMessageRoleUnion, + openResponsesEasyInputMessageRoleUnion: OpenResponsesEasyInputMessageRoleUnion, ): string { return JSON.stringify( OpenResponsesEasyInputMessageRoleUnion$outboundSchema.parse( @@ -186,11 +158,11 @@ export function openResponsesEasyInputMessageContent1ToJSON( /** @internal */ export type OpenResponsesEasyInputMessageContent2$Outbound = | Array< - | ResponseInputText$Outbound - | ResponseInputImage$Outbound - | ResponseInputFile$Outbound - | ResponseInputAudio$Outbound - > + | ResponseInputText$Outbound + | ResponseInputImage$Outbound + | ResponseInputFile$Outbound + | ResponseInputAudio$Outbound + > | string; /** @internal */ @@ -225,11 +197,11 @@ export type OpenResponsesEasyInputMessage$Outbound = { role: string | string | string | string; content: | Array< - | ResponseInputText$Outbound - | ResponseInputImage$Outbound - | ResponseInputFile$Outbound - | ResponseInputAudio$Outbound - > + | ResponseInputText$Outbound + | ResponseInputImage$Outbound + | ResponseInputFile$Outbound + | ResponseInputAudio$Outbound + > | string; }; @@ -262,8 +234,6 @@ export function openResponsesEasyInputMessageToJSON( openResponsesEasyInputMessage: OpenResponsesEasyInputMessage, ): string { return JSON.stringify( - OpenResponsesEasyInputMessage$outboundSchema.parse( - openResponsesEasyInputMessage, - ), + OpenResponsesEasyInputMessage$outboundSchema.parse(openResponsesEasyInputMessage), ); } diff --git a/src/models/openresponseserrorevent.ts b/src/models/openresponseserrorevent.ts index 6585539c..c8a63756 100644 --- a/src/models/openresponseserrorevent.ts +++ b/src/models/openresponseserrorevent.ts @@ -3,17 +3,18 @@ * @generated-id: 508880501ed2 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * Event emitted when an error occurs during streaming */ export type OpenResponsesErrorEvent = { - type: "error"; + type: 'error'; code: string | null; message: string; param: string | null; @@ -21,20 +22,19 @@ export type OpenResponsesErrorEvent = { }; /** @internal */ -export const OpenResponsesErrorEvent$inboundSchema: z.ZodType< - OpenResponsesErrorEvent, - unknown -> = z.object({ - type: z.literal("error"), - code: z.nullable(z.string()), - message: z.string(), - param: z.nullable(z.string()), - sequence_number: z.number(), -}).transform((v) => { - return remap$(v, { - "sequence_number": "sequenceNumber", +export const OpenResponsesErrorEvent$inboundSchema: z.ZodType = z + .object({ + type: z.literal('error'), + code: z.nullable(z.string()), + message: z.string(), + param: z.nullable(z.string()), + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + sequence_number: 'sequenceNumber', + }); }); -}); export function openResponsesErrorEventFromJSON( jsonString: string, diff --git a/src/models/openresponsesfunctioncalloutput.ts b/src/models/openresponsesfunctioncalloutput.ts index 0fe2b77d..16628a5a 100644 --- a/src/models/openresponsesfunctioncalloutput.ts +++ b/src/models/openresponsesfunctioncalloutput.ts @@ -3,16 +3,15 @@ * @generated-id: 5e801f7b2903 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { ClosedEnum } from "../types/enums.js"; -import { - ToolCallStatus, - ToolCallStatus$outboundSchema, -} from "./toolcallstatus.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { ToolCallStatus } from './toolcallstatus.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { ToolCallStatus$outboundSchema } from './toolcallstatus.js'; export const OpenResponsesFunctionCallOutputType = { - FunctionCallOutput: "function_call_output", + FunctionCallOutput: 'function_call_output', } as const; export type OpenResponsesFunctionCallOutputType = ClosedEnum< typeof OpenResponsesFunctionCallOutputType @@ -47,24 +46,24 @@ export type OpenResponsesFunctionCallOutput$Outbound = { export const OpenResponsesFunctionCallOutput$outboundSchema: z.ZodType< OpenResponsesFunctionCallOutput$Outbound, OpenResponsesFunctionCallOutput -> = z.object({ - type: OpenResponsesFunctionCallOutputType$outboundSchema, - id: z.nullable(z.string()).optional(), - callId: z.string(), - output: z.string(), - status: z.nullable(ToolCallStatus$outboundSchema).optional(), -}).transform((v) => { - return remap$(v, { - callId: "call_id", +> = z + .object({ + type: OpenResponsesFunctionCallOutputType$outboundSchema, + id: z.nullable(z.string()).optional(), + callId: z.string(), + output: z.string(), + status: z.nullable(ToolCallStatus$outboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + callId: 'call_id', + }); }); -}); export function openResponsesFunctionCallOutputToJSON( openResponsesFunctionCallOutput: OpenResponsesFunctionCallOutput, ): string { return JSON.stringify( - OpenResponsesFunctionCallOutput$outboundSchema.parse( - openResponsesFunctionCallOutput, - ), + OpenResponsesFunctionCallOutput$outboundSchema.parse(openResponsesFunctionCallOutput), ); } diff --git a/src/models/openresponsesfunctiontoolcall.ts b/src/models/openresponsesfunctiontoolcall.ts index b3b12fca..b01259c2 100644 --- a/src/models/openresponsesfunctiontoolcall.ts +++ b/src/models/openresponsesfunctiontoolcall.ts @@ -3,16 +3,15 @@ * @generated-id: b028e3118a4e */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { ClosedEnum } from "../types/enums.js"; -import { - ToolCallStatus, - ToolCallStatus$outboundSchema, -} from "./toolcallstatus.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { ToolCallStatus } from './toolcallstatus.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { ToolCallStatus$outboundSchema } from './toolcallstatus.js'; export const OpenResponsesFunctionToolCallType = { - FunctionCall: "function_call", + FunctionCall: 'function_call', } as const; export type OpenResponsesFunctionToolCallType = ClosedEnum< typeof OpenResponsesFunctionToolCallType @@ -49,25 +48,25 @@ export type OpenResponsesFunctionToolCall$Outbound = { export const OpenResponsesFunctionToolCall$outboundSchema: z.ZodType< OpenResponsesFunctionToolCall$Outbound, OpenResponsesFunctionToolCall -> = z.object({ - type: OpenResponsesFunctionToolCallType$outboundSchema, - callId: z.string(), - name: z.string(), - arguments: z.string(), - id: z.string(), - status: z.nullable(ToolCallStatus$outboundSchema).optional(), -}).transform((v) => { - return remap$(v, { - callId: "call_id", +> = z + .object({ + type: OpenResponsesFunctionToolCallType$outboundSchema, + callId: z.string(), + name: z.string(), + arguments: z.string(), + id: z.string(), + status: z.nullable(ToolCallStatus$outboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + callId: 'call_id', + }); }); -}); export function openResponsesFunctionToolCallToJSON( openResponsesFunctionToolCall: OpenResponsesFunctionToolCall, ): string { return JSON.stringify( - OpenResponsesFunctionToolCall$outboundSchema.parse( - openResponsesFunctionToolCall, - ), + OpenResponsesFunctionToolCall$outboundSchema.parse(openResponsesFunctionToolCall), ); } diff --git a/src/models/openresponsesimagegencallcompleted.ts b/src/models/openresponsesimagegencallcompleted.ts index 7b5eff27..bb00c21e 100644 --- a/src/models/openresponsesimagegencallcompleted.ts +++ b/src/models/openresponsesimagegencallcompleted.ts @@ -3,17 +3,18 @@ * @generated-id: 8f2a1c3fbf5d */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * Image generation call completed */ export type OpenResponsesImageGenCallCompleted = { - type: "response.image_generation_call.completed"; + type: 'response.image_generation_call.completed'; itemId: string; outputIndex: number; sequenceNumber: number; @@ -23,26 +24,27 @@ export type OpenResponsesImageGenCallCompleted = { export const OpenResponsesImageGenCallCompleted$inboundSchema: z.ZodType< OpenResponsesImageGenCallCompleted, unknown -> = z.object({ - type: z.literal("response.image_generation_call.completed"), - item_id: z.string(), - output_index: z.number(), - sequence_number: z.number(), -}).transform((v) => { - return remap$(v, { - "item_id": "itemId", - "output_index": "outputIndex", - "sequence_number": "sequenceNumber", +> = z + .object({ + type: z.literal('response.image_generation_call.completed'), + item_id: z.string(), + output_index: z.number(), + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + item_id: 'itemId', + output_index: 'outputIndex', + sequence_number: 'sequenceNumber', + }); }); -}); export function openResponsesImageGenCallCompletedFromJSON( jsonString: string, ): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesImageGenCallCompleted$inboundSchema.parse(JSON.parse(x)), + (x) => OpenResponsesImageGenCallCompleted$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesImageGenCallCompleted' from JSON`, ); } diff --git a/src/models/openresponsesimagegencallgenerating.ts b/src/models/openresponsesimagegencallgenerating.ts index b06bf7fd..4ad8d7db 100644 --- a/src/models/openresponsesimagegencallgenerating.ts +++ b/src/models/openresponsesimagegencallgenerating.ts @@ -3,17 +3,18 @@ * @generated-id: 97b22c3fad75 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * Image generation call is generating */ export type OpenResponsesImageGenCallGenerating = { - type: "response.image_generation_call.generating"; + type: 'response.image_generation_call.generating'; itemId: string; outputIndex: number; sequenceNumber: number; @@ -23,26 +24,27 @@ export type OpenResponsesImageGenCallGenerating = { export const OpenResponsesImageGenCallGenerating$inboundSchema: z.ZodType< OpenResponsesImageGenCallGenerating, unknown -> = z.object({ - type: z.literal("response.image_generation_call.generating"), - item_id: z.string(), - output_index: z.number(), - sequence_number: z.number(), -}).transform((v) => { - return remap$(v, { - "item_id": "itemId", - "output_index": "outputIndex", - "sequence_number": "sequenceNumber", +> = z + .object({ + type: z.literal('response.image_generation_call.generating'), + item_id: z.string(), + output_index: z.number(), + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + item_id: 'itemId', + output_index: 'outputIndex', + sequence_number: 'sequenceNumber', + }); }); -}); export function openResponsesImageGenCallGeneratingFromJSON( jsonString: string, ): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesImageGenCallGenerating$inboundSchema.parse(JSON.parse(x)), + (x) => OpenResponsesImageGenCallGenerating$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesImageGenCallGenerating' from JSON`, ); } diff --git a/src/models/openresponsesimagegencallinprogress.ts b/src/models/openresponsesimagegencallinprogress.ts index c04765b1..044083ca 100644 --- a/src/models/openresponsesimagegencallinprogress.ts +++ b/src/models/openresponsesimagegencallinprogress.ts @@ -3,17 +3,18 @@ * @generated-id: 402a8da9c8da */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * Image generation call in progress */ export type OpenResponsesImageGenCallInProgress = { - type: "response.image_generation_call.in_progress"; + type: 'response.image_generation_call.in_progress'; itemId: string; outputIndex: number; sequenceNumber: number; @@ -23,26 +24,27 @@ export type OpenResponsesImageGenCallInProgress = { export const OpenResponsesImageGenCallInProgress$inboundSchema: z.ZodType< OpenResponsesImageGenCallInProgress, unknown -> = z.object({ - type: z.literal("response.image_generation_call.in_progress"), - item_id: z.string(), - output_index: z.number(), - sequence_number: z.number(), -}).transform((v) => { - return remap$(v, { - "item_id": "itemId", - "output_index": "outputIndex", - "sequence_number": "sequenceNumber", +> = z + .object({ + type: z.literal('response.image_generation_call.in_progress'), + item_id: z.string(), + output_index: z.number(), + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + item_id: 'itemId', + output_index: 'outputIndex', + sequence_number: 'sequenceNumber', + }); }); -}); export function openResponsesImageGenCallInProgressFromJSON( jsonString: string, ): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesImageGenCallInProgress$inboundSchema.parse(JSON.parse(x)), + (x) => OpenResponsesImageGenCallInProgress$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesImageGenCallInProgress' from JSON`, ); } diff --git a/src/models/openresponsesimagegencallpartialimage.ts b/src/models/openresponsesimagegencallpartialimage.ts index aedca402..bd80d5a2 100644 --- a/src/models/openresponsesimagegencallpartialimage.ts +++ b/src/models/openresponsesimagegencallpartialimage.ts @@ -3,17 +3,18 @@ * @generated-id: 053a18912617 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * Image generation call with partial image */ export type OpenResponsesImageGenCallPartialImage = { - type: "response.image_generation_call.partial_image"; + type: 'response.image_generation_call.partial_image'; itemId: string; outputIndex: number; sequenceNumber: number; @@ -25,30 +26,31 @@ export type OpenResponsesImageGenCallPartialImage = { export const OpenResponsesImageGenCallPartialImage$inboundSchema: z.ZodType< OpenResponsesImageGenCallPartialImage, unknown -> = z.object({ - type: z.literal("response.image_generation_call.partial_image"), - item_id: z.string(), - output_index: z.number(), - sequence_number: z.number(), - partial_image_b64: z.string(), - partial_image_index: z.number(), -}).transform((v) => { - return remap$(v, { - "item_id": "itemId", - "output_index": "outputIndex", - "sequence_number": "sequenceNumber", - "partial_image_b64": "partialImageB64", - "partial_image_index": "partialImageIndex", +> = z + .object({ + type: z.literal('response.image_generation_call.partial_image'), + item_id: z.string(), + output_index: z.number(), + sequence_number: z.number(), + partial_image_b64: z.string(), + partial_image_index: z.number(), + }) + .transform((v) => { + return remap$(v, { + item_id: 'itemId', + output_index: 'outputIndex', + sequence_number: 'sequenceNumber', + partial_image_b64: 'partialImageB64', + partial_image_index: 'partialImageIndex', + }); }); -}); export function openResponsesImageGenCallPartialImageFromJSON( jsonString: string, ): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesImageGenCallPartialImage$inboundSchema.parse(JSON.parse(x)), + (x) => OpenResponsesImageGenCallPartialImage$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesImageGenCallPartialImage' from JSON`, ); } diff --git a/src/models/openresponsesinput.ts b/src/models/openresponsesinput.ts index 7f007b7a..bc512a69 100644 --- a/src/models/openresponsesinput.ts +++ b/src/models/openresponsesinput.ts @@ -3,62 +3,63 @@ * @generated-id: cc6c94fdea13 */ -import * as z from "zod/v4"; -import { +import type { OpenResponsesEasyInputMessage, OpenResponsesEasyInputMessage$Outbound, - OpenResponsesEasyInputMessage$outboundSchema, -} from "./openresponseseasyinputmessage.js"; -import { +} from './openresponseseasyinputmessage.js'; +import type { OpenResponsesFunctionCallOutput, OpenResponsesFunctionCallOutput$Outbound, - OpenResponsesFunctionCallOutput$outboundSchema, -} from "./openresponsesfunctioncalloutput.js"; -import { +} from './openresponsesfunctioncalloutput.js'; +import type { OpenResponsesFunctionToolCall, OpenResponsesFunctionToolCall$Outbound, - OpenResponsesFunctionToolCall$outboundSchema, -} from "./openresponsesfunctiontoolcall.js"; -import { +} from './openresponsesfunctiontoolcall.js'; +import type { OpenResponsesInputMessageItem, OpenResponsesInputMessageItem$Outbound, - OpenResponsesInputMessageItem$outboundSchema, -} from "./openresponsesinputmessageitem.js"; -import { +} from './openresponsesinputmessageitem.js'; +import type { OpenResponsesReasoning, OpenResponsesReasoning$Outbound, - OpenResponsesReasoning$outboundSchema, -} from "./openresponsesreasoning.js"; -import { +} from './openresponsesreasoning.js'; +import type { ResponsesImageGenerationCall, ResponsesImageGenerationCall$Outbound, - ResponsesImageGenerationCall$outboundSchema, -} from "./responsesimagegenerationcall.js"; -import { +} from './responsesimagegenerationcall.js'; +import type { ResponsesOutputItemFileSearchCall, ResponsesOutputItemFileSearchCall$Outbound, - ResponsesOutputItemFileSearchCall$outboundSchema, -} from "./responsesoutputitemfilesearchcall.js"; -import { +} from './responsesoutputitemfilesearchcall.js'; +import type { ResponsesOutputItemFunctionCall, ResponsesOutputItemFunctionCall$Outbound, - ResponsesOutputItemFunctionCall$outboundSchema, -} from "./responsesoutputitemfunctioncall.js"; -import { +} from './responsesoutputitemfunctioncall.js'; +import type { ResponsesOutputItemReasoning, ResponsesOutputItemReasoning$Outbound, - ResponsesOutputItemReasoning$outboundSchema, -} from "./responsesoutputitemreasoning.js"; -import { +} from './responsesoutputitemreasoning.js'; +import type { ResponsesOutputMessage, ResponsesOutputMessage$Outbound, - ResponsesOutputMessage$outboundSchema, -} from "./responsesoutputmessage.js"; -import { +} from './responsesoutputmessage.js'; +import type { ResponsesWebSearchCallOutput, ResponsesWebSearchCallOutput$Outbound, - ResponsesWebSearchCallOutput$outboundSchema, -} from "./responseswebsearchcalloutput.js"; +} from './responseswebsearchcalloutput.js'; + +import * as z from 'zod/v4'; +import { OpenResponsesEasyInputMessage$outboundSchema } from './openresponseseasyinputmessage.js'; +import { OpenResponsesFunctionCallOutput$outboundSchema } from './openresponsesfunctioncalloutput.js'; +import { OpenResponsesFunctionToolCall$outboundSchema } from './openresponsesfunctiontoolcall.js'; +import { OpenResponsesInputMessageItem$outboundSchema } from './openresponsesinputmessageitem.js'; +import { OpenResponsesReasoning$outboundSchema } from './openresponsesreasoning.js'; +import { ResponsesImageGenerationCall$outboundSchema } from './responsesimagegenerationcall.js'; +import { ResponsesOutputItemFileSearchCall$outboundSchema } from './responsesoutputitemfilesearchcall.js'; +import { ResponsesOutputItemFunctionCall$outboundSchema } from './responsesoutputitemfunctioncall.js'; +import { ResponsesOutputItemReasoning$outboundSchema } from './responsesoutputitemreasoning.js'; +import { ResponsesOutputMessage$outboundSchema } from './responsesoutputmessage.js'; +import { ResponsesWebSearchCallOutput$outboundSchema } from './responseswebsearchcalloutput.js'; export type OpenResponsesInput1 = | OpenResponsesFunctionToolCall @@ -79,18 +80,18 @@ export type OpenResponsesInput1 = export type OpenResponsesInput = | string | Array< - | OpenResponsesFunctionToolCall - | ResponsesOutputMessage - | ResponsesOutputItemFunctionCall - | ResponsesOutputItemFileSearchCall - | OpenResponsesReasoning - | OpenResponsesFunctionCallOutput - | ResponsesOutputItemReasoning - | ResponsesWebSearchCallOutput - | ResponsesImageGenerationCall - | OpenResponsesEasyInputMessage - | OpenResponsesInputMessageItem - >; + | OpenResponsesFunctionToolCall + | ResponsesOutputMessage + | ResponsesOutputItemFunctionCall + | ResponsesOutputItemFileSearchCall + | OpenResponsesReasoning + | OpenResponsesFunctionCallOutput + | ResponsesOutputItemReasoning + | ResponsesWebSearchCallOutput + | ResponsesImageGenerationCall + | OpenResponsesEasyInputMessage + | OpenResponsesInputMessageItem + >; /** @internal */ export type OpenResponsesInput1$Outbound = @@ -124,30 +125,26 @@ export const OpenResponsesInput1$outboundSchema: z.ZodType< OpenResponsesInputMessageItem$outboundSchema, ]); -export function openResponsesInput1ToJSON( - openResponsesInput1: OpenResponsesInput1, -): string { - return JSON.stringify( - OpenResponsesInput1$outboundSchema.parse(openResponsesInput1), - ); +export function openResponsesInput1ToJSON(openResponsesInput1: OpenResponsesInput1): string { + return JSON.stringify(OpenResponsesInput1$outboundSchema.parse(openResponsesInput1)); } /** @internal */ export type OpenResponsesInput$Outbound = | string | Array< - | OpenResponsesFunctionToolCall$Outbound - | ResponsesOutputMessage$Outbound - | ResponsesOutputItemFunctionCall$Outbound - | ResponsesOutputItemFileSearchCall$Outbound - | OpenResponsesReasoning$Outbound - | OpenResponsesFunctionCallOutput$Outbound - | ResponsesOutputItemReasoning$Outbound - | ResponsesWebSearchCallOutput$Outbound - | ResponsesImageGenerationCall$Outbound - | OpenResponsesEasyInputMessage$Outbound - | OpenResponsesInputMessageItem$Outbound - >; + | OpenResponsesFunctionToolCall$Outbound + | ResponsesOutputMessage$Outbound + | ResponsesOutputItemFunctionCall$Outbound + | ResponsesOutputItemFileSearchCall$Outbound + | OpenResponsesReasoning$Outbound + | OpenResponsesFunctionCallOutput$Outbound + | ResponsesOutputItemReasoning$Outbound + | ResponsesWebSearchCallOutput$Outbound + | ResponsesImageGenerationCall$Outbound + | OpenResponsesEasyInputMessage$Outbound + | OpenResponsesInputMessageItem$Outbound + >; /** @internal */ export const OpenResponsesInput$outboundSchema: z.ZodType< @@ -172,10 +169,6 @@ export const OpenResponsesInput$outboundSchema: z.ZodType< ), ]); -export function openResponsesInputToJSON( - openResponsesInput: OpenResponsesInput, -): string { - return JSON.stringify( - OpenResponsesInput$outboundSchema.parse(openResponsesInput), - ); +export function openResponsesInputToJSON(openResponsesInput: OpenResponsesInput): string { + return JSON.stringify(OpenResponsesInput$outboundSchema.parse(openResponsesInput)); } diff --git a/src/models/openresponsesinputmessageitem.ts b/src/models/openresponsesinputmessageitem.ts index d95f5d29..ede35652 100644 --- a/src/models/openresponsesinputmessageitem.ts +++ b/src/models/openresponsesinputmessageitem.ts @@ -3,52 +3,41 @@ * @generated-id: cccc4eb21a9b */ -import * as z from "zod/v4"; -import { ClosedEnum } from "../types/enums.js"; -import { - ResponseInputAudio, - ResponseInputAudio$Outbound, - ResponseInputAudio$outboundSchema, -} from "./responseinputaudio.js"; -import { - ResponseInputFile, - ResponseInputFile$Outbound, - ResponseInputFile$outboundSchema, -} from "./responseinputfile.js"; -import { - ResponseInputImage, - ResponseInputImage$Outbound, - ResponseInputImage$outboundSchema, -} from "./responseinputimage.js"; -import { - ResponseInputText, - ResponseInputText$Outbound, - ResponseInputText$outboundSchema, -} from "./responseinputtext.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { ResponseInputAudio, ResponseInputAudio$Outbound } from './responseinputaudio.js'; +import type { ResponseInputFile, ResponseInputFile$Outbound } from './responseinputfile.js'; +import type { ResponseInputImage, ResponseInputImage$Outbound } from './responseinputimage.js'; +import type { ResponseInputText, ResponseInputText$Outbound } from './responseinputtext.js'; + +import * as z from 'zod/v4'; +import { ResponseInputAudio$outboundSchema } from './responseinputaudio.js'; +import { ResponseInputFile$outboundSchema } from './responseinputfile.js'; +import { ResponseInputImage$outboundSchema } from './responseinputimage.js'; +import { ResponseInputText$outboundSchema } from './responseinputtext.js'; export const OpenResponsesInputMessageItemType = { - Message: "message", + Message: 'message', } as const; export type OpenResponsesInputMessageItemType = ClosedEnum< typeof OpenResponsesInputMessageItemType >; export const OpenResponsesInputMessageItemRoleDeveloper = { - Developer: "developer", + Developer: 'developer', } as const; export type OpenResponsesInputMessageItemRoleDeveloper = ClosedEnum< typeof OpenResponsesInputMessageItemRoleDeveloper >; export const OpenResponsesInputMessageItemRoleSystem = { - System: "system", + System: 'system', } as const; export type OpenResponsesInputMessageItemRoleSystem = ClosedEnum< typeof OpenResponsesInputMessageItemRoleSystem >; export const OpenResponsesInputMessageItemRoleUser = { - User: "user", + User: 'user', } as const; export type OpenResponsesInputMessageItemRoleUser = ClosedEnum< typeof OpenResponsesInputMessageItemRoleUser @@ -72,12 +61,7 @@ export type OpenResponsesInputMessageItem = { | OpenResponsesInputMessageItemRoleUser | OpenResponsesInputMessageItemRoleSystem | OpenResponsesInputMessageItemRoleDeveloper; - content: Array< - | ResponseInputText - | ResponseInputImage - | ResponseInputFile - | ResponseInputAudio - >; + content: Array; }; /** @internal */ @@ -86,10 +70,9 @@ export const OpenResponsesInputMessageItemType$outboundSchema: z.ZodEnum< > = z.enum(OpenResponsesInputMessageItemType); /** @internal */ -export const OpenResponsesInputMessageItemRoleDeveloper$outboundSchema: - z.ZodEnum = z.enum( - OpenResponsesInputMessageItemRoleDeveloper, - ); +export const OpenResponsesInputMessageItemRoleDeveloper$outboundSchema: z.ZodEnum< + typeof OpenResponsesInputMessageItemRoleDeveloper +> = z.enum(OpenResponsesInputMessageItemRoleDeveloper); /** @internal */ export const OpenResponsesInputMessageItemRoleSystem$outboundSchema: z.ZodEnum< @@ -102,10 +85,7 @@ export const OpenResponsesInputMessageItemRoleUser$outboundSchema: z.ZodEnum< > = z.enum(OpenResponsesInputMessageItemRoleUser); /** @internal */ -export type OpenResponsesInputMessageItemRoleUnion$Outbound = - | string - | string - | string; +export type OpenResponsesInputMessageItemRoleUnion$Outbound = string | string | string; /** @internal */ export const OpenResponsesInputMessageItemRoleUnion$outboundSchema: z.ZodType< @@ -118,8 +98,7 @@ export const OpenResponsesInputMessageItemRoleUnion$outboundSchema: z.ZodType< ]); export function openResponsesInputMessageItemRoleUnionToJSON( - openResponsesInputMessageItemRoleUnion: - OpenResponsesInputMessageItemRoleUnion, + openResponsesInputMessageItemRoleUnion: OpenResponsesInputMessageItemRoleUnion, ): string { return JSON.stringify( OpenResponsesInputMessageItemRoleUnion$outboundSchema.parse( @@ -150,9 +129,7 @@ export function openResponsesInputMessageItemContentToJSON( openResponsesInputMessageItemContent: OpenResponsesInputMessageItemContent, ): string { return JSON.stringify( - OpenResponsesInputMessageItemContent$outboundSchema.parse( - openResponsesInputMessageItemContent, - ), + OpenResponsesInputMessageItemContent$outboundSchema.parse(openResponsesInputMessageItemContent), ); } @@ -195,8 +172,6 @@ export function openResponsesInputMessageItemToJSON( openResponsesInputMessageItem: OpenResponsesInputMessageItem, ): string { return JSON.stringify( - OpenResponsesInputMessageItem$outboundSchema.parse( - openResponsesInputMessageItem, - ), + OpenResponsesInputMessageItem$outboundSchema.parse(openResponsesInputMessageItem), ); } diff --git a/src/models/openresponseslogprobs.ts b/src/models/openresponseslogprobs.ts index ea0b9a92..d1dc2533 100644 --- a/src/models/openresponseslogprobs.ts +++ b/src/models/openresponseslogprobs.ts @@ -3,15 +3,14 @@ * @generated-id: 7ec69a3158fc */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { - OpenResponsesTopLogprobs, - OpenResponsesTopLogprobs$inboundSchema, -} from "./openresponsestoplogprobs.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { OpenResponsesTopLogprobs } from './openresponsestoplogprobs.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { OpenResponsesTopLogprobs$inboundSchema } from './openresponsestoplogprobs.js'; /** * Log probability information for a token @@ -23,18 +22,17 @@ export type OpenResponsesLogProbs = { }; /** @internal */ -export const OpenResponsesLogProbs$inboundSchema: z.ZodType< - OpenResponsesLogProbs, - unknown -> = z.object({ - logprob: z.number(), - token: z.string(), - top_logprobs: z.array(OpenResponsesTopLogprobs$inboundSchema).optional(), -}).transform((v) => { - return remap$(v, { - "top_logprobs": "topLogprobs", +export const OpenResponsesLogProbs$inboundSchema: z.ZodType = z + .object({ + logprob: z.number(), + token: z.string(), + top_logprobs: z.array(OpenResponsesTopLogprobs$inboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + top_logprobs: 'topLogprobs', + }); }); -}); export function openResponsesLogProbsFromJSON( jsonString: string, diff --git a/src/models/openresponsesnonstreamingresponse.ts b/src/models/openresponsesnonstreamingresponse.ts index 55771267..56faf191 100644 --- a/src/models/openresponsesnonstreamingresponse.ts +++ b/src/models/openresponsesnonstreamingresponse.ts @@ -3,79 +3,48 @@ * @generated-id: ffd6f7198dd7 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { - OpenAIResponsesIncompleteDetails, - OpenAIResponsesIncompleteDetails$inboundSchema, -} from "./openairesponsesincompletedetails.js"; -import { - OpenAIResponsesInputUnion, - OpenAIResponsesInputUnion$inboundSchema, -} from "./openairesponsesinputunion.js"; -import { - OpenAIResponsesPrompt, - OpenAIResponsesPrompt$inboundSchema, -} from "./openairesponsesprompt.js"; -import { - OpenAIResponsesReasoningConfig, - OpenAIResponsesReasoningConfig$inboundSchema, -} from "./openairesponsesreasoningconfig.js"; -import { - OpenAIResponsesResponseStatus, - OpenAIResponsesResponseStatus$inboundSchema, -} from "./openairesponsesresponsestatus.js"; -import { - OpenAIResponsesServiceTier, - OpenAIResponsesServiceTier$inboundSchema, -} from "./openairesponsesservicetier.js"; -import { - OpenAIResponsesToolChoiceUnion, - OpenAIResponsesToolChoiceUnion$inboundSchema, -} from "./openairesponsestoolchoiceunion.js"; -import { - OpenAIResponsesTruncation, - OpenAIResponsesTruncation$inboundSchema, -} from "./openairesponsestruncation.js"; -import { - OpenResponsesUsage, - OpenResponsesUsage$inboundSchema, -} from "./openresponsesusage.js"; -import { - OpenResponsesWebSearch20250826Tool, - OpenResponsesWebSearch20250826Tool$inboundSchema, -} from "./openresponseswebsearch20250826tool.js"; -import { - OpenResponsesWebSearchPreview20250311Tool, - OpenResponsesWebSearchPreview20250311Tool$inboundSchema, -} from "./openresponseswebsearchpreview20250311tool.js"; -import { - OpenResponsesWebSearchPreviewTool, - OpenResponsesWebSearchPreviewTool$inboundSchema, -} from "./openresponseswebsearchpreviewtool.js"; -import { - OpenResponsesWebSearchTool, - OpenResponsesWebSearchTool$inboundSchema, -} from "./openresponseswebsearchtool.js"; -import { - ResponsesErrorField, - ResponsesErrorField$inboundSchema, -} from "./responseserrorfield.js"; -import { - ResponsesOutputItem, - ResponsesOutputItem$inboundSchema, -} from "./responsesoutputitem.js"; -import { - ResponseTextConfig, - ResponseTextConfig$inboundSchema, -} from "./responsetextconfig.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { OpenAIResponsesIncompleteDetails } from './openairesponsesincompletedetails.js'; +import type { OpenAIResponsesInputUnion } from './openairesponsesinputunion.js'; +import type { OpenAIResponsesPrompt } from './openairesponsesprompt.js'; +import type { OpenAIResponsesReasoningConfig } from './openairesponsesreasoningconfig.js'; +import type { OpenAIResponsesResponseStatus } from './openairesponsesresponsestatus.js'; +import type { OpenAIResponsesServiceTier } from './openairesponsesservicetier.js'; +import type { OpenAIResponsesToolChoiceUnion } from './openairesponsestoolchoiceunion.js'; +import type { OpenAIResponsesTruncation } from './openairesponsestruncation.js'; +import type { OpenResponsesUsage } from './openresponsesusage.js'; +import type { OpenResponsesWebSearch20250826Tool } from './openresponseswebsearch20250826tool.js'; +import type { OpenResponsesWebSearchPreview20250311Tool } from './openresponseswebsearchpreview20250311tool.js'; +import type { OpenResponsesWebSearchPreviewTool } from './openresponseswebsearchpreviewtool.js'; +import type { OpenResponsesWebSearchTool } from './openresponseswebsearchtool.js'; +import type { ResponsesErrorField } from './responseserrorfield.js'; +import type { ResponsesOutputItem } from './responsesoutputitem.js'; +import type { ResponseTextConfig } from './responsetextconfig.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { OpenAIResponsesIncompleteDetails$inboundSchema } from './openairesponsesincompletedetails.js'; +import { OpenAIResponsesInputUnion$inboundSchema } from './openairesponsesinputunion.js'; +import { OpenAIResponsesPrompt$inboundSchema } from './openairesponsesprompt.js'; +import { OpenAIResponsesReasoningConfig$inboundSchema } from './openairesponsesreasoningconfig.js'; +import { OpenAIResponsesResponseStatus$inboundSchema } from './openairesponsesresponsestatus.js'; +import { OpenAIResponsesServiceTier$inboundSchema } from './openairesponsesservicetier.js'; +import { OpenAIResponsesToolChoiceUnion$inboundSchema } from './openairesponsestoolchoiceunion.js'; +import { OpenAIResponsesTruncation$inboundSchema } from './openairesponsestruncation.js'; +import { OpenResponsesUsage$inboundSchema } from './openresponsesusage.js'; +import { OpenResponsesWebSearch20250826Tool$inboundSchema } from './openresponseswebsearch20250826tool.js'; +import { OpenResponsesWebSearchPreview20250311Tool$inboundSchema } from './openresponseswebsearchpreview20250311tool.js'; +import { OpenResponsesWebSearchPreviewTool$inboundSchema } from './openresponseswebsearchpreviewtool.js'; +import { OpenResponsesWebSearchTool$inboundSchema } from './openresponseswebsearchtool.js'; +import { ResponsesErrorField$inboundSchema } from './responseserrorfield.js'; +import { ResponsesOutputItem$inboundSchema } from './responsesoutputitem.js'; +import { ResponseTextConfig$inboundSchema } from './responsetextconfig.js'; export const ObjectT = { - Response: "response", + Response: 'response', } as const; export type ObjectT = ClosedEnum; @@ -83,11 +52,13 @@ export type ObjectT = ClosedEnum; * Function tool definition */ export type OpenResponsesNonStreamingResponseToolFunction = { - type: "function"; + type: 'function'; name: string; description?: string | null | undefined; strict?: boolean | null | undefined; - parameters: { [k: string]: any | null } | null; + parameters: { + [k: string]: any | null; + } | null; }; export type OpenResponsesNonStreamingResponseToolUnion = @@ -129,7 +100,9 @@ export type OpenResponsesNonStreamingResponse = { /** * Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. */ - metadata: { [k: string]: string } | null; + metadata: { + [k: string]: string; + } | null; tools: Array< | OpenResponsesNonStreamingResponseToolFunction | OpenResponsesWebSearchPreviewTool @@ -156,53 +129,45 @@ export type OpenResponsesNonStreamingResponse = { export const ObjectT$inboundSchema: z.ZodEnum = z.enum(ObjectT); /** @internal */ -export const OpenResponsesNonStreamingResponseToolFunction$inboundSchema: - z.ZodType = z.object({ - type: z.literal("function"), - name: z.string(), - description: z.nullable(z.string()).optional(), - strict: z.nullable(z.boolean()).optional(), - parameters: z.nullable(z.record(z.string(), z.nullable(z.any()))), - }); +export const OpenResponsesNonStreamingResponseToolFunction$inboundSchema: z.ZodType< + OpenResponsesNonStreamingResponseToolFunction, + unknown +> = z.object({ + type: z.literal('function'), + name: z.string(), + description: z.nullable(z.string()).optional(), + strict: z.nullable(z.boolean()).optional(), + parameters: z.nullable(z.record(z.string(), z.nullable(z.any()))), +}); export function openResponsesNonStreamingResponseToolFunctionFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesNonStreamingResponseToolFunction, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesNonStreamingResponseToolFunction$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesNonStreamingResponseToolFunction$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesNonStreamingResponseToolFunction' from JSON`, ); } /** @internal */ -export const OpenResponsesNonStreamingResponseToolUnion$inboundSchema: - z.ZodType = z.union([ - z.lazy(() => OpenResponsesNonStreamingResponseToolFunction$inboundSchema), - OpenResponsesWebSearchPreviewTool$inboundSchema, - OpenResponsesWebSearchPreview20250311Tool$inboundSchema, - OpenResponsesWebSearchTool$inboundSchema, - OpenResponsesWebSearch20250826Tool$inboundSchema, - ]); +export const OpenResponsesNonStreamingResponseToolUnion$inboundSchema: z.ZodType< + OpenResponsesNonStreamingResponseToolUnion, + unknown +> = z.union([ + z.lazy(() => OpenResponsesNonStreamingResponseToolFunction$inboundSchema), + OpenResponsesWebSearchPreviewTool$inboundSchema, + OpenResponsesWebSearchPreview20250311Tool$inboundSchema, + OpenResponsesWebSearchTool$inboundSchema, + OpenResponsesWebSearch20250826Tool$inboundSchema, +]); export function openResponsesNonStreamingResponseToolUnionFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesNonStreamingResponseToolUnion, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesNonStreamingResponseToolUnion$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesNonStreamingResponseToolUnion$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesNonStreamingResponseToolUnion' from JSON`, ); } @@ -211,66 +176,65 @@ export function openResponsesNonStreamingResponseToolUnionFromJSON( export const OpenResponsesNonStreamingResponse$inboundSchema: z.ZodType< OpenResponsesNonStreamingResponse, unknown -> = z.object({ - id: z.string(), - object: ObjectT$inboundSchema, - created_at: z.number(), - model: z.string(), - status: OpenAIResponsesResponseStatus$inboundSchema.optional(), - output: z.array(ResponsesOutputItem$inboundSchema), - user: z.nullable(z.string()).optional(), - output_text: z.string().optional(), - prompt_cache_key: z.nullable(z.string()).optional(), - safety_identifier: z.nullable(z.string()).optional(), - error: z.nullable(ResponsesErrorField$inboundSchema), - incomplete_details: z.nullable( - OpenAIResponsesIncompleteDetails$inboundSchema, - ), - usage: OpenResponsesUsage$inboundSchema.optional(), - max_tool_calls: z.nullable(z.number()).optional(), - top_logprobs: z.number().optional(), - max_output_tokens: z.nullable(z.number()).optional(), - temperature: z.nullable(z.number()), - top_p: z.nullable(z.number()), - instructions: z.nullable(OpenAIResponsesInputUnion$inboundSchema).optional(), - metadata: z.nullable(z.record(z.string(), z.string())), - tools: z.array( - z.union([ - z.lazy(() => OpenResponsesNonStreamingResponseToolFunction$inboundSchema), - OpenResponsesWebSearchPreviewTool$inboundSchema, - OpenResponsesWebSearchPreview20250311Tool$inboundSchema, - OpenResponsesWebSearchTool$inboundSchema, - OpenResponsesWebSearch20250826Tool$inboundSchema, - ]), - ), - tool_choice: OpenAIResponsesToolChoiceUnion$inboundSchema, - parallel_tool_calls: z.boolean(), - prompt: z.nullable(OpenAIResponsesPrompt$inboundSchema).optional(), - background: z.nullable(z.boolean()).optional(), - previous_response_id: z.nullable(z.string()).optional(), - reasoning: z.nullable(OpenAIResponsesReasoningConfig$inboundSchema) - .optional(), - service_tier: z.nullable(OpenAIResponsesServiceTier$inboundSchema).optional(), - store: z.boolean().optional(), - truncation: z.nullable(OpenAIResponsesTruncation$inboundSchema).optional(), - text: ResponseTextConfig$inboundSchema.optional(), -}).transform((v) => { - return remap$(v, { - "created_at": "createdAt", - "output_text": "outputText", - "prompt_cache_key": "promptCacheKey", - "safety_identifier": "safetyIdentifier", - "incomplete_details": "incompleteDetails", - "max_tool_calls": "maxToolCalls", - "top_logprobs": "topLogprobs", - "max_output_tokens": "maxOutputTokens", - "top_p": "topP", - "tool_choice": "toolChoice", - "parallel_tool_calls": "parallelToolCalls", - "previous_response_id": "previousResponseId", - "service_tier": "serviceTier", +> = z + .object({ + id: z.string(), + object: ObjectT$inboundSchema, + created_at: z.number(), + model: z.string(), + status: OpenAIResponsesResponseStatus$inboundSchema.optional(), + output: z.array(ResponsesOutputItem$inboundSchema), + user: z.nullable(z.string()).optional(), + output_text: z.string().optional(), + prompt_cache_key: z.nullable(z.string()).optional(), + safety_identifier: z.nullable(z.string()).optional(), + error: z.nullable(ResponsesErrorField$inboundSchema), + incomplete_details: z.nullable(OpenAIResponsesIncompleteDetails$inboundSchema), + usage: OpenResponsesUsage$inboundSchema.optional(), + max_tool_calls: z.nullable(z.number()).optional(), + top_logprobs: z.number().optional(), + max_output_tokens: z.nullable(z.number()).optional(), + temperature: z.nullable(z.number()), + top_p: z.nullable(z.number()), + instructions: z.nullable(OpenAIResponsesInputUnion$inboundSchema).optional(), + metadata: z.nullable(z.record(z.string(), z.string())), + tools: z.array( + z.union([ + z.lazy(() => OpenResponsesNonStreamingResponseToolFunction$inboundSchema), + OpenResponsesWebSearchPreviewTool$inboundSchema, + OpenResponsesWebSearchPreview20250311Tool$inboundSchema, + OpenResponsesWebSearchTool$inboundSchema, + OpenResponsesWebSearch20250826Tool$inboundSchema, + ]), + ), + tool_choice: OpenAIResponsesToolChoiceUnion$inboundSchema, + parallel_tool_calls: z.boolean(), + prompt: z.nullable(OpenAIResponsesPrompt$inboundSchema).optional(), + background: z.nullable(z.boolean()).optional(), + previous_response_id: z.nullable(z.string()).optional(), + reasoning: z.nullable(OpenAIResponsesReasoningConfig$inboundSchema).optional(), + service_tier: z.nullable(OpenAIResponsesServiceTier$inboundSchema).optional(), + store: z.boolean().optional(), + truncation: z.nullable(OpenAIResponsesTruncation$inboundSchema).optional(), + text: ResponseTextConfig$inboundSchema.optional(), + }) + .transform((v) => { + return remap$(v, { + created_at: 'createdAt', + output_text: 'outputText', + prompt_cache_key: 'promptCacheKey', + safety_identifier: 'safetyIdentifier', + incomplete_details: 'incompleteDetails', + max_tool_calls: 'maxToolCalls', + top_logprobs: 'topLogprobs', + max_output_tokens: 'maxOutputTokens', + top_p: 'topP', + tool_choice: 'toolChoice', + parallel_tool_calls: 'parallelToolCalls', + previous_response_id: 'previousResponseId', + service_tier: 'serviceTier', + }); }); -}); export function openResponsesNonStreamingResponseFromJSON( jsonString: string, diff --git a/src/models/openresponsesreasoning.ts b/src/models/openresponsesreasoning.ts index 2bf9ff6b..b283e501 100644 --- a/src/models/openresponsesreasoning.ts +++ b/src/models/openresponsesreasoning.ts @@ -3,44 +3,43 @@ * @generated-id: 296442f2d24a */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import * as openEnums from "../types/enums.js"; -import { ClosedEnum, OpenEnum } from "../types/enums.js"; -import { +import type { ClosedEnum, OpenEnum } from '../types/enums.js'; +import type { ReasoningSummaryText, ReasoningSummaryText$Outbound, - ReasoningSummaryText$outboundSchema, -} from "./reasoningsummarytext.js"; -import { +} from './reasoningsummarytext.js'; +import type { ReasoningTextContent, ReasoningTextContent$Outbound, - ReasoningTextContent$outboundSchema, -} from "./reasoningtextcontent.js"; +} from './reasoningtextcontent.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import * as openEnums from '../types/enums.js'; +import { ReasoningSummaryText$outboundSchema } from './reasoningsummarytext.js'; +import { ReasoningTextContent$outboundSchema } from './reasoningtextcontent.js'; export const OpenResponsesReasoningType = { - Reasoning: "reasoning", + Reasoning: 'reasoning', } as const; -export type OpenResponsesReasoningType = ClosedEnum< - typeof OpenResponsesReasoningType ->; +export type OpenResponsesReasoningType = ClosedEnum; export const OpenResponsesReasoningStatusInProgress = { - InProgress: "in_progress", + InProgress: 'in_progress', } as const; export type OpenResponsesReasoningStatusInProgress = ClosedEnum< typeof OpenResponsesReasoningStatusInProgress >; export const OpenResponsesReasoningStatusIncomplete = { - Incomplete: "incomplete", + Incomplete: 'incomplete', } as const; export type OpenResponsesReasoningStatusIncomplete = ClosedEnum< typeof OpenResponsesReasoningStatusIncomplete >; export const OpenResponsesReasoningStatusCompleted = { - Completed: "completed", + Completed: 'completed', } as const; export type OpenResponsesReasoningStatusCompleted = ClosedEnum< typeof OpenResponsesReasoningStatusCompleted @@ -52,15 +51,13 @@ export type OpenResponsesReasoningStatusUnion = | OpenResponsesReasoningStatusInProgress; export const OpenResponsesReasoningFormat = { - Unknown: "unknown", - OpenaiResponsesV1: "openai-responses-v1", - XaiResponsesV1: "xai-responses-v1", - AnthropicClaudeV1: "anthropic-claude-v1", - GoogleGeminiV1: "google-gemini-v1", + Unknown: 'unknown', + OpenaiResponsesV1: 'openai-responses-v1', + XaiResponsesV1: 'xai-responses-v1', + AnthropicClaudeV1: 'anthropic-claude-v1', + GoogleGeminiV1: 'google-gemini-v1', } as const; -export type OpenResponsesReasoningFormat = OpenEnum< - typeof OpenResponsesReasoningFormat ->; +export type OpenResponsesReasoningFormat = OpenEnum; /** * Reasoning output item with signature and format extensions @@ -101,10 +98,7 @@ export const OpenResponsesReasoningStatusCompleted$outboundSchema: z.ZodEnum< > = z.enum(OpenResponsesReasoningStatusCompleted); /** @internal */ -export type OpenResponsesReasoningStatusUnion$Outbound = - | string - | string - | string; +export type OpenResponsesReasoningStatusUnion$Outbound = string | string | string; /** @internal */ export const OpenResponsesReasoningStatusUnion$outboundSchema: z.ZodType< @@ -120,9 +114,7 @@ export function openResponsesReasoningStatusUnionToJSON( openResponsesReasoningStatusUnion: OpenResponsesReasoningStatusUnion, ): string { return JSON.stringify( - OpenResponsesReasoningStatusUnion$outboundSchema.parse( - openResponsesReasoningStatusUnion, - ), + OpenResponsesReasoningStatusUnion$outboundSchema.parse(openResponsesReasoningStatusUnion), ); } @@ -148,29 +140,31 @@ export type OpenResponsesReasoning$Outbound = { export const OpenResponsesReasoning$outboundSchema: z.ZodType< OpenResponsesReasoning$Outbound, OpenResponsesReasoning -> = z.object({ - type: OpenResponsesReasoningType$outboundSchema, - id: z.string(), - content: z.array(ReasoningTextContent$outboundSchema).optional(), - summary: z.array(ReasoningSummaryText$outboundSchema), - encryptedContent: z.nullable(z.string()).optional(), - status: z.union([ - OpenResponsesReasoningStatusCompleted$outboundSchema, - OpenResponsesReasoningStatusIncomplete$outboundSchema, - OpenResponsesReasoningStatusInProgress$outboundSchema, - ]).optional(), - signature: z.nullable(z.string()).optional(), - format: z.nullable(OpenResponsesReasoningFormat$outboundSchema).optional(), -}).transform((v) => { - return remap$(v, { - encryptedContent: "encrypted_content", +> = z + .object({ + type: OpenResponsesReasoningType$outboundSchema, + id: z.string(), + content: z.array(ReasoningTextContent$outboundSchema).optional(), + summary: z.array(ReasoningSummaryText$outboundSchema), + encryptedContent: z.nullable(z.string()).optional(), + status: z + .union([ + OpenResponsesReasoningStatusCompleted$outboundSchema, + OpenResponsesReasoningStatusIncomplete$outboundSchema, + OpenResponsesReasoningStatusInProgress$outboundSchema, + ]) + .optional(), + signature: z.nullable(z.string()).optional(), + format: z.nullable(OpenResponsesReasoningFormat$outboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + encryptedContent: 'encrypted_content', + }); }); -}); export function openResponsesReasoningToJSON( openResponsesReasoning: OpenResponsesReasoning, ): string { - return JSON.stringify( - OpenResponsesReasoning$outboundSchema.parse(openResponsesReasoning), - ); + return JSON.stringify(OpenResponsesReasoning$outboundSchema.parse(openResponsesReasoning)); } diff --git a/src/models/openresponsesreasoningconfig.ts b/src/models/openresponsesreasoningconfig.ts index 6c2046fa..b3591f72 100644 --- a/src/models/openresponsesreasoningconfig.ts +++ b/src/models/openresponsesreasoningconfig.ts @@ -3,16 +3,13 @@ * @generated-id: c2f9d074fbd4 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { - OpenAIResponsesReasoningEffort, - OpenAIResponsesReasoningEffort$outboundSchema, -} from "./openairesponsesreasoningeffort.js"; -import { - ReasoningSummaryVerbosity, - ReasoningSummaryVerbosity$outboundSchema, -} from "./reasoningsummaryverbosity.js"; +import type { OpenAIResponsesReasoningEffort } from './openairesponsesreasoningeffort.js'; +import type { ReasoningSummaryVerbosity } from './reasoningsummaryverbosity.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { OpenAIResponsesReasoningEffort$outboundSchema } from './openairesponsesreasoningeffort.js'; +import { ReasoningSummaryVerbosity$outboundSchema } from './reasoningsummaryverbosity.js'; /** * Configuration for reasoning mode in the response @@ -36,23 +33,23 @@ export type OpenResponsesReasoningConfig$Outbound = { export const OpenResponsesReasoningConfig$outboundSchema: z.ZodType< OpenResponsesReasoningConfig$Outbound, OpenResponsesReasoningConfig -> = z.object({ - effort: z.nullable(OpenAIResponsesReasoningEffort$outboundSchema).optional(), - summary: ReasoningSummaryVerbosity$outboundSchema.optional(), - maxTokens: z.nullable(z.number()).optional(), - enabled: z.nullable(z.boolean()).optional(), -}).transform((v) => { - return remap$(v, { - maxTokens: "max_tokens", +> = z + .object({ + effort: z.nullable(OpenAIResponsesReasoningEffort$outboundSchema).optional(), + summary: ReasoningSummaryVerbosity$outboundSchema.optional(), + maxTokens: z.nullable(z.number()).optional(), + enabled: z.nullable(z.boolean()).optional(), + }) + .transform((v) => { + return remap$(v, { + maxTokens: 'max_tokens', + }); }); -}); export function openResponsesReasoningConfigToJSON( openResponsesReasoningConfig: OpenResponsesReasoningConfig, ): string { return JSON.stringify( - OpenResponsesReasoningConfig$outboundSchema.parse( - openResponsesReasoningConfig, - ), + OpenResponsesReasoningConfig$outboundSchema.parse(openResponsesReasoningConfig), ); } diff --git a/src/models/openresponsesreasoningdeltaevent.ts b/src/models/openresponsesreasoningdeltaevent.ts index d306e0a7..02d9423e 100644 --- a/src/models/openresponsesreasoningdeltaevent.ts +++ b/src/models/openresponsesreasoningdeltaevent.ts @@ -3,17 +3,18 @@ * @generated-id: 32b751d1d3d7 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * Event emitted when reasoning text delta is streamed */ export type OpenResponsesReasoningDeltaEvent = { - type: "response.reasoning_text.delta"; + type: 'response.reasoning_text.delta'; outputIndex: number; itemId: string; contentIndex: number; @@ -25,21 +26,23 @@ export type OpenResponsesReasoningDeltaEvent = { export const OpenResponsesReasoningDeltaEvent$inboundSchema: z.ZodType< OpenResponsesReasoningDeltaEvent, unknown -> = z.object({ - type: z.literal("response.reasoning_text.delta"), - output_index: z.number(), - item_id: z.string(), - content_index: z.number(), - delta: z.string(), - sequence_number: z.number(), -}).transform((v) => { - return remap$(v, { - "output_index": "outputIndex", - "item_id": "itemId", - "content_index": "contentIndex", - "sequence_number": "sequenceNumber", +> = z + .object({ + type: z.literal('response.reasoning_text.delta'), + output_index: z.number(), + item_id: z.string(), + content_index: z.number(), + delta: z.string(), + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + output_index: 'outputIndex', + item_id: 'itemId', + content_index: 'contentIndex', + sequence_number: 'sequenceNumber', + }); }); -}); export function openResponsesReasoningDeltaEventFromJSON( jsonString: string, diff --git a/src/models/openresponsesreasoningdoneevent.ts b/src/models/openresponsesreasoningdoneevent.ts index adafa6bf..ab6bca0a 100644 --- a/src/models/openresponsesreasoningdoneevent.ts +++ b/src/models/openresponsesreasoningdoneevent.ts @@ -3,17 +3,18 @@ * @generated-id: f76803b0bdd0 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * Event emitted when reasoning text streaming is complete */ export type OpenResponsesReasoningDoneEvent = { - type: "response.reasoning_text.done"; + type: 'response.reasoning_text.done'; outputIndex: number; itemId: string; contentIndex: number; @@ -25,21 +26,23 @@ export type OpenResponsesReasoningDoneEvent = { export const OpenResponsesReasoningDoneEvent$inboundSchema: z.ZodType< OpenResponsesReasoningDoneEvent, unknown -> = z.object({ - type: z.literal("response.reasoning_text.done"), - output_index: z.number(), - item_id: z.string(), - content_index: z.number(), - text: z.string(), - sequence_number: z.number(), -}).transform((v) => { - return remap$(v, { - "output_index": "outputIndex", - "item_id": "itemId", - "content_index": "contentIndex", - "sequence_number": "sequenceNumber", +> = z + .object({ + type: z.literal('response.reasoning_text.done'), + output_index: z.number(), + item_id: z.string(), + content_index: z.number(), + text: z.string(), + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + output_index: 'outputIndex', + item_id: 'itemId', + content_index: 'contentIndex', + sequence_number: 'sequenceNumber', + }); }); -}); export function openResponsesReasoningDoneEventFromJSON( jsonString: string, diff --git a/src/models/openresponsesreasoningsummarypartaddedevent.ts b/src/models/openresponsesreasoningsummarypartaddedevent.ts index 1a65568c..8203243d 100644 --- a/src/models/openresponsesreasoningsummarypartaddedevent.ts +++ b/src/models/openresponsesreasoningsummarypartaddedevent.ts @@ -3,21 +3,20 @@ * @generated-id: e83b9ca2ee64 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { - ReasoningSummaryText, - ReasoningSummaryText$inboundSchema, -} from "./reasoningsummarytext.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { ReasoningSummaryText } from './reasoningsummarytext.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { ReasoningSummaryText$inboundSchema } from './reasoningsummarytext.js'; /** * Event emitted when a reasoning summary part is added */ export type OpenResponsesReasoningSummaryPartAddedEvent = { - type: "response.reasoning_summary_part.added"; + type: 'response.reasoning_summary_part.added'; outputIndex: number; itemId: string; summaryIndex: number; @@ -26,35 +25,33 @@ export type OpenResponsesReasoningSummaryPartAddedEvent = { }; /** @internal */ -export const OpenResponsesReasoningSummaryPartAddedEvent$inboundSchema: - z.ZodType = z.object({ - type: z.literal("response.reasoning_summary_part.added"), +export const OpenResponsesReasoningSummaryPartAddedEvent$inboundSchema: z.ZodType< + OpenResponsesReasoningSummaryPartAddedEvent, + unknown +> = z + .object({ + type: z.literal('response.reasoning_summary_part.added'), output_index: z.number(), item_id: z.string(), summary_index: z.number(), part: ReasoningSummaryText$inboundSchema, sequence_number: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "output_index": "outputIndex", - "item_id": "itemId", - "summary_index": "summaryIndex", - "sequence_number": "sequenceNumber", + output_index: 'outputIndex', + item_id: 'itemId', + summary_index: 'summaryIndex', + sequence_number: 'sequenceNumber', }); }); export function openResponsesReasoningSummaryPartAddedEventFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesReasoningSummaryPartAddedEvent, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesReasoningSummaryPartAddedEvent$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesReasoningSummaryPartAddedEvent$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesReasoningSummaryPartAddedEvent' from JSON`, ); } diff --git a/src/models/openresponsesreasoningsummarytextdeltaevent.ts b/src/models/openresponsesreasoningsummarytextdeltaevent.ts index f29f6bbe..cd2be8fc 100644 --- a/src/models/openresponsesreasoningsummarytextdeltaevent.ts +++ b/src/models/openresponsesreasoningsummarytextdeltaevent.ts @@ -3,17 +3,18 @@ * @generated-id: 61ee69f0a41f */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * Event emitted when reasoning summary text delta is streamed */ export type OpenResponsesReasoningSummaryTextDeltaEvent = { - type: "response.reasoning_summary_text.delta"; + type: 'response.reasoning_summary_text.delta'; itemId: string; outputIndex: number; summaryIndex: number; @@ -22,35 +23,33 @@ export type OpenResponsesReasoningSummaryTextDeltaEvent = { }; /** @internal */ -export const OpenResponsesReasoningSummaryTextDeltaEvent$inboundSchema: - z.ZodType = z.object({ - type: z.literal("response.reasoning_summary_text.delta"), +export const OpenResponsesReasoningSummaryTextDeltaEvent$inboundSchema: z.ZodType< + OpenResponsesReasoningSummaryTextDeltaEvent, + unknown +> = z + .object({ + type: z.literal('response.reasoning_summary_text.delta'), item_id: z.string(), output_index: z.number(), summary_index: z.number(), delta: z.string(), sequence_number: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "item_id": "itemId", - "output_index": "outputIndex", - "summary_index": "summaryIndex", - "sequence_number": "sequenceNumber", + item_id: 'itemId', + output_index: 'outputIndex', + summary_index: 'summaryIndex', + sequence_number: 'sequenceNumber', }); }); export function openResponsesReasoningSummaryTextDeltaEventFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesReasoningSummaryTextDeltaEvent, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesReasoningSummaryTextDeltaEvent$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesReasoningSummaryTextDeltaEvent$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesReasoningSummaryTextDeltaEvent' from JSON`, ); } diff --git a/src/models/openresponsesreasoningsummarytextdoneevent.ts b/src/models/openresponsesreasoningsummarytextdoneevent.ts index 438e3268..8c64c150 100644 --- a/src/models/openresponsesreasoningsummarytextdoneevent.ts +++ b/src/models/openresponsesreasoningsummarytextdoneevent.ts @@ -3,17 +3,18 @@ * @generated-id: 0519f084cea8 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * Event emitted when reasoning summary text streaming is complete */ export type OpenResponsesReasoningSummaryTextDoneEvent = { - type: "response.reasoning_summary_text.done"; + type: 'response.reasoning_summary_text.done'; itemId: string; outputIndex: number; summaryIndex: number; @@ -22,35 +23,33 @@ export type OpenResponsesReasoningSummaryTextDoneEvent = { }; /** @internal */ -export const OpenResponsesReasoningSummaryTextDoneEvent$inboundSchema: - z.ZodType = z.object({ - type: z.literal("response.reasoning_summary_text.done"), +export const OpenResponsesReasoningSummaryTextDoneEvent$inboundSchema: z.ZodType< + OpenResponsesReasoningSummaryTextDoneEvent, + unknown +> = z + .object({ + type: z.literal('response.reasoning_summary_text.done'), item_id: z.string(), output_index: z.number(), summary_index: z.number(), text: z.string(), sequence_number: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "item_id": "itemId", - "output_index": "outputIndex", - "summary_index": "summaryIndex", - "sequence_number": "sequenceNumber", + item_id: 'itemId', + output_index: 'outputIndex', + summary_index: 'summaryIndex', + sequence_number: 'sequenceNumber', }); }); export function openResponsesReasoningSummaryTextDoneEventFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesReasoningSummaryTextDoneEvent, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesReasoningSummaryTextDoneEvent$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesReasoningSummaryTextDoneEvent$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesReasoningSummaryTextDoneEvent' from JSON`, ); } diff --git a/src/models/openresponsesrequest.ts b/src/models/openresponsesrequest.ts index b415f732..6cc12588 100644 --- a/src/models/openresponsesrequest.ts +++ b/src/models/openresponsesrequest.ts @@ -3,90 +3,81 @@ * @generated-id: ff8a31d46b1c */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import * as openEnums from "../types/enums.js"; -import { ClosedEnum, OpenEnum } from "../types/enums.js"; -import { - DataCollection, - DataCollection$outboundSchema, -} from "./datacollection.js"; -import { - OpenAIResponsesIncludable, - OpenAIResponsesIncludable$outboundSchema, -} from "./openairesponsesincludable.js"; -import { +import type { ClosedEnum, OpenEnum } from '../types/enums.js'; +import type { DataCollection } from './datacollection.js'; +import type { OpenAIResponsesIncludable } from './openairesponsesincludable.js'; +import type { OpenAIResponsesPrompt, OpenAIResponsesPrompt$Outbound, - OpenAIResponsesPrompt$outboundSchema, -} from "./openairesponsesprompt.js"; -import { +} from './openairesponsesprompt.js'; +import type { OpenAIResponsesToolChoiceUnion, OpenAIResponsesToolChoiceUnion$Outbound, - OpenAIResponsesToolChoiceUnion$outboundSchema, -} from "./openairesponsestoolchoiceunion.js"; -import { - OpenResponsesInput, - OpenResponsesInput$Outbound, - OpenResponsesInput$outboundSchema, -} from "./openresponsesinput.js"; -import { +} from './openairesponsestoolchoiceunion.js'; +import type { OpenResponsesInput, OpenResponsesInput$Outbound } from './openresponsesinput.js'; +import type { OpenResponsesReasoningConfig, OpenResponsesReasoningConfig$Outbound, - OpenResponsesReasoningConfig$outboundSchema, -} from "./openresponsesreasoningconfig.js"; -import { +} from './openresponsesreasoningconfig.js'; +import type { OpenResponsesResponseText, OpenResponsesResponseText$Outbound, - OpenResponsesResponseText$outboundSchema, -} from "./openresponsesresponsetext.js"; -import { +} from './openresponsesresponsetext.js'; +import type { OpenResponsesWebSearch20250826Tool, OpenResponsesWebSearch20250826Tool$Outbound, - OpenResponsesWebSearch20250826Tool$outboundSchema, -} from "./openresponseswebsearch20250826tool.js"; -import { +} from './openresponseswebsearch20250826tool.js'; +import type { OpenResponsesWebSearchPreview20250311Tool, OpenResponsesWebSearchPreview20250311Tool$Outbound, - OpenResponsesWebSearchPreview20250311Tool$outboundSchema, -} from "./openresponseswebsearchpreview20250311tool.js"; -import { +} from './openresponseswebsearchpreview20250311tool.js'; +import type { OpenResponsesWebSearchPreviewTool, OpenResponsesWebSearchPreviewTool$Outbound, - OpenResponsesWebSearchPreviewTool$outboundSchema, -} from "./openresponseswebsearchpreviewtool.js"; -import { +} from './openresponseswebsearchpreviewtool.js'; +import type { OpenResponsesWebSearchTool, OpenResponsesWebSearchTool$Outbound, - OpenResponsesWebSearchTool$outboundSchema, -} from "./openresponseswebsearchtool.js"; -import { - PDFParserOptions, - PDFParserOptions$Outbound, - PDFParserOptions$outboundSchema, -} from "./pdfparseroptions.js"; -import { ProviderName, ProviderName$outboundSchema } from "./providername.js"; -import { ProviderSort, ProviderSort$outboundSchema } from "./providersort.js"; -import { - ProviderSortConfig, - ProviderSortConfig$Outbound, - ProviderSortConfig$outboundSchema, -} from "./providersortconfig.js"; -import { Quantization, Quantization$outboundSchema } from "./quantization.js"; -import { - WebSearchEngine, - WebSearchEngine$outboundSchema, -} from "./websearchengine.js"; +} from './openresponseswebsearchtool.js'; +import type { PDFParserOptions, PDFParserOptions$Outbound } from './pdfparseroptions.js'; +import type { ProviderName } from './providername.js'; +import type { ProviderSort } from './providersort.js'; +import type { ProviderSortConfig, ProviderSortConfig$Outbound } from './providersortconfig.js'; +import type { Quantization } from './quantization.js'; +import type { WebSearchEngine } from './websearchengine.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import * as openEnums from '../types/enums.js'; +import { DataCollection$outboundSchema } from './datacollection.js'; +import { OpenAIResponsesIncludable$outboundSchema } from './openairesponsesincludable.js'; +import { OpenAIResponsesPrompt$outboundSchema } from './openairesponsesprompt.js'; +import { OpenAIResponsesToolChoiceUnion$outboundSchema } from './openairesponsestoolchoiceunion.js'; +import { OpenResponsesInput$outboundSchema } from './openresponsesinput.js'; +import { OpenResponsesReasoningConfig$outboundSchema } from './openresponsesreasoningconfig.js'; +import { OpenResponsesResponseText$outboundSchema } from './openresponsesresponsetext.js'; +import { OpenResponsesWebSearch20250826Tool$outboundSchema } from './openresponseswebsearch20250826tool.js'; +import { OpenResponsesWebSearchPreview20250311Tool$outboundSchema } from './openresponseswebsearchpreview20250311tool.js'; +import { OpenResponsesWebSearchPreviewTool$outboundSchema } from './openresponseswebsearchpreviewtool.js'; +import { OpenResponsesWebSearchTool$outboundSchema } from './openresponseswebsearchtool.js'; +import { PDFParserOptions$outboundSchema } from './pdfparseroptions.js'; +import { ProviderName$outboundSchema } from './providername.js'; +import { ProviderSort$outboundSchema } from './providersort.js'; +import { ProviderSortConfig$outboundSchema } from './providersortconfig.js'; +import { Quantization$outboundSchema } from './quantization.js'; +import { WebSearchEngine$outboundSchema } from './websearchengine.js'; /** * Function tool definition */ export type OpenResponsesRequestToolFunction = { - type: "function"; + type: 'function'; name: string; description?: string | null | undefined; strict?: boolean | null | undefined; - parameters: { [k: string]: any | null } | null; + parameters: { + [k: string]: any | null; + } | null; }; export type OpenResponsesRequestToolUnion = @@ -97,13 +88,13 @@ export type OpenResponsesRequestToolUnion = | OpenResponsesWebSearch20250826Tool; export const ServiceTier = { - Auto: "auto", + Auto: 'auto', } as const; export type ServiceTier = ClosedEnum; export const Truncation = { - Auto: "auto", - Disabled: "disabled", + Auto: 'auto', + Disabled: 'disabled', } as const; export type Truncation = OpenEnum; @@ -224,7 +215,7 @@ export type OpenResponsesRequestProvider = { }; export type OpenResponsesRequestPluginResponseHealing = { - id: "response-healing"; + id: 'response-healing'; /** * Set to false to disable the response-healing plugin for this request. Defaults to true. */ @@ -232,7 +223,7 @@ export type OpenResponsesRequestPluginResponseHealing = { }; export type OpenResponsesRequestPluginFileParser = { - id: "file-parser"; + id: 'file-parser'; /** * Set to false to disable the file-parser plugin for this request. Defaults to true. */ @@ -244,7 +235,7 @@ export type OpenResponsesRequestPluginFileParser = { }; export type OpenResponsesRequestPluginWeb = { - id: "web"; + id: 'web'; /** * Set to false to disable the web-search plugin for this request. Defaults to true. */ @@ -258,7 +249,7 @@ export type OpenResponsesRequestPluginWeb = { }; export type OpenResponsesRequestPluginModeration = { - id: "moderation"; + id: 'moderation'; }; export type OpenResponsesRequestPluginUnion = @@ -279,15 +270,20 @@ export type OpenResponsesRequest = { /** * Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. */ - metadata?: { [k: string]: string } | null | undefined; + metadata?: + | { + [k: string]: string; + } + | null + | undefined; tools?: | Array< - | OpenResponsesRequestToolFunction - | OpenResponsesWebSearchPreviewTool - | OpenResponsesWebSearchPreview20250311Tool - | OpenResponsesWebSearchTool - | OpenResponsesWebSearch20250826Tool - > + | OpenResponsesRequestToolFunction + | OpenResponsesWebSearchPreviewTool + | OpenResponsesWebSearchPreview20250311Tool + | OpenResponsesWebSearchTool + | OpenResponsesWebSearch20250826Tool + > | undefined; toolChoice?: OpenAIResponsesToolChoiceUnion | undefined; parallelToolCalls?: boolean | null | undefined; @@ -324,11 +320,11 @@ export type OpenResponsesRequest = { */ plugins?: | Array< - | OpenResponsesRequestPluginModeration - | OpenResponsesRequestPluginWeb - | OpenResponsesRequestPluginFileParser - | OpenResponsesRequestPluginResponseHealing - > + | OpenResponsesRequestPluginModeration + | OpenResponsesRequestPluginWeb + | OpenResponsesRequestPluginFileParser + | OpenResponsesRequestPluginResponseHealing + > | undefined; /** * A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters. @@ -342,11 +338,13 @@ export type OpenResponsesRequest = { /** @internal */ export type OpenResponsesRequestToolFunction$Outbound = { - type: "function"; + type: 'function'; name: string; description?: string | null | undefined; strict?: boolean | null | undefined; - parameters: { [k: string]: any | null } | null; + parameters: { + [k: string]: any | null; + } | null; }; /** @internal */ @@ -354,7 +352,7 @@ export const OpenResponsesRequestToolFunction$outboundSchema: z.ZodType< OpenResponsesRequestToolFunction$Outbound, OpenResponsesRequestToolFunction > = z.object({ - type: z.literal("function"), + type: z.literal('function'), name: z.string(), description: z.nullable(z.string()).optional(), strict: z.nullable(z.boolean()).optional(), @@ -365,9 +363,7 @@ export function openResponsesRequestToolFunctionToJSON( openResponsesRequestToolFunction: OpenResponsesRequestToolFunction, ): string { return JSON.stringify( - OpenResponsesRequestToolFunction$outboundSchema.parse( - openResponsesRequestToolFunction, - ), + OpenResponsesRequestToolFunction$outboundSchema.parse(openResponsesRequestToolFunction), ); } @@ -395,16 +391,12 @@ export function openResponsesRequestToolUnionToJSON( openResponsesRequestToolUnion: OpenResponsesRequestToolUnion, ): string { return JSON.stringify( - OpenResponsesRequestToolUnion$outboundSchema.parse( - openResponsesRequestToolUnion, - ), + OpenResponsesRequestToolUnion$outboundSchema.parse(openResponsesRequestToolUnion), ); } /** @internal */ -export const ServiceTier$outboundSchema: z.ZodEnum = z.enum( - ServiceTier, -); +export const ServiceTier$outboundSchema: z.ZodEnum = z.enum(ServiceTier); /** @internal */ export const Truncation$outboundSchema: z.ZodType = @@ -417,14 +409,15 @@ export type OpenResponsesRequestOrder$Outbound = string | string; export const OpenResponsesRequestOrder$outboundSchema: z.ZodType< OpenResponsesRequestOrder$Outbound, OpenResponsesRequestOrder -> = z.union([ProviderName$outboundSchema, z.string()]); +> = z.union([ + ProviderName$outboundSchema, + z.string(), +]); export function openResponsesRequestOrderToJSON( openResponsesRequestOrder: OpenResponsesRequestOrder, ): string { - return JSON.stringify( - OpenResponsesRequestOrder$outboundSchema.parse(openResponsesRequestOrder), - ); + return JSON.stringify(OpenResponsesRequestOrder$outboundSchema.parse(openResponsesRequestOrder)); } /** @internal */ @@ -434,14 +427,15 @@ export type OpenResponsesRequestOnly$Outbound = string | string; export const OpenResponsesRequestOnly$outboundSchema: z.ZodType< OpenResponsesRequestOnly$Outbound, OpenResponsesRequestOnly -> = z.union([ProviderName$outboundSchema, z.string()]); +> = z.union([ + ProviderName$outboundSchema, + z.string(), +]); export function openResponsesRequestOnlyToJSON( openResponsesRequestOnly: OpenResponsesRequestOnly, ): string { - return JSON.stringify( - OpenResponsesRequestOnly$outboundSchema.parse(openResponsesRequestOnly), - ); + return JSON.stringify(OpenResponsesRequestOnly$outboundSchema.parse(openResponsesRequestOnly)); } /** @internal */ @@ -451,7 +445,10 @@ export type OpenResponsesRequestIgnore$Outbound = string | string; export const OpenResponsesRequestIgnore$outboundSchema: z.ZodType< OpenResponsesRequestIgnore$Outbound, OpenResponsesRequestIgnore -> = z.union([ProviderName$outboundSchema, z.string()]); +> = z.union([ + ProviderName$outboundSchema, + z.string(), +]); export function openResponsesRequestIgnoreToJSON( openResponsesRequestIgnore: OpenResponsesRequestIgnore, @@ -462,10 +459,7 @@ export function openResponsesRequestIgnoreToJSON( } /** @internal */ -export type OpenResponsesRequestSort$Outbound = - | string - | ProviderSortConfig$Outbound - | any; +export type OpenResponsesRequestSort$Outbound = string | ProviderSortConfig$Outbound | any; /** @internal */ export const OpenResponsesRequestSort$outboundSchema: z.ZodType< @@ -480,9 +474,7 @@ export const OpenResponsesRequestSort$outboundSchema: z.ZodType< export function openResponsesRequestSortToJSON( openResponsesRequestSort: OpenResponsesRequestSort, ): string { - return JSON.stringify( - OpenResponsesRequestSort$outboundSchema.parse(openResponsesRequestSort), - ); + return JSON.stringify(OpenResponsesRequestSort$outboundSchema.parse(openResponsesRequestSort)); } /** @internal */ @@ -510,9 +502,7 @@ export function openResponsesRequestMaxPriceToJSON( openResponsesRequestMaxPrice: OpenResponsesRequestMaxPrice, ): string { return JSON.stringify( - OpenResponsesRequestMaxPrice$outboundSchema.parse( - openResponsesRequestMaxPrice, - ), + OpenResponsesRequestMaxPrice$outboundSchema.parse(openResponsesRequestMaxPrice), ); } @@ -539,76 +529,98 @@ export type OpenResponsesRequestProvider$Outbound = { export const OpenResponsesRequestProvider$outboundSchema: z.ZodType< OpenResponsesRequestProvider$Outbound, OpenResponsesRequestProvider -> = z.object({ - allowFallbacks: z.nullable(z.boolean()).optional(), - requireParameters: z.nullable(z.boolean()).optional(), - dataCollection: z.nullable(DataCollection$outboundSchema).optional(), - zdr: z.nullable(z.boolean()).optional(), - enforceDistillableText: z.nullable(z.boolean()).optional(), - order: z.nullable(z.array(z.union([ProviderName$outboundSchema, z.string()]))) - .optional(), - only: z.nullable(z.array(z.union([ProviderName$outboundSchema, z.string()]))) - .optional(), - ignore: z.nullable( - z.array(z.union([ProviderName$outboundSchema, z.string()])), - ).optional(), - quantizations: z.nullable(z.array(Quantization$outboundSchema)).optional(), - sort: z.nullable( - z.union([ - ProviderSort$outboundSchema, - ProviderSortConfig$outboundSchema, - z.any(), - ]), - ).optional(), - maxPrice: z.lazy(() => OpenResponsesRequestMaxPrice$outboundSchema) - .optional(), - preferredMinThroughput: z.nullable(z.number()).optional(), - preferredMaxLatency: z.nullable(z.number()).optional(), - minThroughput: z.nullable(z.number()).optional(), - maxLatency: z.nullable(z.number()).optional(), -}).transform((v) => { - return remap$(v, { - allowFallbacks: "allow_fallbacks", - requireParameters: "require_parameters", - dataCollection: "data_collection", - enforceDistillableText: "enforce_distillable_text", - maxPrice: "max_price", - preferredMinThroughput: "preferred_min_throughput", - preferredMaxLatency: "preferred_max_latency", - minThroughput: "min_throughput", - maxLatency: "max_latency", +> = z + .object({ + allowFallbacks: z.nullable(z.boolean()).optional(), + requireParameters: z.nullable(z.boolean()).optional(), + dataCollection: z.nullable(DataCollection$outboundSchema).optional(), + zdr: z.nullable(z.boolean()).optional(), + enforceDistillableText: z.nullable(z.boolean()).optional(), + order: z + .nullable( + z.array( + z.union([ + ProviderName$outboundSchema, + z.string(), + ]), + ), + ) + .optional(), + only: z + .nullable( + z.array( + z.union([ + ProviderName$outboundSchema, + z.string(), + ]), + ), + ) + .optional(), + ignore: z + .nullable( + z.array( + z.union([ + ProviderName$outboundSchema, + z.string(), + ]), + ), + ) + .optional(), + quantizations: z.nullable(z.array(Quantization$outboundSchema)).optional(), + sort: z + .nullable( + z.union([ + ProviderSort$outboundSchema, + ProviderSortConfig$outboundSchema, + z.any(), + ]), + ) + .optional(), + maxPrice: z.lazy(() => OpenResponsesRequestMaxPrice$outboundSchema).optional(), + preferredMinThroughput: z.nullable(z.number()).optional(), + preferredMaxLatency: z.nullable(z.number()).optional(), + minThroughput: z.nullable(z.number()).optional(), + maxLatency: z.nullable(z.number()).optional(), + }) + .transform((v) => { + return remap$(v, { + allowFallbacks: 'allow_fallbacks', + requireParameters: 'require_parameters', + dataCollection: 'data_collection', + enforceDistillableText: 'enforce_distillable_text', + maxPrice: 'max_price', + preferredMinThroughput: 'preferred_min_throughput', + preferredMaxLatency: 'preferred_max_latency', + minThroughput: 'min_throughput', + maxLatency: 'max_latency', + }); }); -}); export function openResponsesRequestProviderToJSON( openResponsesRequestProvider: OpenResponsesRequestProvider, ): string { return JSON.stringify( - OpenResponsesRequestProvider$outboundSchema.parse( - openResponsesRequestProvider, - ), + OpenResponsesRequestProvider$outboundSchema.parse(openResponsesRequestProvider), ); } /** @internal */ export type OpenResponsesRequestPluginResponseHealing$Outbound = { - id: "response-healing"; + id: 'response-healing'; enabled?: boolean | undefined; }; /** @internal */ -export const OpenResponsesRequestPluginResponseHealing$outboundSchema: - z.ZodType< - OpenResponsesRequestPluginResponseHealing$Outbound, - OpenResponsesRequestPluginResponseHealing - > = z.object({ - id: z.literal("response-healing"), - enabled: z.boolean().optional(), - }); +export const OpenResponsesRequestPluginResponseHealing$outboundSchema: z.ZodType< + OpenResponsesRequestPluginResponseHealing$Outbound, + OpenResponsesRequestPluginResponseHealing +> = z.object({ + id: z.literal('response-healing'), + enabled: z.boolean().optional(), +}); export function openResponsesRequestPluginResponseHealingToJSON( - openResponsesRequestPluginResponseHealing: - OpenResponsesRequestPluginResponseHealing, + openResponsesRequestPluginResponseHealing: OpenResponsesRequestPluginResponseHealing, ): string { return JSON.stringify( OpenResponsesRequestPluginResponseHealing$outboundSchema.parse( @@ -619,7 +631,7 @@ export function openResponsesRequestPluginResponseHealingToJSON( /** @internal */ export type OpenResponsesRequestPluginFileParser$Outbound = { - id: "file-parser"; + id: 'file-parser'; enabled?: boolean | undefined; pdf?: PDFParserOptions$Outbound | undefined; }; @@ -629,7 +641,7 @@ export const OpenResponsesRequestPluginFileParser$outboundSchema: z.ZodType< OpenResponsesRequestPluginFileParser$Outbound, OpenResponsesRequestPluginFileParser > = z.object({ - id: z.literal("file-parser"), + id: z.literal('file-parser'), enabled: z.boolean().optional(), pdf: PDFParserOptions$outboundSchema.optional(), }); @@ -638,15 +650,13 @@ export function openResponsesRequestPluginFileParserToJSON( openResponsesRequestPluginFileParser: OpenResponsesRequestPluginFileParser, ): string { return JSON.stringify( - OpenResponsesRequestPluginFileParser$outboundSchema.parse( - openResponsesRequestPluginFileParser, - ), + OpenResponsesRequestPluginFileParser$outboundSchema.parse(openResponsesRequestPluginFileParser), ); } /** @internal */ export type OpenResponsesRequestPluginWeb$Outbound = { - id: "web"; + id: 'web'; enabled?: boolean | undefined; max_results?: number | undefined; search_prompt?: string | undefined; @@ -657,32 +667,32 @@ export type OpenResponsesRequestPluginWeb$Outbound = { export const OpenResponsesRequestPluginWeb$outboundSchema: z.ZodType< OpenResponsesRequestPluginWeb$Outbound, OpenResponsesRequestPluginWeb -> = z.object({ - id: z.literal("web"), - enabled: z.boolean().optional(), - maxResults: z.number().optional(), - searchPrompt: z.string().optional(), - engine: WebSearchEngine$outboundSchema.optional(), -}).transform((v) => { - return remap$(v, { - maxResults: "max_results", - searchPrompt: "search_prompt", +> = z + .object({ + id: z.literal('web'), + enabled: z.boolean().optional(), + maxResults: z.number().optional(), + searchPrompt: z.string().optional(), + engine: WebSearchEngine$outboundSchema.optional(), + }) + .transform((v) => { + return remap$(v, { + maxResults: 'max_results', + searchPrompt: 'search_prompt', + }); }); -}); export function openResponsesRequestPluginWebToJSON( openResponsesRequestPluginWeb: OpenResponsesRequestPluginWeb, ): string { return JSON.stringify( - OpenResponsesRequestPluginWeb$outboundSchema.parse( - openResponsesRequestPluginWeb, - ), + OpenResponsesRequestPluginWeb$outboundSchema.parse(openResponsesRequestPluginWeb), ); } /** @internal */ export type OpenResponsesRequestPluginModeration$Outbound = { - id: "moderation"; + id: 'moderation'; }; /** @internal */ @@ -690,16 +700,14 @@ export const OpenResponsesRequestPluginModeration$outboundSchema: z.ZodType< OpenResponsesRequestPluginModeration$Outbound, OpenResponsesRequestPluginModeration > = z.object({ - id: z.literal("moderation"), + id: z.literal('moderation'), }); export function openResponsesRequestPluginModerationToJSON( openResponsesRequestPluginModeration: OpenResponsesRequestPluginModeration, ): string { return JSON.stringify( - OpenResponsesRequestPluginModeration$outboundSchema.parse( - openResponsesRequestPluginModeration, - ), + OpenResponsesRequestPluginModeration$outboundSchema.parse(openResponsesRequestPluginModeration), ); } @@ -725,9 +733,7 @@ export function openResponsesRequestPluginUnionToJSON( openResponsesRequestPluginUnion: OpenResponsesRequestPluginUnion, ): string { return JSON.stringify( - OpenResponsesRequestPluginUnion$outboundSchema.parse( - openResponsesRequestPluginUnion, - ), + OpenResponsesRequestPluginUnion$outboundSchema.parse(openResponsesRequestPluginUnion), ); } @@ -735,15 +741,20 @@ export function openResponsesRequestPluginUnionToJSON( export type OpenResponsesRequest$Outbound = { input?: OpenResponsesInput$Outbound | undefined; instructions?: string | null | undefined; - metadata?: { [k: string]: string } | null | undefined; + metadata?: + | { + [k: string]: string; + } + | null + | undefined; tools?: | Array< - | OpenResponsesRequestToolFunction$Outbound - | OpenResponsesWebSearchPreviewTool$Outbound - | OpenResponsesWebSearchPreview20250311Tool$Outbound - | OpenResponsesWebSearchTool$Outbound - | OpenResponsesWebSearch20250826Tool$Outbound - > + | OpenResponsesRequestToolFunction$Outbound + | OpenResponsesWebSearchPreviewTool$Outbound + | OpenResponsesWebSearchPreview20250311Tool$Outbound + | OpenResponsesWebSearchTool$Outbound + | OpenResponsesWebSearch20250826Tool$Outbound + > | undefined; tool_choice?: OpenAIResponsesToolChoiceUnion$Outbound | undefined; parallel_tool_calls?: boolean | null | undefined; @@ -768,11 +779,11 @@ export type OpenResponsesRequest$Outbound = { provider?: OpenResponsesRequestProvider$Outbound | null | undefined; plugins?: | Array< - | OpenResponsesRequestPluginModeration$Outbound - | OpenResponsesRequestPluginWeb$Outbound - | OpenResponsesRequestPluginFileParser$Outbound - | OpenResponsesRequestPluginResponseHealing$Outbound - > + | OpenResponsesRequestPluginModeration$Outbound + | OpenResponsesRequestPluginWeb$Outbound + | OpenResponsesRequestPluginFileParser$Outbound + | OpenResponsesRequestPluginResponseHealing$Outbound + > | undefined; user?: string | undefined; session_id?: string | undefined; @@ -782,72 +793,71 @@ export type OpenResponsesRequest$Outbound = { export const OpenResponsesRequest$outboundSchema: z.ZodType< OpenResponsesRequest$Outbound, OpenResponsesRequest -> = z.object({ - input: OpenResponsesInput$outboundSchema.optional(), - instructions: z.nullable(z.string()).optional(), - metadata: z.nullable(z.record(z.string(), z.string())).optional(), - tools: z.array( - z.union([ - z.lazy(() => OpenResponsesRequestToolFunction$outboundSchema), - OpenResponsesWebSearchPreviewTool$outboundSchema, - OpenResponsesWebSearchPreview20250311Tool$outboundSchema, - OpenResponsesWebSearchTool$outboundSchema, - OpenResponsesWebSearch20250826Tool$outboundSchema, - ]), - ).optional(), - toolChoice: OpenAIResponsesToolChoiceUnion$outboundSchema.optional(), - parallelToolCalls: z.nullable(z.boolean()).optional(), - model: z.string().optional(), - models: z.array(z.string()).optional(), - text: OpenResponsesResponseText$outboundSchema.optional(), - reasoning: z.nullable(OpenResponsesReasoningConfig$outboundSchema).optional(), - maxOutputTokens: z.nullable(z.number()).optional(), - temperature: z.nullable(z.number()).optional(), - topP: z.nullable(z.number()).optional(), - topK: z.number().optional(), - promptCacheKey: z.nullable(z.string()).optional(), - previousResponseId: z.nullable(z.string()).optional(), - prompt: z.nullable(OpenAIResponsesPrompt$outboundSchema).optional(), - include: z.nullable(z.array(OpenAIResponsesIncludable$outboundSchema)) - .optional(), - background: z.nullable(z.boolean()).optional(), - safetyIdentifier: z.nullable(z.string()).optional(), - store: z.literal(false).default(false as const), - serviceTier: ServiceTier$outboundSchema.default("auto"), - truncation: z.nullable(Truncation$outboundSchema).optional(), - stream: z.boolean().default(false), - provider: z.nullable( - z.lazy(() => OpenResponsesRequestProvider$outboundSchema), - ).optional(), - plugins: z.array( - z.union([ - z.lazy(() => OpenResponsesRequestPluginModeration$outboundSchema), - z.lazy(() => OpenResponsesRequestPluginWeb$outboundSchema), - z.lazy(() => OpenResponsesRequestPluginFileParser$outboundSchema), - z.lazy(() => OpenResponsesRequestPluginResponseHealing$outboundSchema), - ]), - ).optional(), - user: z.string().optional(), - sessionId: z.string().optional(), -}).transform((v) => { - return remap$(v, { - toolChoice: "tool_choice", - parallelToolCalls: "parallel_tool_calls", - maxOutputTokens: "max_output_tokens", - topP: "top_p", - topK: "top_k", - promptCacheKey: "prompt_cache_key", - previousResponseId: "previous_response_id", - safetyIdentifier: "safety_identifier", - serviceTier: "service_tier", - sessionId: "session_id", +> = z + .object({ + input: OpenResponsesInput$outboundSchema.optional(), + instructions: z.nullable(z.string()).optional(), + metadata: z.nullable(z.record(z.string(), z.string())).optional(), + tools: z + .array( + z.union([ + z.lazy(() => OpenResponsesRequestToolFunction$outboundSchema), + OpenResponsesWebSearchPreviewTool$outboundSchema, + OpenResponsesWebSearchPreview20250311Tool$outboundSchema, + OpenResponsesWebSearchTool$outboundSchema, + OpenResponsesWebSearch20250826Tool$outboundSchema, + ]), + ) + .optional(), + toolChoice: OpenAIResponsesToolChoiceUnion$outboundSchema.optional(), + parallelToolCalls: z.nullable(z.boolean()).optional(), + model: z.string().optional(), + models: z.array(z.string()).optional(), + text: OpenResponsesResponseText$outboundSchema.optional(), + reasoning: z.nullable(OpenResponsesReasoningConfig$outboundSchema).optional(), + maxOutputTokens: z.nullable(z.number()).optional(), + temperature: z.nullable(z.number()).optional(), + topP: z.nullable(z.number()).optional(), + topK: z.number().optional(), + promptCacheKey: z.nullable(z.string()).optional(), + previousResponseId: z.nullable(z.string()).optional(), + prompt: z.nullable(OpenAIResponsesPrompt$outboundSchema).optional(), + include: z.nullable(z.array(OpenAIResponsesIncludable$outboundSchema)).optional(), + background: z.nullable(z.boolean()).optional(), + safetyIdentifier: z.nullable(z.string()).optional(), + store: z.literal(false).default(false as const), + serviceTier: ServiceTier$outboundSchema.default('auto'), + truncation: z.nullable(Truncation$outboundSchema).optional(), + stream: z.boolean().default(false), + provider: z.nullable(z.lazy(() => OpenResponsesRequestProvider$outboundSchema)).optional(), + plugins: z + .array( + z.union([ + z.lazy(() => OpenResponsesRequestPluginModeration$outboundSchema), + z.lazy(() => OpenResponsesRequestPluginWeb$outboundSchema), + z.lazy(() => OpenResponsesRequestPluginFileParser$outboundSchema), + z.lazy(() => OpenResponsesRequestPluginResponseHealing$outboundSchema), + ]), + ) + .optional(), + user: z.string().optional(), + sessionId: z.string().optional(), + }) + .transform((v) => { + return remap$(v, { + toolChoice: 'tool_choice', + parallelToolCalls: 'parallel_tool_calls', + maxOutputTokens: 'max_output_tokens', + topP: 'top_p', + topK: 'top_k', + promptCacheKey: 'prompt_cache_key', + previousResponseId: 'previous_response_id', + safetyIdentifier: 'safety_identifier', + serviceTier: 'service_tier', + sessionId: 'session_id', + }); }); -}); -export function openResponsesRequestToJSON( - openResponsesRequest: OpenResponsesRequest, -): string { - return JSON.stringify( - OpenResponsesRequest$outboundSchema.parse(openResponsesRequest), - ); +export function openResponsesRequestToJSON(openResponsesRequest: OpenResponsesRequest): string { + return JSON.stringify(OpenResponsesRequest$outboundSchema.parse(openResponsesRequest)); } diff --git a/src/models/openresponsesresponsetext.ts b/src/models/openresponsesresponsetext.ts index 56f6d642..c02f3887 100644 --- a/src/models/openresponsesresponsetext.ts +++ b/src/models/openresponsesresponsetext.ts @@ -3,19 +3,20 @@ * @generated-id: aded1ce23b04 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { +import type { OpenEnum } from '../types/enums.js'; +import type { ResponseFormatTextConfig, ResponseFormatTextConfig$Outbound, - ResponseFormatTextConfig$outboundSchema, -} from "./responseformattextconfig.js"; +} from './responseformattextconfig.js'; + +import * as z from 'zod/v4'; +import * as openEnums from '../types/enums.js'; +import { ResponseFormatTextConfig$outboundSchema } from './responseformattextconfig.js'; export const OpenResponsesResponseTextVerbosity = { - High: "high", - Low: "low", - Medium: "medium", + High: 'high', + Low: 'low', + Medium: 'medium', } as const; export type OpenResponsesResponseTextVerbosity = OpenEnum< typeof OpenResponsesResponseTextVerbosity @@ -50,14 +51,11 @@ export const OpenResponsesResponseText$outboundSchema: z.ZodType< OpenResponsesResponseText > = z.object({ format: ResponseFormatTextConfig$outboundSchema.optional(), - verbosity: z.nullable(OpenResponsesResponseTextVerbosity$outboundSchema) - .optional(), + verbosity: z.nullable(OpenResponsesResponseTextVerbosity$outboundSchema).optional(), }); export function openResponsesResponseTextToJSON( openResponsesResponseText: OpenResponsesResponseText, ): string { - return JSON.stringify( - OpenResponsesResponseText$outboundSchema.parse(openResponsesResponseText), - ); + return JSON.stringify(OpenResponsesResponseText$outboundSchema.parse(openResponsesResponseText)); } diff --git a/src/models/openresponsesstreamevent.ts b/src/models/openresponsesstreamevent.ts index 40398c79..bc6548b5 100644 --- a/src/models/openresponsesstreamevent.ts +++ b/src/models/openresponsesstreamevent.ts @@ -3,89 +3,54 @@ * @generated-id: bdd51c7b4bd0 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { - OpenAIResponsesAnnotation, - OpenAIResponsesAnnotation$inboundSchema, -} from "./openairesponsesannotation.js"; -import { - OpenAIResponsesRefusalContent, - OpenAIResponsesRefusalContent$inboundSchema, -} from "./openairesponsesrefusalcontent.js"; -import { - OpenResponsesErrorEvent, - OpenResponsesErrorEvent$inboundSchema, -} from "./openresponseserrorevent.js"; -import { - OpenResponsesImageGenCallCompleted, - OpenResponsesImageGenCallCompleted$inboundSchema, -} from "./openresponsesimagegencallcompleted.js"; -import { - OpenResponsesImageGenCallGenerating, - OpenResponsesImageGenCallGenerating$inboundSchema, -} from "./openresponsesimagegencallgenerating.js"; -import { - OpenResponsesImageGenCallInProgress, - OpenResponsesImageGenCallInProgress$inboundSchema, -} from "./openresponsesimagegencallinprogress.js"; -import { - OpenResponsesImageGenCallPartialImage, - OpenResponsesImageGenCallPartialImage$inboundSchema, -} from "./openresponsesimagegencallpartialimage.js"; -import { - OpenResponsesLogProbs, - OpenResponsesLogProbs$inboundSchema, -} from "./openresponseslogprobs.js"; -import { - OpenResponsesNonStreamingResponse, - OpenResponsesNonStreamingResponse$inboundSchema, -} from "./openresponsesnonstreamingresponse.js"; -import { - OpenResponsesReasoningDeltaEvent, - OpenResponsesReasoningDeltaEvent$inboundSchema, -} from "./openresponsesreasoningdeltaevent.js"; -import { - OpenResponsesReasoningDoneEvent, - OpenResponsesReasoningDoneEvent$inboundSchema, -} from "./openresponsesreasoningdoneevent.js"; -import { - OpenResponsesReasoningSummaryPartAddedEvent, - OpenResponsesReasoningSummaryPartAddedEvent$inboundSchema, -} from "./openresponsesreasoningsummarypartaddedevent.js"; -import { - OpenResponsesReasoningSummaryTextDeltaEvent, - OpenResponsesReasoningSummaryTextDeltaEvent$inboundSchema, -} from "./openresponsesreasoningsummarytextdeltaevent.js"; -import { - OpenResponsesReasoningSummaryTextDoneEvent, - OpenResponsesReasoningSummaryTextDoneEvent$inboundSchema, -} from "./openresponsesreasoningsummarytextdoneevent.js"; -import { - ReasoningSummaryText, - ReasoningSummaryText$inboundSchema, -} from "./reasoningsummarytext.js"; -import { - ReasoningTextContent, - ReasoningTextContent$inboundSchema, -} from "./reasoningtextcontent.js"; -import { - ResponseOutputText, - ResponseOutputText$inboundSchema, -} from "./responseoutputtext.js"; -import { - ResponsesOutputItem, - ResponsesOutputItem$inboundSchema, -} from "./responsesoutputitem.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { OpenAIResponsesAnnotation } from './openairesponsesannotation.js'; +import type { OpenAIResponsesRefusalContent } from './openairesponsesrefusalcontent.js'; +import type { OpenResponsesErrorEvent } from './openresponseserrorevent.js'; +import type { OpenResponsesImageGenCallCompleted } from './openresponsesimagegencallcompleted.js'; +import type { OpenResponsesImageGenCallGenerating } from './openresponsesimagegencallgenerating.js'; +import type { OpenResponsesImageGenCallInProgress } from './openresponsesimagegencallinprogress.js'; +import type { OpenResponsesImageGenCallPartialImage } from './openresponsesimagegencallpartialimage.js'; +import type { OpenResponsesLogProbs } from './openresponseslogprobs.js'; +import type { OpenResponsesNonStreamingResponse } from './openresponsesnonstreamingresponse.js'; +import type { OpenResponsesReasoningDeltaEvent } from './openresponsesreasoningdeltaevent.js'; +import type { OpenResponsesReasoningDoneEvent } from './openresponsesreasoningdoneevent.js'; +import type { OpenResponsesReasoningSummaryPartAddedEvent } from './openresponsesreasoningsummarypartaddedevent.js'; +import type { OpenResponsesReasoningSummaryTextDeltaEvent } from './openresponsesreasoningsummarytextdeltaevent.js'; +import type { OpenResponsesReasoningSummaryTextDoneEvent } from './openresponsesreasoningsummarytextdoneevent.js'; +import type { ReasoningSummaryText } from './reasoningsummarytext.js'; +import type { ReasoningTextContent } from './reasoningtextcontent.js'; +import type { ResponseOutputText } from './responseoutputtext.js'; +import type { ResponsesOutputItem } from './responsesoutputitem.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { OpenAIResponsesAnnotation$inboundSchema } from './openairesponsesannotation.js'; +import { OpenAIResponsesRefusalContent$inboundSchema } from './openairesponsesrefusalcontent.js'; +import { OpenResponsesErrorEvent$inboundSchema } from './openresponseserrorevent.js'; +import { OpenResponsesImageGenCallCompleted$inboundSchema } from './openresponsesimagegencallcompleted.js'; +import { OpenResponsesImageGenCallGenerating$inboundSchema } from './openresponsesimagegencallgenerating.js'; +import { OpenResponsesImageGenCallInProgress$inboundSchema } from './openresponsesimagegencallinprogress.js'; +import { OpenResponsesImageGenCallPartialImage$inboundSchema } from './openresponsesimagegencallpartialimage.js'; +import { OpenResponsesLogProbs$inboundSchema } from './openresponseslogprobs.js'; +import { OpenResponsesNonStreamingResponse$inboundSchema } from './openresponsesnonstreamingresponse.js'; +import { OpenResponsesReasoningDeltaEvent$inboundSchema } from './openresponsesreasoningdeltaevent.js'; +import { OpenResponsesReasoningDoneEvent$inboundSchema } from './openresponsesreasoningdoneevent.js'; +import { OpenResponsesReasoningSummaryPartAddedEvent$inboundSchema } from './openresponsesreasoningsummarypartaddedevent.js'; +import { OpenResponsesReasoningSummaryTextDeltaEvent$inboundSchema } from './openresponsesreasoningsummarytextdeltaevent.js'; +import { OpenResponsesReasoningSummaryTextDoneEvent$inboundSchema } from './openresponsesreasoningsummarytextdoneevent.js'; +import { ReasoningSummaryText$inboundSchema } from './reasoningsummarytext.js'; +import { ReasoningTextContent$inboundSchema } from './reasoningtextcontent.js'; +import { ResponseOutputText$inboundSchema } from './responseoutputtext.js'; +import { ResponsesOutputItem$inboundSchema } from './responsesoutputitem.js'; /** * Event emitted when a reasoning summary part is complete */ export type OpenResponsesStreamEventResponseReasoningSummaryPartDone = { - type: "response.reasoning_summary_part.done"; + type: 'response.reasoning_summary_part.done'; outputIndex: number; itemId: string; summaryIndex: number; @@ -97,7 +62,7 @@ export type OpenResponsesStreamEventResponseReasoningSummaryPartDone = { * Event emitted when function call arguments streaming is complete */ export type OpenResponsesStreamEventResponseFunctionCallArgumentsDone = { - type: "response.function_call_arguments.done"; + type: 'response.function_call_arguments.done'; itemId: string; outputIndex: number; name: string; @@ -109,7 +74,7 @@ export type OpenResponsesStreamEventResponseFunctionCallArgumentsDone = { * Event emitted when function call arguments are being streamed */ export type OpenResponsesStreamEventResponseFunctionCallArgumentsDelta = { - type: "response.function_call_arguments.delta"; + type: 'response.function_call_arguments.delta'; itemId: string; outputIndex: number; delta: string; @@ -120,7 +85,7 @@ export type OpenResponsesStreamEventResponseFunctionCallArgumentsDelta = { * Event emitted when a text annotation is added to output */ export type OpenResponsesStreamEventResponseOutputTextAnnotationAdded = { - type: "response.output_text.annotation.added"; + type: 'response.output_text.annotation.added'; outputIndex: number; itemId: string; contentIndex: number; @@ -133,7 +98,7 @@ export type OpenResponsesStreamEventResponseOutputTextAnnotationAdded = { * Event emitted when refusal streaming is complete */ export type OpenResponsesStreamEventResponseRefusalDone = { - type: "response.refusal.done"; + type: 'response.refusal.done'; outputIndex: number; itemId: string; contentIndex: number; @@ -145,7 +110,7 @@ export type OpenResponsesStreamEventResponseRefusalDone = { * Event emitted when a refusal delta is streamed */ export type OpenResponsesStreamEventResponseRefusalDelta = { - type: "response.refusal.delta"; + type: 'response.refusal.delta'; outputIndex: number; itemId: string; contentIndex: number; @@ -157,7 +122,7 @@ export type OpenResponsesStreamEventResponseRefusalDelta = { * Event emitted when text streaming is complete */ export type OpenResponsesStreamEventResponseOutputTextDone = { - type: "response.output_text.done"; + type: 'response.output_text.done'; outputIndex: number; itemId: string; contentIndex: number; @@ -170,7 +135,7 @@ export type OpenResponsesStreamEventResponseOutputTextDone = { * Event emitted when a text delta is streamed */ export type OpenResponsesStreamEventResponseOutputTextDelta = { - type: "response.output_text.delta"; + type: 'response.output_text.delta'; logprobs: Array; outputIndex: number; itemId: string; @@ -181,40 +146,48 @@ export type OpenResponsesStreamEventResponseOutputTextDelta = { export type Part2 = | ResponseOutputText - | (ReasoningTextContent & { type: "reasoning_text" }) + | (ReasoningTextContent & { + type: 'reasoning_text'; + }) | OpenAIResponsesRefusalContent; /** * Event emitted when a content part is complete */ export type OpenResponsesStreamEventResponseContentPartDone = { - type: "response.content_part.done"; + type: 'response.content_part.done'; outputIndex: number; itemId: string; contentIndex: number; part: | ResponseOutputText - | (ReasoningTextContent & { type: "reasoning_text" }) + | (ReasoningTextContent & { + type: 'reasoning_text'; + }) | OpenAIResponsesRefusalContent; sequenceNumber: number; }; export type Part1 = | ResponseOutputText - | (ReasoningTextContent & { type: "reasoning_text" }) + | (ReasoningTextContent & { + type: 'reasoning_text'; + }) | OpenAIResponsesRefusalContent; /** * Event emitted when a new content part is added to an output item */ export type OpenResponsesStreamEventResponseContentPartAdded = { - type: "response.content_part.added"; + type: 'response.content_part.added'; outputIndex: number; itemId: string; contentIndex: number; part: | ResponseOutputText - | (ReasoningTextContent & { type: "reasoning_text" }) + | (ReasoningTextContent & { + type: 'reasoning_text'; + }) | OpenAIResponsesRefusalContent; sequenceNumber: number; }; @@ -223,7 +196,7 @@ export type OpenResponsesStreamEventResponseContentPartAdded = { * Event emitted when an output item is complete */ export type OpenResponsesStreamEventResponseOutputItemDone = { - type: "response.output_item.done"; + type: 'response.output_item.done'; outputIndex: number; /** * An output item from the response @@ -236,7 +209,7 @@ export type OpenResponsesStreamEventResponseOutputItemDone = { * Event emitted when a new output item is added to the response */ export type OpenResponsesStreamEventResponseOutputItemAdded = { - type: "response.output_item.added"; + type: 'response.output_item.added'; outputIndex: number; /** * An output item from the response @@ -249,7 +222,7 @@ export type OpenResponsesStreamEventResponseOutputItemAdded = { * Event emitted when a response has failed */ export type OpenResponsesStreamEventResponseFailed = { - type: "response.failed"; + type: 'response.failed'; /** * Complete non-streaming response from the Responses API */ @@ -261,7 +234,7 @@ export type OpenResponsesStreamEventResponseFailed = { * Event emitted when a response is incomplete */ export type OpenResponsesStreamEventResponseIncomplete = { - type: "response.incomplete"; + type: 'response.incomplete'; /** * Complete non-streaming response from the Responses API */ @@ -273,7 +246,7 @@ export type OpenResponsesStreamEventResponseIncomplete = { * Event emitted when a response has completed successfully */ export type OpenResponsesStreamEventResponseCompleted = { - type: "response.completed"; + type: 'response.completed'; /** * Complete non-streaming response from the Responses API */ @@ -285,7 +258,7 @@ export type OpenResponsesStreamEventResponseCompleted = { * Event emitted when a response is in progress */ export type OpenResponsesStreamEventResponseInProgress = { - type: "response.in_progress"; + type: 'response.in_progress'; /** * Complete non-streaming response from the Responses API */ @@ -297,7 +270,7 @@ export type OpenResponsesStreamEventResponseInProgress = { * Event emitted when a response is created */ export type OpenResponsesStreamEventResponseCreated = { - type: "response.created"; + type: 'response.created'; /** * Complete non-streaming response from the Responses API */ @@ -338,283 +311,262 @@ export type OpenResponsesStreamEvent = | OpenResponsesImageGenCallCompleted; /** @internal */ -export const OpenResponsesStreamEventResponseReasoningSummaryPartDone$inboundSchema: - z.ZodType = - z.object({ - type: z.literal("response.reasoning_summary_part.done"), - output_index: z.number(), - item_id: z.string(), - summary_index: z.number(), - part: ReasoningSummaryText$inboundSchema, - sequence_number: z.number(), - }).transform((v) => { - return remap$(v, { - "output_index": "outputIndex", - "item_id": "itemId", - "summary_index": "summaryIndex", - "sequence_number": "sequenceNumber", - }); +export const OpenResponsesStreamEventResponseReasoningSummaryPartDone$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseReasoningSummaryPartDone, + unknown +> = z + .object({ + type: z.literal('response.reasoning_summary_part.done'), + output_index: z.number(), + item_id: z.string(), + summary_index: z.number(), + part: ReasoningSummaryText$inboundSchema, + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + output_index: 'outputIndex', + item_id: 'itemId', + summary_index: 'summaryIndex', + sequence_number: 'sequenceNumber', }); + }); export function openResponsesStreamEventResponseReasoningSummaryPartDoneFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseReasoningSummaryPartDone, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, (x) => - OpenResponsesStreamEventResponseReasoningSummaryPartDone$inboundSchema - .parse(JSON.parse(x)), + OpenResponsesStreamEventResponseReasoningSummaryPartDone$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseReasoningSummaryPartDone' from JSON`, ); } /** @internal */ -export const OpenResponsesStreamEventResponseFunctionCallArgumentsDone$inboundSchema: - z.ZodType< - OpenResponsesStreamEventResponseFunctionCallArgumentsDone, - unknown - > = z.object({ - type: z.literal("response.function_call_arguments.done"), +export const OpenResponsesStreamEventResponseFunctionCallArgumentsDone$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseFunctionCallArgumentsDone, + unknown +> = z + .object({ + type: z.literal('response.function_call_arguments.done'), item_id: z.string(), output_index: z.number(), name: z.string(), arguments: z.string(), sequence_number: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "item_id": "itemId", - "output_index": "outputIndex", - "sequence_number": "sequenceNumber", + item_id: 'itemId', + output_index: 'outputIndex', + sequence_number: 'sequenceNumber', }); }); export function openResponsesStreamEventResponseFunctionCallArgumentsDoneFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseFunctionCallArgumentsDone, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, (x) => - OpenResponsesStreamEventResponseFunctionCallArgumentsDone$inboundSchema - .parse(JSON.parse(x)), + OpenResponsesStreamEventResponseFunctionCallArgumentsDone$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseFunctionCallArgumentsDone' from JSON`, ); } /** @internal */ -export const OpenResponsesStreamEventResponseFunctionCallArgumentsDelta$inboundSchema: - z.ZodType< - OpenResponsesStreamEventResponseFunctionCallArgumentsDelta, - unknown - > = z.object({ - type: z.literal("response.function_call_arguments.delta"), +export const OpenResponsesStreamEventResponseFunctionCallArgumentsDelta$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseFunctionCallArgumentsDelta, + unknown +> = z + .object({ + type: z.literal('response.function_call_arguments.delta'), item_id: z.string(), output_index: z.number(), delta: z.string(), sequence_number: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "item_id": "itemId", - "output_index": "outputIndex", - "sequence_number": "sequenceNumber", + item_id: 'itemId', + output_index: 'outputIndex', + sequence_number: 'sequenceNumber', }); }); export function openResponsesStreamEventResponseFunctionCallArgumentsDeltaFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseFunctionCallArgumentsDelta, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, (x) => - OpenResponsesStreamEventResponseFunctionCallArgumentsDelta$inboundSchema - .parse(JSON.parse(x)), + OpenResponsesStreamEventResponseFunctionCallArgumentsDelta$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseFunctionCallArgumentsDelta' from JSON`, ); } /** @internal */ -export const OpenResponsesStreamEventResponseOutputTextAnnotationAdded$inboundSchema: - z.ZodType< - OpenResponsesStreamEventResponseOutputTextAnnotationAdded, - unknown - > = z.object({ - type: z.literal("response.output_text.annotation.added"), +export const OpenResponsesStreamEventResponseOutputTextAnnotationAdded$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseOutputTextAnnotationAdded, + unknown +> = z + .object({ + type: z.literal('response.output_text.annotation.added'), output_index: z.number(), item_id: z.string(), content_index: z.number(), sequence_number: z.number(), annotation_index: z.number(), annotation: OpenAIResponsesAnnotation$inboundSchema, - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "output_index": "outputIndex", - "item_id": "itemId", - "content_index": "contentIndex", - "sequence_number": "sequenceNumber", - "annotation_index": "annotationIndex", + output_index: 'outputIndex', + item_id: 'itemId', + content_index: 'contentIndex', + sequence_number: 'sequenceNumber', + annotation_index: 'annotationIndex', }); }); export function openResponsesStreamEventResponseOutputTextAnnotationAddedFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseOutputTextAnnotationAdded, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, (x) => - OpenResponsesStreamEventResponseOutputTextAnnotationAdded$inboundSchema - .parse(JSON.parse(x)), + OpenResponsesStreamEventResponseOutputTextAnnotationAdded$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseOutputTextAnnotationAdded' from JSON`, ); } /** @internal */ -export const OpenResponsesStreamEventResponseRefusalDone$inboundSchema: - z.ZodType = z.object({ - type: z.literal("response.refusal.done"), +export const OpenResponsesStreamEventResponseRefusalDone$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseRefusalDone, + unknown +> = z + .object({ + type: z.literal('response.refusal.done'), output_index: z.number(), item_id: z.string(), content_index: z.number(), refusal: z.string(), sequence_number: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "output_index": "outputIndex", - "item_id": "itemId", - "content_index": "contentIndex", - "sequence_number": "sequenceNumber", + output_index: 'outputIndex', + item_id: 'itemId', + content_index: 'contentIndex', + sequence_number: 'sequenceNumber', }); }); export function openResponsesStreamEventResponseRefusalDoneFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseRefusalDone, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesStreamEventResponseRefusalDone$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesStreamEventResponseRefusalDone$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseRefusalDone' from JSON`, ); } /** @internal */ -export const OpenResponsesStreamEventResponseRefusalDelta$inboundSchema: - z.ZodType = z.object({ - type: z.literal("response.refusal.delta"), +export const OpenResponsesStreamEventResponseRefusalDelta$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseRefusalDelta, + unknown +> = z + .object({ + type: z.literal('response.refusal.delta'), output_index: z.number(), item_id: z.string(), content_index: z.number(), delta: z.string(), sequence_number: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "output_index": "outputIndex", - "item_id": "itemId", - "content_index": "contentIndex", - "sequence_number": "sequenceNumber", + output_index: 'outputIndex', + item_id: 'itemId', + content_index: 'contentIndex', + sequence_number: 'sequenceNumber', }); }); export function openResponsesStreamEventResponseRefusalDeltaFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseRefusalDelta, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesStreamEventResponseRefusalDelta$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesStreamEventResponseRefusalDelta$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseRefusalDelta' from JSON`, ); } /** @internal */ -export const OpenResponsesStreamEventResponseOutputTextDone$inboundSchema: - z.ZodType = z.object( - { - type: z.literal("response.output_text.done"), - output_index: z.number(), - item_id: z.string(), - content_index: z.number(), - text: z.string(), - sequence_number: z.number(), - logprobs: z.array(OpenResponsesLogProbs$inboundSchema), - }, - ).transform((v) => { +export const OpenResponsesStreamEventResponseOutputTextDone$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseOutputTextDone, + unknown +> = z + .object({ + type: z.literal('response.output_text.done'), + output_index: z.number(), + item_id: z.string(), + content_index: z.number(), + text: z.string(), + sequence_number: z.number(), + logprobs: z.array(OpenResponsesLogProbs$inboundSchema), + }) + .transform((v) => { return remap$(v, { - "output_index": "outputIndex", - "item_id": "itemId", - "content_index": "contentIndex", - "sequence_number": "sequenceNumber", + output_index: 'outputIndex', + item_id: 'itemId', + content_index: 'contentIndex', + sequence_number: 'sequenceNumber', }); }); export function openResponsesStreamEventResponseOutputTextDoneFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseOutputTextDone, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesStreamEventResponseOutputTextDone$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesStreamEventResponseOutputTextDone$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseOutputTextDone' from JSON`, ); } /** @internal */ -export const OpenResponsesStreamEventResponseOutputTextDelta$inboundSchema: - z.ZodType = z - .object({ - type: z.literal("response.output_text.delta"), - logprobs: z.array(OpenResponsesLogProbs$inboundSchema), - output_index: z.number(), - item_id: z.string(), - content_index: z.number(), - delta: z.string(), - sequence_number: z.number(), - }).transform((v) => { - return remap$(v, { - "output_index": "outputIndex", - "item_id": "itemId", - "content_index": "contentIndex", - "sequence_number": "sequenceNumber", - }); +export const OpenResponsesStreamEventResponseOutputTextDelta$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseOutputTextDelta, + unknown +> = z + .object({ + type: z.literal('response.output_text.delta'), + logprobs: z.array(OpenResponsesLogProbs$inboundSchema), + output_index: z.number(), + item_id: z.string(), + content_index: z.number(), + delta: z.string(), + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + output_index: 'outputIndex', + item_id: 'itemId', + content_index: 'contentIndex', + sequence_number: 'sequenceNumber', }); + }); export function openResponsesStreamEventResponseOutputTextDeltaFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseOutputTextDelta, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesStreamEventResponseOutputTextDelta$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesStreamEventResponseOutputTextDelta$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseOutputTextDelta' from JSON`, ); } @@ -623,14 +575,14 @@ export function openResponsesStreamEventResponseOutputTextDeltaFromJSON( export const Part2$inboundSchema: z.ZodType = z.union([ ResponseOutputText$inboundSchema, ReasoningTextContent$inboundSchema.and( - z.object({ type: z.literal("reasoning_text") }), + z.object({ + type: z.literal('reasoning_text'), + }), ), OpenAIResponsesRefusalContent$inboundSchema, ]); -export function part2FromJSON( - jsonString: string, -): SafeParseResult { +export function part2FromJSON(jsonString: string): SafeParseResult { return safeParse( jsonString, (x) => Part2$inboundSchema.parse(JSON.parse(x)), @@ -639,42 +591,41 @@ export function part2FromJSON( } /** @internal */ -export const OpenResponsesStreamEventResponseContentPartDone$inboundSchema: - z.ZodType = z - .object({ - type: z.literal("response.content_part.done"), - output_index: z.number(), - item_id: z.string(), - content_index: z.number(), - part: z.union([ - ResponseOutputText$inboundSchema, - ReasoningTextContent$inboundSchema.and( - z.object({ type: z.literal("reasoning_text") }), - ), - OpenAIResponsesRefusalContent$inboundSchema, - ]), - sequence_number: z.number(), - }).transform((v) => { - return remap$(v, { - "output_index": "outputIndex", - "item_id": "itemId", - "content_index": "contentIndex", - "sequence_number": "sequenceNumber", - }); +export const OpenResponsesStreamEventResponseContentPartDone$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseContentPartDone, + unknown +> = z + .object({ + type: z.literal('response.content_part.done'), + output_index: z.number(), + item_id: z.string(), + content_index: z.number(), + part: z.union([ + ResponseOutputText$inboundSchema, + ReasoningTextContent$inboundSchema.and( + z.object({ + type: z.literal('reasoning_text'), + }), + ), + OpenAIResponsesRefusalContent$inboundSchema, + ]), + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + output_index: 'outputIndex', + item_id: 'itemId', + content_index: 'contentIndex', + sequence_number: 'sequenceNumber', }); + }); export function openResponsesStreamEventResponseContentPartDoneFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseContentPartDone, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesStreamEventResponseContentPartDone$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesStreamEventResponseContentPartDone$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseContentPartDone' from JSON`, ); } @@ -683,14 +634,14 @@ export function openResponsesStreamEventResponseContentPartDoneFromJSON( export const Part1$inboundSchema: z.ZodType = z.union([ ResponseOutputText$inboundSchema, ReasoningTextContent$inboundSchema.and( - z.object({ type: z.literal("reasoning_text") }), + z.object({ + type: z.literal('reasoning_text'), + }), ), OpenAIResponsesRefusalContent$inboundSchema, ]); -export function part1FromJSON( - jsonString: string, -): SafeParseResult { +export function part1FromJSON(jsonString: string): SafeParseResult { return safeParse( jsonString, (x) => Part1$inboundSchema.parse(JSON.parse(x)), @@ -699,105 +650,97 @@ export function part1FromJSON( } /** @internal */ -export const OpenResponsesStreamEventResponseContentPartAdded$inboundSchema: - z.ZodType = z - .object({ - type: z.literal("response.content_part.added"), - output_index: z.number(), - item_id: z.string(), - content_index: z.number(), - part: z.union([ - ResponseOutputText$inboundSchema, - ReasoningTextContent$inboundSchema.and( - z.object({ type: z.literal("reasoning_text") }), - ), - OpenAIResponsesRefusalContent$inboundSchema, - ]), - sequence_number: z.number(), - }).transform((v) => { - return remap$(v, { - "output_index": "outputIndex", - "item_id": "itemId", - "content_index": "contentIndex", - "sequence_number": "sequenceNumber", - }); +export const OpenResponsesStreamEventResponseContentPartAdded$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseContentPartAdded, + unknown +> = z + .object({ + type: z.literal('response.content_part.added'), + output_index: z.number(), + item_id: z.string(), + content_index: z.number(), + part: z.union([ + ResponseOutputText$inboundSchema, + ReasoningTextContent$inboundSchema.and( + z.object({ + type: z.literal('reasoning_text'), + }), + ), + OpenAIResponsesRefusalContent$inboundSchema, + ]), + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + output_index: 'outputIndex', + item_id: 'itemId', + content_index: 'contentIndex', + sequence_number: 'sequenceNumber', }); + }); export function openResponsesStreamEventResponseContentPartAddedFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseContentPartAdded, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesStreamEventResponseContentPartAdded$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesStreamEventResponseContentPartAdded$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseContentPartAdded' from JSON`, ); } /** @internal */ -export const OpenResponsesStreamEventResponseOutputItemDone$inboundSchema: - z.ZodType = z.object( - { - type: z.literal("response.output_item.done"), - output_index: z.number(), - item: ResponsesOutputItem$inboundSchema, - sequence_number: z.number(), - }, - ).transform((v) => { +export const OpenResponsesStreamEventResponseOutputItemDone$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseOutputItemDone, + unknown +> = z + .object({ + type: z.literal('response.output_item.done'), + output_index: z.number(), + item: ResponsesOutputItem$inboundSchema, + sequence_number: z.number(), + }) + .transform((v) => { return remap$(v, { - "output_index": "outputIndex", - "sequence_number": "sequenceNumber", + output_index: 'outputIndex', + sequence_number: 'sequenceNumber', }); }); export function openResponsesStreamEventResponseOutputItemDoneFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseOutputItemDone, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesStreamEventResponseOutputItemDone$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesStreamEventResponseOutputItemDone$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseOutputItemDone' from JSON`, ); } /** @internal */ -export const OpenResponsesStreamEventResponseOutputItemAdded$inboundSchema: - z.ZodType = z - .object({ - type: z.literal("response.output_item.added"), - output_index: z.number(), - item: ResponsesOutputItem$inboundSchema, - sequence_number: z.number(), - }).transform((v) => { - return remap$(v, { - "output_index": "outputIndex", - "sequence_number": "sequenceNumber", - }); +export const OpenResponsesStreamEventResponseOutputItemAdded$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseOutputItemAdded, + unknown +> = z + .object({ + type: z.literal('response.output_item.added'), + output_index: z.number(), + item: ResponsesOutputItem$inboundSchema, + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + output_index: 'outputIndex', + sequence_number: 'sequenceNumber', }); + }); export function openResponsesStreamEventResponseOutputItemAddedFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseOutputItemAdded, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesStreamEventResponseOutputItemAdded$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesStreamEventResponseOutputItemAdded$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseOutputItemAdded' from JSON`, ); } @@ -806,51 +749,50 @@ export function openResponsesStreamEventResponseOutputItemAddedFromJSON( export const OpenResponsesStreamEventResponseFailed$inboundSchema: z.ZodType< OpenResponsesStreamEventResponseFailed, unknown -> = z.object({ - type: z.literal("response.failed"), - response: OpenResponsesNonStreamingResponse$inboundSchema, - sequence_number: z.number(), -}).transform((v) => { - return remap$(v, { - "sequence_number": "sequenceNumber", +> = z + .object({ + type: z.literal('response.failed'), + response: OpenResponsesNonStreamingResponse$inboundSchema, + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + sequence_number: 'sequenceNumber', + }); }); -}); export function openResponsesStreamEventResponseFailedFromJSON( jsonString: string, ): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesStreamEventResponseFailed$inboundSchema.parse(JSON.parse(x)), + (x) => OpenResponsesStreamEventResponseFailed$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseFailed' from JSON`, ); } /** @internal */ -export const OpenResponsesStreamEventResponseIncomplete$inboundSchema: - z.ZodType = z.object({ - type: z.literal("response.incomplete"), +export const OpenResponsesStreamEventResponseIncomplete$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseIncomplete, + unknown +> = z + .object({ + type: z.literal('response.incomplete'), response: OpenResponsesNonStreamingResponse$inboundSchema, sequence_number: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "sequence_number": "sequenceNumber", + sequence_number: 'sequenceNumber', }); }); export function openResponsesStreamEventResponseIncompleteFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseIncomplete, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesStreamEventResponseIncomplete$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesStreamEventResponseIncomplete$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseIncomplete' from JSON`, ); } @@ -859,56 +801,50 @@ export function openResponsesStreamEventResponseIncompleteFromJSON( export const OpenResponsesStreamEventResponseCompleted$inboundSchema: z.ZodType< OpenResponsesStreamEventResponseCompleted, unknown -> = z.object({ - type: z.literal("response.completed"), - response: OpenResponsesNonStreamingResponse$inboundSchema, - sequence_number: z.number(), -}).transform((v) => { - return remap$(v, { - "sequence_number": "sequenceNumber", +> = z + .object({ + type: z.literal('response.completed'), + response: OpenResponsesNonStreamingResponse$inboundSchema, + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + sequence_number: 'sequenceNumber', + }); }); -}); export function openResponsesStreamEventResponseCompletedFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseCompleted, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesStreamEventResponseCompleted$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesStreamEventResponseCompleted$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseCompleted' from JSON`, ); } /** @internal */ -export const OpenResponsesStreamEventResponseInProgress$inboundSchema: - z.ZodType = z.object({ - type: z.literal("response.in_progress"), +export const OpenResponsesStreamEventResponseInProgress$inboundSchema: z.ZodType< + OpenResponsesStreamEventResponseInProgress, + unknown +> = z + .object({ + type: z.literal('response.in_progress'), response: OpenResponsesNonStreamingResponse$inboundSchema, sequence_number: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "sequence_number": "sequenceNumber", + sequence_number: 'sequenceNumber', }); }); export function openResponsesStreamEventResponseInProgressFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseInProgress, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesStreamEventResponseInProgress$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesStreamEventResponseInProgress$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseInProgress' from JSON`, ); } @@ -917,73 +853,59 @@ export function openResponsesStreamEventResponseInProgressFromJSON( export const OpenResponsesStreamEventResponseCreated$inboundSchema: z.ZodType< OpenResponsesStreamEventResponseCreated, unknown -> = z.object({ - type: z.literal("response.created"), - response: OpenResponsesNonStreamingResponse$inboundSchema, - sequence_number: z.number(), -}).transform((v) => { - return remap$(v, { - "sequence_number": "sequenceNumber", +> = z + .object({ + type: z.literal('response.created'), + response: OpenResponsesNonStreamingResponse$inboundSchema, + sequence_number: z.number(), + }) + .transform((v) => { + return remap$(v, { + sequence_number: 'sequenceNumber', + }); }); -}); export function openResponsesStreamEventResponseCreatedFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesStreamEventResponseCreated, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesStreamEventResponseCreated$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesStreamEventResponseCreated$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesStreamEventResponseCreated' from JSON`, ); } /** @internal */ -export const OpenResponsesStreamEvent$inboundSchema: z.ZodType< - OpenResponsesStreamEvent, - unknown -> = z.union([ - z.lazy(() => OpenResponsesStreamEventResponseCreated$inboundSchema), - z.lazy(() => OpenResponsesStreamEventResponseInProgress$inboundSchema), - z.lazy(() => OpenResponsesStreamEventResponseCompleted$inboundSchema), - z.lazy(() => OpenResponsesStreamEventResponseIncomplete$inboundSchema), - z.lazy(() => OpenResponsesStreamEventResponseFailed$inboundSchema), - OpenResponsesErrorEvent$inboundSchema, - z.lazy(() => OpenResponsesStreamEventResponseOutputItemAdded$inboundSchema), - z.lazy(() => OpenResponsesStreamEventResponseOutputItemDone$inboundSchema), - z.lazy(() => OpenResponsesStreamEventResponseContentPartAdded$inboundSchema), - z.lazy(() => OpenResponsesStreamEventResponseContentPartDone$inboundSchema), - z.lazy(() => OpenResponsesStreamEventResponseOutputTextDelta$inboundSchema), - z.lazy(() => OpenResponsesStreamEventResponseOutputTextDone$inboundSchema), - z.lazy(() => OpenResponsesStreamEventResponseRefusalDelta$inboundSchema), - z.lazy(() => OpenResponsesStreamEventResponseRefusalDone$inboundSchema), - z.lazy(() => - OpenResponsesStreamEventResponseOutputTextAnnotationAdded$inboundSchema - ), - z.lazy(() => - OpenResponsesStreamEventResponseFunctionCallArgumentsDelta$inboundSchema - ), - z.lazy(() => - OpenResponsesStreamEventResponseFunctionCallArgumentsDone$inboundSchema - ), - OpenResponsesReasoningDeltaEvent$inboundSchema, - OpenResponsesReasoningDoneEvent$inboundSchema, - OpenResponsesReasoningSummaryPartAddedEvent$inboundSchema, - z.lazy(() => - OpenResponsesStreamEventResponseReasoningSummaryPartDone$inboundSchema - ), - OpenResponsesReasoningSummaryTextDeltaEvent$inboundSchema, - OpenResponsesReasoningSummaryTextDoneEvent$inboundSchema, - OpenResponsesImageGenCallInProgress$inboundSchema, - OpenResponsesImageGenCallGenerating$inboundSchema, - OpenResponsesImageGenCallPartialImage$inboundSchema, - OpenResponsesImageGenCallCompleted$inboundSchema, -]); +export const OpenResponsesStreamEvent$inboundSchema: z.ZodType = + z.union([ + z.lazy(() => OpenResponsesStreamEventResponseCreated$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseInProgress$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseCompleted$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseIncomplete$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseFailed$inboundSchema), + OpenResponsesErrorEvent$inboundSchema, + z.lazy(() => OpenResponsesStreamEventResponseOutputItemAdded$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseOutputItemDone$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseContentPartAdded$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseContentPartDone$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseOutputTextDelta$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseOutputTextDone$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseRefusalDelta$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseRefusalDone$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseOutputTextAnnotationAdded$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseFunctionCallArgumentsDelta$inboundSchema), + z.lazy(() => OpenResponsesStreamEventResponseFunctionCallArgumentsDone$inboundSchema), + OpenResponsesReasoningDeltaEvent$inboundSchema, + OpenResponsesReasoningDoneEvent$inboundSchema, + OpenResponsesReasoningSummaryPartAddedEvent$inboundSchema, + z.lazy(() => OpenResponsesStreamEventResponseReasoningSummaryPartDone$inboundSchema), + OpenResponsesReasoningSummaryTextDeltaEvent$inboundSchema, + OpenResponsesReasoningSummaryTextDoneEvent$inboundSchema, + OpenResponsesImageGenCallInProgress$inboundSchema, + OpenResponsesImageGenCallGenerating$inboundSchema, + OpenResponsesImageGenCallPartialImage$inboundSchema, + OpenResponsesImageGenCallCompleted$inboundSchema, + ]); export function openResponsesStreamEventFromJSON( jsonString: string, diff --git a/src/models/openresponsestoplogprobs.ts b/src/models/openresponsestoplogprobs.ts index 12a5897e..1661e004 100644 --- a/src/models/openresponsestoplogprobs.ts +++ b/src/models/openresponsestoplogprobs.ts @@ -3,10 +3,11 @@ * @generated-id: 9deb0a6359d1 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Alternative token with its log probability @@ -17,13 +18,11 @@ export type OpenResponsesTopLogprobs = { }; /** @internal */ -export const OpenResponsesTopLogprobs$inboundSchema: z.ZodType< - OpenResponsesTopLogprobs, - unknown -> = z.object({ - token: z.string().optional(), - logprob: z.number().optional(), -}); +export const OpenResponsesTopLogprobs$inboundSchema: z.ZodType = + z.object({ + token: z.string().optional(), + logprob: z.number().optional(), + }); export function openResponsesTopLogprobsFromJSON( jsonString: string, diff --git a/src/models/openresponsesusage.ts b/src/models/openresponsesusage.ts index 736c9789..facfc7de 100644 --- a/src/models/openresponsesusage.ts +++ b/src/models/openresponsesusage.ts @@ -3,11 +3,12 @@ * @generated-id: 806527de3bfd */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; export type InputTokensDetails = { cachedTokens: number; @@ -44,16 +45,15 @@ export type OpenResponsesUsage = { }; /** @internal */ -export const InputTokensDetails$inboundSchema: z.ZodType< - InputTokensDetails, - unknown -> = z.object({ - cached_tokens: z.number(), -}).transform((v) => { - return remap$(v, { - "cached_tokens": "cachedTokens", +export const InputTokensDetails$inboundSchema: z.ZodType = z + .object({ + cached_tokens: z.number(), + }) + .transform((v) => { + return remap$(v, { + cached_tokens: 'cachedTokens', + }); }); -}); export function inputTokensDetailsFromJSON( jsonString: string, @@ -66,16 +66,15 @@ export function inputTokensDetailsFromJSON( } /** @internal */ -export const OutputTokensDetails$inboundSchema: z.ZodType< - OutputTokensDetails, - unknown -> = z.object({ - reasoning_tokens: z.number(), -}).transform((v) => { - return remap$(v, { - "reasoning_tokens": "reasoningTokens", +export const OutputTokensDetails$inboundSchema: z.ZodType = z + .object({ + reasoning_tokens: z.number(), + }) + .transform((v) => { + return remap$(v, { + reasoning_tokens: 'reasoningTokens', + }); }); -}); export function outputTokensDetailsFromJSON( jsonString: string, @@ -93,11 +92,12 @@ export const CostDetails$inboundSchema: z.ZodType = z upstream_inference_cost: z.nullable(z.number()).optional(), upstream_inference_input_cost: z.number(), upstream_inference_output_cost: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "upstream_inference_cost": "upstreamInferenceCost", - "upstream_inference_input_cost": "upstreamInferenceInputCost", - "upstream_inference_output_cost": "upstreamInferenceOutputCost", + upstream_inference_cost: 'upstreamInferenceCost', + upstream_inference_input_cost: 'upstreamInferenceInputCost', + upstream_inference_output_cost: 'upstreamInferenceOutputCost', }); }); @@ -112,29 +112,28 @@ export function costDetailsFromJSON( } /** @internal */ -export const OpenResponsesUsage$inboundSchema: z.ZodType< - OpenResponsesUsage, - unknown -> = z.object({ - input_tokens: z.number(), - input_tokens_details: z.lazy(() => InputTokensDetails$inboundSchema), - output_tokens: z.number(), - output_tokens_details: z.lazy(() => OutputTokensDetails$inboundSchema), - total_tokens: z.number(), - cost: z.nullable(z.number()).optional(), - is_byok: z.boolean().optional(), - cost_details: z.lazy(() => CostDetails$inboundSchema).optional(), -}).transform((v) => { - return remap$(v, { - "input_tokens": "inputTokens", - "input_tokens_details": "inputTokensDetails", - "output_tokens": "outputTokens", - "output_tokens_details": "outputTokensDetails", - "total_tokens": "totalTokens", - "is_byok": "isByok", - "cost_details": "costDetails", +export const OpenResponsesUsage$inboundSchema: z.ZodType = z + .object({ + input_tokens: z.number(), + input_tokens_details: z.lazy(() => InputTokensDetails$inboundSchema), + output_tokens: z.number(), + output_tokens_details: z.lazy(() => OutputTokensDetails$inboundSchema), + total_tokens: z.number(), + cost: z.nullable(z.number()).optional(), + is_byok: z.boolean().optional(), + cost_details: z.lazy(() => CostDetails$inboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + input_tokens: 'inputTokens', + input_tokens_details: 'inputTokensDetails', + output_tokens: 'outputTokens', + output_tokens_details: 'outputTokensDetails', + total_tokens: 'totalTokens', + is_byok: 'isByok', + cost_details: 'costDetails', + }); }); -}); export function openResponsesUsageFromJSON( jsonString: string, diff --git a/src/models/openresponseswebsearch20250826tool.ts b/src/models/openresponseswebsearch20250826tool.ts index a8ec3ef2..0f05fbc7 100644 --- a/src/models/openresponseswebsearch20250826tool.ts +++ b/src/models/openresponseswebsearch20250826tool.ts @@ -3,22 +3,25 @@ * @generated-id: 7650f38c7184 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { ResponsesSearchContextSize } from './responsessearchcontextsize.js'; +import type { + ResponsesWebSearchUserLocation, + ResponsesWebSearchUserLocation$Outbound, +} from './responseswebsearchuserlocation.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; import { - ResponsesSearchContextSize, ResponsesSearchContextSize$inboundSchema, ResponsesSearchContextSize$outboundSchema, -} from "./responsessearchcontextsize.js"; +} from './responsessearchcontextsize.js'; import { - ResponsesWebSearchUserLocation, ResponsesWebSearchUserLocation$inboundSchema, - ResponsesWebSearchUserLocation$Outbound, ResponsesWebSearchUserLocation$outboundSchema, -} from "./responseswebsearchuserlocation.js"; +} from './responseswebsearchuserlocation.js'; export type OpenResponsesWebSearch20250826ToolFilters = { allowedDomains?: Array | null | undefined; @@ -28,7 +31,7 @@ export type OpenResponsesWebSearch20250826ToolFilters = { * Web search tool configuration (2025-08-26 version) */ export type OpenResponsesWebSearch20250826Tool = { - type: "web_search_2025_08_26"; + type: 'web_search_2025_08_26'; filters?: OpenResponsesWebSearch20250826ToolFilters | null | undefined; /** * Size of the search context for web search tools @@ -44,34 +47,36 @@ export type OpenResponsesWebSearch20250826Tool = { export const OpenResponsesWebSearch20250826ToolFilters$inboundSchema: z.ZodType< OpenResponsesWebSearch20250826ToolFilters, unknown -> = z.object({ - allowed_domains: z.nullable(z.array(z.string())).optional(), -}).transform((v) => { - return remap$(v, { - "allowed_domains": "allowedDomains", +> = z + .object({ + allowed_domains: z.nullable(z.array(z.string())).optional(), + }) + .transform((v) => { + return remap$(v, { + allowed_domains: 'allowedDomains', + }); }); -}); /** @internal */ export type OpenResponsesWebSearch20250826ToolFilters$Outbound = { allowed_domains?: Array | null | undefined; }; /** @internal */ -export const OpenResponsesWebSearch20250826ToolFilters$outboundSchema: - z.ZodType< - OpenResponsesWebSearch20250826ToolFilters$Outbound, - OpenResponsesWebSearch20250826ToolFilters - > = z.object({ +export const OpenResponsesWebSearch20250826ToolFilters$outboundSchema: z.ZodType< + OpenResponsesWebSearch20250826ToolFilters$Outbound, + OpenResponsesWebSearch20250826ToolFilters +> = z + .object({ allowedDomains: z.nullable(z.array(z.string())).optional(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - allowedDomains: "allowed_domains", + allowedDomains: 'allowed_domains', }); }); export function openResponsesWebSearch20250826ToolFiltersToJSON( - openResponsesWebSearch20250826ToolFilters: - OpenResponsesWebSearch20250826ToolFilters, + openResponsesWebSearch20250826ToolFilters: OpenResponsesWebSearch20250826ToolFilters, ): string { return JSON.stringify( OpenResponsesWebSearch20250826ToolFilters$outboundSchema.parse( @@ -81,16 +86,10 @@ export function openResponsesWebSearch20250826ToolFiltersToJSON( } export function openResponsesWebSearch20250826ToolFiltersFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesWebSearch20250826ToolFilters, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesWebSearch20250826ToolFilters$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesWebSearch20250826ToolFilters$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesWebSearch20250826ToolFilters' from JSON`, ); } @@ -99,27 +98,25 @@ export function openResponsesWebSearch20250826ToolFiltersFromJSON( export const OpenResponsesWebSearch20250826Tool$inboundSchema: z.ZodType< OpenResponsesWebSearch20250826Tool, unknown -> = z.object({ - type: z.literal("web_search_2025_08_26"), - filters: z.nullable( - z.lazy(() => OpenResponsesWebSearch20250826ToolFilters$inboundSchema), - ).optional(), - search_context_size: ResponsesSearchContextSize$inboundSchema.optional(), - user_location: z.nullable(ResponsesWebSearchUserLocation$inboundSchema) - .optional(), -}).transform((v) => { - return remap$(v, { - "search_context_size": "searchContextSize", - "user_location": "userLocation", +> = z + .object({ + type: z.literal('web_search_2025_08_26'), + filters: z + .nullable(z.lazy(() => OpenResponsesWebSearch20250826ToolFilters$inboundSchema)) + .optional(), + search_context_size: ResponsesSearchContextSize$inboundSchema.optional(), + user_location: z.nullable(ResponsesWebSearchUserLocation$inboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + search_context_size: 'searchContextSize', + user_location: 'userLocation', + }); }); -}); /** @internal */ export type OpenResponsesWebSearch20250826Tool$Outbound = { - type: "web_search_2025_08_26"; - filters?: - | OpenResponsesWebSearch20250826ToolFilters$Outbound - | null - | undefined; + type: 'web_search_2025_08_26'; + filters?: OpenResponsesWebSearch20250826ToolFilters$Outbound | null | undefined; search_context_size?: string | undefined; user_location?: ResponsesWebSearchUserLocation$Outbound | null | undefined; }; @@ -128,28 +125,27 @@ export type OpenResponsesWebSearch20250826Tool$Outbound = { export const OpenResponsesWebSearch20250826Tool$outboundSchema: z.ZodType< OpenResponsesWebSearch20250826Tool$Outbound, OpenResponsesWebSearch20250826Tool -> = z.object({ - type: z.literal("web_search_2025_08_26"), - filters: z.nullable( - z.lazy(() => OpenResponsesWebSearch20250826ToolFilters$outboundSchema), - ).optional(), - searchContextSize: ResponsesSearchContextSize$outboundSchema.optional(), - userLocation: z.nullable(ResponsesWebSearchUserLocation$outboundSchema) - .optional(), -}).transform((v) => { - return remap$(v, { - searchContextSize: "search_context_size", - userLocation: "user_location", +> = z + .object({ + type: z.literal('web_search_2025_08_26'), + filters: z + .nullable(z.lazy(() => OpenResponsesWebSearch20250826ToolFilters$outboundSchema)) + .optional(), + searchContextSize: ResponsesSearchContextSize$outboundSchema.optional(), + userLocation: z.nullable(ResponsesWebSearchUserLocation$outboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + searchContextSize: 'search_context_size', + userLocation: 'user_location', + }); }); -}); export function openResponsesWebSearch20250826ToolToJSON( openResponsesWebSearch20250826Tool: OpenResponsesWebSearch20250826Tool, ): string { return JSON.stringify( - OpenResponsesWebSearch20250826Tool$outboundSchema.parse( - openResponsesWebSearch20250826Tool, - ), + OpenResponsesWebSearch20250826Tool$outboundSchema.parse(openResponsesWebSearch20250826Tool), ); } export function openResponsesWebSearch20250826ToolFromJSON( @@ -157,8 +153,7 @@ export function openResponsesWebSearch20250826ToolFromJSON( ): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesWebSearch20250826Tool$inboundSchema.parse(JSON.parse(x)), + (x) => OpenResponsesWebSearch20250826Tool$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesWebSearch20250826Tool' from JSON`, ); } diff --git a/src/models/openresponseswebsearchpreview20250311tool.ts b/src/models/openresponseswebsearchpreview20250311tool.ts index 767d79d8..261083fc 100644 --- a/src/models/openresponseswebsearchpreview20250311tool.ts +++ b/src/models/openresponseswebsearchpreview20250311tool.ts @@ -3,28 +3,31 @@ * @generated-id: d450efb8b660 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { ResponsesSearchContextSize } from './responsessearchcontextsize.js'; +import type { + WebSearchPreviewToolUserLocation, + WebSearchPreviewToolUserLocation$Outbound, +} from './websearchpreviewtooluserlocation.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; import { - ResponsesSearchContextSize, ResponsesSearchContextSize$inboundSchema, ResponsesSearchContextSize$outboundSchema, -} from "./responsessearchcontextsize.js"; +} from './responsessearchcontextsize.js'; import { - WebSearchPreviewToolUserLocation, WebSearchPreviewToolUserLocation$inboundSchema, - WebSearchPreviewToolUserLocation$Outbound, WebSearchPreviewToolUserLocation$outboundSchema, -} from "./websearchpreviewtooluserlocation.js"; +} from './websearchpreviewtooluserlocation.js'; /** * Web search preview tool configuration (2025-03-11 version) */ export type OpenResponsesWebSearchPreview20250311Tool = { - type: "web_search_preview_2025_03_11"; + type: 'web_search_preview_2025_03_11'; /** * Size of the search context for web search tools */ @@ -36,44 +39,44 @@ export type OpenResponsesWebSearchPreview20250311Tool = { export const OpenResponsesWebSearchPreview20250311Tool$inboundSchema: z.ZodType< OpenResponsesWebSearchPreview20250311Tool, unknown -> = z.object({ - type: z.literal("web_search_preview_2025_03_11"), - search_context_size: ResponsesSearchContextSize$inboundSchema.optional(), - user_location: z.nullable(WebSearchPreviewToolUserLocation$inboundSchema) - .optional(), -}).transform((v) => { - return remap$(v, { - "search_context_size": "searchContextSize", - "user_location": "userLocation", +> = z + .object({ + type: z.literal('web_search_preview_2025_03_11'), + search_context_size: ResponsesSearchContextSize$inboundSchema.optional(), + user_location: z.nullable(WebSearchPreviewToolUserLocation$inboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + search_context_size: 'searchContextSize', + user_location: 'userLocation', + }); }); -}); /** @internal */ export type OpenResponsesWebSearchPreview20250311Tool$Outbound = { - type: "web_search_preview_2025_03_11"; + type: 'web_search_preview_2025_03_11'; search_context_size?: string | undefined; user_location?: WebSearchPreviewToolUserLocation$Outbound | null | undefined; }; /** @internal */ -export const OpenResponsesWebSearchPreview20250311Tool$outboundSchema: - z.ZodType< - OpenResponsesWebSearchPreview20250311Tool$Outbound, - OpenResponsesWebSearchPreview20250311Tool - > = z.object({ - type: z.literal("web_search_preview_2025_03_11"), +export const OpenResponsesWebSearchPreview20250311Tool$outboundSchema: z.ZodType< + OpenResponsesWebSearchPreview20250311Tool$Outbound, + OpenResponsesWebSearchPreview20250311Tool +> = z + .object({ + type: z.literal('web_search_preview_2025_03_11'), searchContextSize: ResponsesSearchContextSize$outboundSchema.optional(), - userLocation: z.nullable(WebSearchPreviewToolUserLocation$outboundSchema) - .optional(), - }).transform((v) => { + userLocation: z.nullable(WebSearchPreviewToolUserLocation$outboundSchema).optional(), + }) + .transform((v) => { return remap$(v, { - searchContextSize: "search_context_size", - userLocation: "user_location", + searchContextSize: 'search_context_size', + userLocation: 'user_location', }); }); export function openResponsesWebSearchPreview20250311ToolToJSON( - openResponsesWebSearchPreview20250311Tool: - OpenResponsesWebSearchPreview20250311Tool, + openResponsesWebSearchPreview20250311Tool: OpenResponsesWebSearchPreview20250311Tool, ): string { return JSON.stringify( OpenResponsesWebSearchPreview20250311Tool$outboundSchema.parse( @@ -83,16 +86,10 @@ export function openResponsesWebSearchPreview20250311ToolToJSON( } export function openResponsesWebSearchPreview20250311ToolFromJSON( jsonString: string, -): SafeParseResult< - OpenResponsesWebSearchPreview20250311Tool, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - OpenResponsesWebSearchPreview20250311Tool$inboundSchema.parse( - JSON.parse(x), - ), + (x) => OpenResponsesWebSearchPreview20250311Tool$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'OpenResponsesWebSearchPreview20250311Tool' from JSON`, ); } diff --git a/src/models/openresponseswebsearchpreviewtool.ts b/src/models/openresponseswebsearchpreviewtool.ts index 53d80f92..26052ee6 100644 --- a/src/models/openresponseswebsearchpreviewtool.ts +++ b/src/models/openresponseswebsearchpreviewtool.ts @@ -3,28 +3,31 @@ * @generated-id: 7d594dd37b72 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { ResponsesSearchContextSize } from './responsessearchcontextsize.js'; +import type { + WebSearchPreviewToolUserLocation, + WebSearchPreviewToolUserLocation$Outbound, +} from './websearchpreviewtooluserlocation.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; import { - ResponsesSearchContextSize, ResponsesSearchContextSize$inboundSchema, ResponsesSearchContextSize$outboundSchema, -} from "./responsessearchcontextsize.js"; +} from './responsessearchcontextsize.js'; import { - WebSearchPreviewToolUserLocation, WebSearchPreviewToolUserLocation$inboundSchema, - WebSearchPreviewToolUserLocation$Outbound, WebSearchPreviewToolUserLocation$outboundSchema, -} from "./websearchpreviewtooluserlocation.js"; +} from './websearchpreviewtooluserlocation.js'; /** * Web search preview tool configuration */ export type OpenResponsesWebSearchPreviewTool = { - type: "web_search_preview"; + type: 'web_search_preview'; /** * Size of the search context for web search tools */ @@ -36,20 +39,21 @@ export type OpenResponsesWebSearchPreviewTool = { export const OpenResponsesWebSearchPreviewTool$inboundSchema: z.ZodType< OpenResponsesWebSearchPreviewTool, unknown -> = z.object({ - type: z.literal("web_search_preview"), - search_context_size: ResponsesSearchContextSize$inboundSchema.optional(), - user_location: z.nullable(WebSearchPreviewToolUserLocation$inboundSchema) - .optional(), -}).transform((v) => { - return remap$(v, { - "search_context_size": "searchContextSize", - "user_location": "userLocation", +> = z + .object({ + type: z.literal('web_search_preview'), + search_context_size: ResponsesSearchContextSize$inboundSchema.optional(), + user_location: z.nullable(WebSearchPreviewToolUserLocation$inboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + search_context_size: 'searchContextSize', + user_location: 'userLocation', + }); }); -}); /** @internal */ export type OpenResponsesWebSearchPreviewTool$Outbound = { - type: "web_search_preview"; + type: 'web_search_preview'; search_context_size?: string | undefined; user_location?: WebSearchPreviewToolUserLocation$Outbound | null | undefined; }; @@ -58,25 +62,24 @@ export type OpenResponsesWebSearchPreviewTool$Outbound = { export const OpenResponsesWebSearchPreviewTool$outboundSchema: z.ZodType< OpenResponsesWebSearchPreviewTool$Outbound, OpenResponsesWebSearchPreviewTool -> = z.object({ - type: z.literal("web_search_preview"), - searchContextSize: ResponsesSearchContextSize$outboundSchema.optional(), - userLocation: z.nullable(WebSearchPreviewToolUserLocation$outboundSchema) - .optional(), -}).transform((v) => { - return remap$(v, { - searchContextSize: "search_context_size", - userLocation: "user_location", +> = z + .object({ + type: z.literal('web_search_preview'), + searchContextSize: ResponsesSearchContextSize$outboundSchema.optional(), + userLocation: z.nullable(WebSearchPreviewToolUserLocation$outboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + searchContextSize: 'search_context_size', + userLocation: 'user_location', + }); }); -}); export function openResponsesWebSearchPreviewToolToJSON( openResponsesWebSearchPreviewTool: OpenResponsesWebSearchPreviewTool, ): string { return JSON.stringify( - OpenResponsesWebSearchPreviewTool$outboundSchema.parse( - openResponsesWebSearchPreviewTool, - ), + OpenResponsesWebSearchPreviewTool$outboundSchema.parse(openResponsesWebSearchPreviewTool), ); } export function openResponsesWebSearchPreviewToolFromJSON( diff --git a/src/models/openresponseswebsearchtool.ts b/src/models/openresponseswebsearchtool.ts index 187fdd5a..50e1f994 100644 --- a/src/models/openresponseswebsearchtool.ts +++ b/src/models/openresponseswebsearchtool.ts @@ -3,22 +3,25 @@ * @generated-id: 510ab58460c2 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { ResponsesSearchContextSize } from './responsessearchcontextsize.js'; +import type { + ResponsesWebSearchUserLocation, + ResponsesWebSearchUserLocation$Outbound, +} from './responseswebsearchuserlocation.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; import { - ResponsesSearchContextSize, ResponsesSearchContextSize$inboundSchema, ResponsesSearchContextSize$outboundSchema, -} from "./responsessearchcontextsize.js"; +} from './responsessearchcontextsize.js'; import { - ResponsesWebSearchUserLocation, ResponsesWebSearchUserLocation$inboundSchema, - ResponsesWebSearchUserLocation$Outbound, ResponsesWebSearchUserLocation$outboundSchema, -} from "./responseswebsearchuserlocation.js"; +} from './responseswebsearchuserlocation.js'; export type OpenResponsesWebSearchToolFilters = { allowedDomains?: Array | null | undefined; @@ -28,7 +31,7 @@ export type OpenResponsesWebSearchToolFilters = { * Web search tool configuration */ export type OpenResponsesWebSearchTool = { - type: "web_search"; + type: 'web_search'; filters?: OpenResponsesWebSearchToolFilters | null | undefined; /** * Size of the search context for web search tools @@ -44,13 +47,15 @@ export type OpenResponsesWebSearchTool = { export const OpenResponsesWebSearchToolFilters$inboundSchema: z.ZodType< OpenResponsesWebSearchToolFilters, unknown -> = z.object({ - allowed_domains: z.nullable(z.array(z.string())).optional(), -}).transform((v) => { - return remap$(v, { - "allowed_domains": "allowedDomains", +> = z + .object({ + allowed_domains: z.nullable(z.array(z.string())).optional(), + }) + .transform((v) => { + return remap$(v, { + allowed_domains: 'allowedDomains', + }); }); -}); /** @internal */ export type OpenResponsesWebSearchToolFilters$Outbound = { allowed_domains?: Array | null | undefined; @@ -60,21 +65,21 @@ export type OpenResponsesWebSearchToolFilters$Outbound = { export const OpenResponsesWebSearchToolFilters$outboundSchema: z.ZodType< OpenResponsesWebSearchToolFilters$Outbound, OpenResponsesWebSearchToolFilters -> = z.object({ - allowedDomains: z.nullable(z.array(z.string())).optional(), -}).transform((v) => { - return remap$(v, { - allowedDomains: "allowed_domains", +> = z + .object({ + allowedDomains: z.nullable(z.array(z.string())).optional(), + }) + .transform((v) => { + return remap$(v, { + allowedDomains: 'allowed_domains', + }); }); -}); export function openResponsesWebSearchToolFiltersToJSON( openResponsesWebSearchToolFilters: OpenResponsesWebSearchToolFilters, ): string { return JSON.stringify( - OpenResponsesWebSearchToolFilters$outboundSchema.parse( - openResponsesWebSearchToolFilters, - ), + OpenResponsesWebSearchToolFilters$outboundSchema.parse(openResponsesWebSearchToolFilters), ); } export function openResponsesWebSearchToolFiltersFromJSON( @@ -91,23 +96,22 @@ export function openResponsesWebSearchToolFiltersFromJSON( export const OpenResponsesWebSearchTool$inboundSchema: z.ZodType< OpenResponsesWebSearchTool, unknown -> = z.object({ - type: z.literal("web_search"), - filters: z.nullable( - z.lazy(() => OpenResponsesWebSearchToolFilters$inboundSchema), - ).optional(), - search_context_size: ResponsesSearchContextSize$inboundSchema.optional(), - user_location: z.nullable(ResponsesWebSearchUserLocation$inboundSchema) - .optional(), -}).transform((v) => { - return remap$(v, { - "search_context_size": "searchContextSize", - "user_location": "userLocation", +> = z + .object({ + type: z.literal('web_search'), + filters: z.nullable(z.lazy(() => OpenResponsesWebSearchToolFilters$inboundSchema)).optional(), + search_context_size: ResponsesSearchContextSize$inboundSchema.optional(), + user_location: z.nullable(ResponsesWebSearchUserLocation$inboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + search_context_size: 'searchContextSize', + user_location: 'userLocation', + }); }); -}); /** @internal */ export type OpenResponsesWebSearchTool$Outbound = { - type: "web_search"; + type: 'web_search'; filters?: OpenResponsesWebSearchToolFilters$Outbound | null | undefined; search_context_size?: string | undefined; user_location?: ResponsesWebSearchUserLocation$Outbound | null | undefined; @@ -117,20 +121,19 @@ export type OpenResponsesWebSearchTool$Outbound = { export const OpenResponsesWebSearchTool$outboundSchema: z.ZodType< OpenResponsesWebSearchTool$Outbound, OpenResponsesWebSearchTool -> = z.object({ - type: z.literal("web_search"), - filters: z.nullable( - z.lazy(() => OpenResponsesWebSearchToolFilters$outboundSchema), - ).optional(), - searchContextSize: ResponsesSearchContextSize$outboundSchema.optional(), - userLocation: z.nullable(ResponsesWebSearchUserLocation$outboundSchema) - .optional(), -}).transform((v) => { - return remap$(v, { - searchContextSize: "search_context_size", - userLocation: "user_location", +> = z + .object({ + type: z.literal('web_search'), + filters: z.nullable(z.lazy(() => OpenResponsesWebSearchToolFilters$outboundSchema)).optional(), + searchContextSize: ResponsesSearchContextSize$outboundSchema.optional(), + userLocation: z.nullable(ResponsesWebSearchUserLocation$outboundSchema).optional(), + }) + .transform((v) => { + return remap$(v, { + searchContextSize: 'search_context_size', + userLocation: 'user_location', + }); }); -}); export function openResponsesWebSearchToolToJSON( openResponsesWebSearchTool: OpenResponsesWebSearchTool, diff --git a/src/models/operations/createauthkeyscode.ts b/src/models/operations/createauthkeyscode.ts index 5309dfd7..37eccf66 100644 --- a/src/models/operations/createauthkeyscode.ts +++ b/src/models/operations/createauthkeyscode.ts @@ -3,20 +3,21 @@ * @generated-id: 1443f6afbf40 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import { safeParse } from "../../lib/schemas.js"; -import * as openEnums from "../../types/enums.js"; -import { OpenEnum } from "../../types/enums.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; +import type { OpenEnum } from '../../types/enums.js'; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import { safeParse } from '../../lib/schemas.js'; +import * as openEnums from '../../types/enums.js'; /** * The method used to generate the code challenge */ export const CreateAuthKeysCodeCodeChallengeMethod = { - S256: "S256", - Plain: "plain", + S256: 'S256', + Plain: 'plain', } as const; /** * The method used to generate the code challenge @@ -95,44 +96,42 @@ export type CreateAuthKeysCodeRequest$Outbound = { export const CreateAuthKeysCodeRequest$outboundSchema: z.ZodType< CreateAuthKeysCodeRequest$Outbound, CreateAuthKeysCodeRequest -> = z.object({ - callbackUrl: z.string(), - codeChallenge: z.string().optional(), - codeChallengeMethod: CreateAuthKeysCodeCodeChallengeMethod$outboundSchema - .optional(), - limit: z.number().optional(), - expiresAt: z.nullable(z.date().transform(v => v.toISOString())).optional(), -}).transform((v) => { - return remap$(v, { - callbackUrl: "callback_url", - codeChallenge: "code_challenge", - codeChallengeMethod: "code_challenge_method", - expiresAt: "expires_at", +> = z + .object({ + callbackUrl: z.string(), + codeChallenge: z.string().optional(), + codeChallengeMethod: CreateAuthKeysCodeCodeChallengeMethod$outboundSchema.optional(), + limit: z.number().optional(), + expiresAt: z.nullable(z.date().transform((v) => v.toISOString())).optional(), + }) + .transform((v) => { + return remap$(v, { + callbackUrl: 'callback_url', + codeChallenge: 'code_challenge', + codeChallengeMethod: 'code_challenge_method', + expiresAt: 'expires_at', + }); }); -}); export function createAuthKeysCodeRequestToJSON( createAuthKeysCodeRequest: CreateAuthKeysCodeRequest, ): string { - return JSON.stringify( - CreateAuthKeysCodeRequest$outboundSchema.parse(createAuthKeysCodeRequest), - ); + return JSON.stringify(CreateAuthKeysCodeRequest$outboundSchema.parse(createAuthKeysCodeRequest)); } /** @internal */ -export const CreateAuthKeysCodeData$inboundSchema: z.ZodType< - CreateAuthKeysCodeData, - unknown -> = z.object({ - id: z.string(), - app_id: z.number(), - created_at: z.string(), -}).transform((v) => { - return remap$(v, { - "app_id": "appId", - "created_at": "createdAt", +export const CreateAuthKeysCodeData$inboundSchema: z.ZodType = z + .object({ + id: z.string(), + app_id: z.number(), + created_at: z.string(), + }) + .transform((v) => { + return remap$(v, { + app_id: 'appId', + created_at: 'createdAt', + }); }); -}); export function createAuthKeysCodeDataFromJSON( jsonString: string, diff --git a/src/models/operations/createcoinbasecharge.ts b/src/models/operations/createcoinbasecharge.ts index a16d5a04..0dabe87f 100644 --- a/src/models/operations/createcoinbasecharge.ts +++ b/src/models/operations/createcoinbasecharge.ts @@ -3,11 +3,12 @@ * @generated-id: 1e75ac2debf2 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import { safeParse } from "../../lib/schemas.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import { safeParse } from '../../lib/schemas.js'; export type CreateCoinbaseChargeSecurity = { bearer: string; @@ -72,32 +73,32 @@ export function createCoinbaseChargeSecurityToJSON( createCoinbaseChargeSecurity: CreateCoinbaseChargeSecurity, ): string { return JSON.stringify( - CreateCoinbaseChargeSecurity$outboundSchema.parse( - createCoinbaseChargeSecurity, - ), + CreateCoinbaseChargeSecurity$outboundSchema.parse(createCoinbaseChargeSecurity), ); } /** @internal */ -export const CallData$inboundSchema: z.ZodType = z.object({ - deadline: z.string(), - fee_amount: z.string(), - id: z.string(), - operator: z.string(), - prefix: z.string(), - recipient: z.string(), - recipient_amount: z.string(), - recipient_currency: z.string(), - refund_destination: z.string(), - signature: z.string(), -}).transform((v) => { - return remap$(v, { - "fee_amount": "feeAmount", - "recipient_amount": "recipientAmount", - "recipient_currency": "recipientCurrency", - "refund_destination": "refundDestination", +export const CallData$inboundSchema: z.ZodType = z + .object({ + deadline: z.string(), + fee_amount: z.string(), + id: z.string(), + operator: z.string(), + prefix: z.string(), + recipient: z.string(), + recipient_amount: z.string(), + recipient_currency: z.string(), + refund_destination: z.string(), + signature: z.string(), + }) + .transform((v) => { + return remap$(v, { + fee_amount: 'feeAmount', + recipient_amount: 'recipientAmount', + recipient_currency: 'recipientCurrency', + refund_destination: 'refundDestination', + }); }); -}); export function callDataFromJSON( jsonString: string, @@ -110,16 +111,18 @@ export function callDataFromJSON( } /** @internal */ -export const Metadata$inboundSchema: z.ZodType = z.object({ - chain_id: z.number(), - contract_address: z.string(), - sender: z.string(), -}).transform((v) => { - return remap$(v, { - "chain_id": "chainId", - "contract_address": "contractAddress", +export const Metadata$inboundSchema: z.ZodType = z + .object({ + chain_id: z.number(), + contract_address: z.string(), + sender: z.string(), + }) + .transform((v) => { + return remap$(v, { + chain_id: 'chainId', + contract_address: 'contractAddress', + }); }); -}); export function metadataFromJSON( jsonString: string, @@ -132,13 +135,14 @@ export function metadataFromJSON( } /** @internal */ -export const TransferIntent$inboundSchema: z.ZodType = - z.object({ +export const TransferIntent$inboundSchema: z.ZodType = z + .object({ call_data: z.lazy(() => CallData$inboundSchema), metadata: z.lazy(() => Metadata$inboundSchema), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "call_data": "callData", + call_data: 'callData', }); }); @@ -153,13 +157,15 @@ export function transferIntentFromJSON( } /** @internal */ -export const Web3Data$inboundSchema: z.ZodType = z.object({ - transfer_intent: z.lazy(() => TransferIntent$inboundSchema), -}).transform((v) => { - return remap$(v, { - "transfer_intent": "transferIntent", +export const Web3Data$inboundSchema: z.ZodType = z + .object({ + transfer_intent: z.lazy(() => TransferIntent$inboundSchema), + }) + .transform((v) => { + return remap$(v, { + transfer_intent: 'transferIntent', + }); }); -}); export function web3DataFromJSON( jsonString: string, @@ -172,21 +178,21 @@ export function web3DataFromJSON( } /** @internal */ -export const CreateCoinbaseChargeData$inboundSchema: z.ZodType< - CreateCoinbaseChargeData, - unknown -> = z.object({ - id: z.string(), - created_at: z.string(), - expires_at: z.string(), - web3_data: z.lazy(() => Web3Data$inboundSchema), -}).transform((v) => { - return remap$(v, { - "created_at": "createdAt", - "expires_at": "expiresAt", - "web3_data": "web3Data", - }); -}); +export const CreateCoinbaseChargeData$inboundSchema: z.ZodType = + z + .object({ + id: z.string(), + created_at: z.string(), + expires_at: z.string(), + web3_data: z.lazy(() => Web3Data$inboundSchema), + }) + .transform((v) => { + return remap$(v, { + created_at: 'createdAt', + expires_at: 'expiresAt', + web3_data: 'web3Data', + }); + }); export function createCoinbaseChargeDataFromJSON( jsonString: string, diff --git a/src/models/operations/createembeddings.ts b/src/models/operations/createembeddings.ts index fa8b7586..ee7ecb35 100644 --- a/src/models/operations/createembeddings.ts +++ b/src/models/operations/createembeddings.ts @@ -3,26 +3,27 @@ * @generated-id: 7c210337fdff */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import { safeParse } from "../../lib/schemas.js"; -import * as openEnums from "../../types/enums.js"; -import { ClosedEnum, OpenEnum } from "../../types/enums.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; -import * as models from "../index.js"; +import type { ClosedEnum, OpenEnum } from '../../types/enums.js'; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import { safeParse } from '../../lib/schemas.js'; +import * as openEnums from '../../types/enums.js'; +import * as models from '../index.js'; export type ImageUrl = { url: string; }; export type ContentImageURL = { - type: "image_url"; + type: 'image_url'; imageUrl: ImageUrl; }; export type ContentText = { - type: "text"; + type: 'text'; text: string; }; @@ -40,18 +41,13 @@ export type InputUnion = | Array; export const EncodingFormat = { - Float: "float", - Base64: "base64", + Float: 'float', + Base64: 'base64', } as const; export type EncodingFormat = OpenEnum; export type CreateEmbeddingsRequest = { - input: - | string - | Array - | Array - | Array> - | Array; + input: string | Array | Array | Array> | Array; model: string; encodingFormat?: EncodingFormat | undefined; dimensions?: number | undefined; @@ -64,12 +60,12 @@ export type CreateEmbeddingsRequest = { }; export const ObjectT = { - List: "list", + List: 'list', } as const; export type ObjectT = ClosedEnum; export const ObjectEmbedding = { - Embedding: "embedding", + Embedding: 'embedding', } as const; export type ObjectEmbedding = ClosedEnum; @@ -106,10 +102,9 @@ export type ImageUrl$Outbound = { }; /** @internal */ -export const ImageUrl$outboundSchema: z.ZodType = z - .object({ - url: z.string(), - }); +export const ImageUrl$outboundSchema: z.ZodType = z.object({ + url: z.string(), +}); export function imageUrlToJSON(imageUrl: ImageUrl): string { return JSON.stringify(ImageUrl$outboundSchema.parse(imageUrl)); @@ -117,41 +112,36 @@ export function imageUrlToJSON(imageUrl: ImageUrl): string { /** @internal */ export type ContentImageURL$Outbound = { - type: "image_url"; + type: 'image_url'; image_url: ImageUrl$Outbound; }; /** @internal */ -export const ContentImageURL$outboundSchema: z.ZodType< - ContentImageURL$Outbound, - ContentImageURL -> = z.object({ - type: z.literal("image_url"), - imageUrl: z.lazy(() => ImageUrl$outboundSchema), -}).transform((v) => { - return remap$(v, { - imageUrl: "image_url", - }); -}); - -export function contentImageURLToJSON( - contentImageURL: ContentImageURL, -): string { +export const ContentImageURL$outboundSchema: z.ZodType = + z + .object({ + type: z.literal('image_url'), + imageUrl: z.lazy(() => ImageUrl$outboundSchema), + }) + .transform((v) => { + return remap$(v, { + imageUrl: 'image_url', + }); + }); + +export function contentImageURLToJSON(contentImageURL: ContentImageURL): string { return JSON.stringify(ContentImageURL$outboundSchema.parse(contentImageURL)); } /** @internal */ export type ContentText$Outbound = { - type: "text"; + type: 'text'; text: string; }; /** @internal */ -export const ContentText$outboundSchema: z.ZodType< - ContentText$Outbound, - ContentText -> = z.object({ - type: z.literal("text"), +export const ContentText$outboundSchema: z.ZodType = z.object({ + type: z.literal('text'), text: z.string(), }); @@ -163,11 +153,10 @@ export function contentTextToJSON(contentText: ContentText): string { export type Content$Outbound = ContentText$Outbound | ContentImageURL$Outbound; /** @internal */ -export const Content$outboundSchema: z.ZodType = z - .union([ - z.lazy(() => ContentText$outboundSchema), - z.lazy(() => ContentImageURL$outboundSchema), - ]); +export const Content$outboundSchema: z.ZodType = z.union([ + z.lazy(() => ContentText$outboundSchema), + z.lazy(() => ContentImageURL$outboundSchema), +]); export function contentToJSON(content: Content): string { return JSON.stringify(Content$outboundSchema.parse(content)); @@ -201,10 +190,7 @@ export type InputUnion$Outbound = | Array; /** @internal */ -export const InputUnion$outboundSchema: z.ZodType< - InputUnion$Outbound, - InputUnion -> = z.union([ +export const InputUnion$outboundSchema: z.ZodType = z.union([ z.string(), z.array(z.string()), z.array(z.number()), @@ -222,12 +208,7 @@ export const EncodingFormat$outboundSchema: z.ZodType = /** @internal */ export type CreateEmbeddingsRequest$Outbound = { - input: - | string - | Array - | Array - | Array> - | Array; + input: string | Array | Array | Array> | Array; model: string; encoding_format?: string | undefined; dimensions?: number | undefined; @@ -240,33 +221,33 @@ export type CreateEmbeddingsRequest$Outbound = { export const CreateEmbeddingsRequest$outboundSchema: z.ZodType< CreateEmbeddingsRequest$Outbound, CreateEmbeddingsRequest -> = z.object({ - input: z.union([ - z.string(), - z.array(z.string()), - z.array(z.number()), - z.array(z.array(z.number())), - z.array(z.lazy(() => Input$outboundSchema)), - ]), - model: z.string(), - encodingFormat: EncodingFormat$outboundSchema.optional(), - dimensions: z.int().optional(), - user: z.string().optional(), - provider: models.ProviderPreferences$outboundSchema.optional(), - inputType: z.string().optional(), -}).transform((v) => { - return remap$(v, { - encodingFormat: "encoding_format", - inputType: "input_type", +> = z + .object({ + input: z.union([ + z.string(), + z.array(z.string()), + z.array(z.number()), + z.array(z.array(z.number())), + z.array(z.lazy(() => Input$outboundSchema)), + ]), + model: z.string(), + encodingFormat: EncodingFormat$outboundSchema.optional(), + dimensions: z.int().optional(), + user: z.string().optional(), + provider: models.ProviderPreferences$outboundSchema.optional(), + inputType: z.string().optional(), + }) + .transform((v) => { + return remap$(v, { + encodingFormat: 'encoding_format', + inputType: 'input_type', + }); }); -}); export function createEmbeddingsRequestToJSON( createEmbeddingsRequest: CreateEmbeddingsRequest, ): string { - return JSON.stringify( - CreateEmbeddingsRequest$outboundSchema.parse(createEmbeddingsRequest), - ); + return JSON.stringify(CreateEmbeddingsRequest$outboundSchema.parse(createEmbeddingsRequest)); } /** @internal */ @@ -293,14 +274,15 @@ export function embeddingFromJSON( } /** @internal */ -export const CreateEmbeddingsData$inboundSchema: z.ZodType< - CreateEmbeddingsData, - unknown -> = z.object({ - object: ObjectEmbedding$inboundSchema, - embedding: z.union([z.array(z.number()), z.string()]), - index: z.number().optional(), -}); +export const CreateEmbeddingsData$inboundSchema: z.ZodType = + z.object({ + object: ObjectEmbedding$inboundSchema, + embedding: z.union([ + z.array(z.number()), + z.string(), + ]), + index: z.number().optional(), + }); export function createEmbeddingsDataFromJSON( jsonString: string, @@ -313,20 +295,20 @@ export function createEmbeddingsDataFromJSON( } /** @internal */ -export const Usage$inboundSchema: z.ZodType = z.object({ - prompt_tokens: z.number(), - total_tokens: z.number(), - cost: z.number().optional(), -}).transform((v) => { - return remap$(v, { - "prompt_tokens": "promptTokens", - "total_tokens": "totalTokens", +export const Usage$inboundSchema: z.ZodType = z + .object({ + prompt_tokens: z.number(), + total_tokens: z.number(), + cost: z.number().optional(), + }) + .transform((v) => { + return remap$(v, { + prompt_tokens: 'promptTokens', + total_tokens: 'totalTokens', + }); }); -}); -export function usageFromJSON( - jsonString: string, -): SafeParseResult { +export function usageFromJSON(jsonString: string): SafeParseResult { return safeParse( jsonString, (x) => Usage$inboundSchema.parse(JSON.parse(x)), @@ -357,13 +339,11 @@ export function createEmbeddingsResponseBodyFromJSON( } /** @internal */ -export const CreateEmbeddingsResponse$inboundSchema: z.ZodType< - CreateEmbeddingsResponse, - unknown -> = z.union([ - z.lazy(() => CreateEmbeddingsResponseBody$inboundSchema), - z.string(), -]); +export const CreateEmbeddingsResponse$inboundSchema: z.ZodType = + z.union([ + z.lazy(() => CreateEmbeddingsResponseBody$inboundSchema), + z.string(), + ]); export function createEmbeddingsResponseFromJSON( jsonString: string, diff --git a/src/models/operations/createkeys.ts b/src/models/operations/createkeys.ts index 24aa7279..d24a5fcb 100644 --- a/src/models/operations/createkeys.ts +++ b/src/models/operations/createkeys.ts @@ -3,21 +3,22 @@ * @generated-id: e7a250c8b7bb */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import { safeParse } from "../../lib/schemas.js"; -import * as openEnums from "../../types/enums.js"; -import { OpenEnum } from "../../types/enums.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; +import type { OpenEnum } from '../../types/enums.js'; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import { safeParse } from '../../lib/schemas.js'; +import * as openEnums from '../../types/enums.js'; /** * Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. */ export const CreateKeysLimitReset = { - Daily: "daily", - Weekly: "weekly", - Monthly: "monthly", + Daily: 'daily', + Weekly: 'weekly', + Monthly: 'monthly', } as const; /** * Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. @@ -144,10 +145,8 @@ export type CreateKeysResponse = { }; /** @internal */ -export const CreateKeysLimitReset$outboundSchema: z.ZodType< - string, - CreateKeysLimitReset -> = openEnums.outboundSchema(CreateKeysLimitReset); +export const CreateKeysLimitReset$outboundSchema: z.ZodType = + openEnums.outboundSchema(CreateKeysLimitReset); /** @internal */ export type CreateKeysRequest$Outbound = { @@ -162,31 +161,29 @@ export type CreateKeysRequest$Outbound = { export const CreateKeysRequest$outboundSchema: z.ZodType< CreateKeysRequest$Outbound, CreateKeysRequest -> = z.object({ - name: z.string(), - limit: z.nullable(z.number()).optional(), - limitReset: z.nullable(CreateKeysLimitReset$outboundSchema).optional(), - includeByokInLimit: z.boolean().optional(), - expiresAt: z.nullable(z.date().transform(v => v.toISOString())).optional(), -}).transform((v) => { - return remap$(v, { - limitReset: "limit_reset", - includeByokInLimit: "include_byok_in_limit", - expiresAt: "expires_at", +> = z + .object({ + name: z.string(), + limit: z.nullable(z.number()).optional(), + limitReset: z.nullable(CreateKeysLimitReset$outboundSchema).optional(), + includeByokInLimit: z.boolean().optional(), + expiresAt: z.nullable(z.date().transform((v) => v.toISOString())).optional(), + }) + .transform((v) => { + return remap$(v, { + limitReset: 'limit_reset', + includeByokInLimit: 'include_byok_in_limit', + expiresAt: 'expires_at', + }); }); -}); -export function createKeysRequestToJSON( - createKeysRequest: CreateKeysRequest, -): string { - return JSON.stringify( - CreateKeysRequest$outboundSchema.parse(createKeysRequest), - ); +export function createKeysRequestToJSON(createKeysRequest: CreateKeysRequest): string { + return JSON.stringify(CreateKeysRequest$outboundSchema.parse(createKeysRequest)); } /** @internal */ -export const CreateKeysData$inboundSchema: z.ZodType = - z.object({ +export const CreateKeysData$inboundSchema: z.ZodType = z + .object({ hash: z.string(), name: z.string(), label: z.string(), @@ -205,24 +202,31 @@ export const CreateKeysData$inboundSchema: z.ZodType = byok_usage_monthly: z.number(), created_at: z.string(), updated_at: z.nullable(z.string()), - expires_at: z.nullable( - z.iso.datetime({ offset: true }).transform(v => new Date(v)), - ).optional(), - }).transform((v) => { + expires_at: z + .nullable( + z.iso + .datetime({ + offset: true, + }) + .transform((v) => new Date(v)), + ) + .optional(), + }) + .transform((v) => { return remap$(v, { - "limit_remaining": "limitRemaining", - "limit_reset": "limitReset", - "include_byok_in_limit": "includeByokInLimit", - "usage_daily": "usageDaily", - "usage_weekly": "usageWeekly", - "usage_monthly": "usageMonthly", - "byok_usage": "byokUsage", - "byok_usage_daily": "byokUsageDaily", - "byok_usage_weekly": "byokUsageWeekly", - "byok_usage_monthly": "byokUsageMonthly", - "created_at": "createdAt", - "updated_at": "updatedAt", - "expires_at": "expiresAt", + limit_remaining: 'limitRemaining', + limit_reset: 'limitReset', + include_byok_in_limit: 'includeByokInLimit', + usage_daily: 'usageDaily', + usage_weekly: 'usageWeekly', + usage_monthly: 'usageMonthly', + byok_usage: 'byokUsage', + byok_usage_daily: 'byokUsageDaily', + byok_usage_weekly: 'byokUsageWeekly', + byok_usage_monthly: 'byokUsageMonthly', + created_at: 'createdAt', + updated_at: 'updatedAt', + expires_at: 'expiresAt', }); }); @@ -237,10 +241,7 @@ export function createKeysDataFromJSON( } /** @internal */ -export const CreateKeysResponse$inboundSchema: z.ZodType< - CreateKeysResponse, - unknown -> = z.object({ +export const CreateKeysResponse$inboundSchema: z.ZodType = z.object({ data: z.lazy(() => CreateKeysData$inboundSchema), key: z.string(), }); diff --git a/src/models/operations/createresponses.ts b/src/models/operations/createresponses.ts index 5e74e0c6..fecc0c7a 100644 --- a/src/models/operations/createresponses.ts +++ b/src/models/operations/createresponses.ts @@ -3,12 +3,13 @@ * @generated-id: 7ad611b27e9d */ -import * as z from "zod/v4"; -import { EventStream } from "../../lib/event-streams.js"; -import { safeParse } from "../../lib/schemas.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; -import * as models from "../index.js"; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { EventStream } from '../../lib/event-streams.js'; +import { safeParse } from '../../lib/schemas.js'; +import * as models from '../index.js'; /** * Successful response @@ -29,18 +30,21 @@ export const CreateResponsesResponseBody$inboundSchema: z.ZodType< CreateResponsesResponseBody, unknown > = z.object({ - data: z.string().transform((v, ctx) => { - try { - return JSON.parse(v); - } catch (err) { - ctx.addIssue({ - input: v, - code: "custom", - message: `malformed json: ${err}`, - }); - return z.NEVER; - } - }).pipe(models.OpenResponsesStreamEvent$inboundSchema), + data: z + .string() + .transform((v, ctx) => { + try { + return JSON.parse(v); + } catch (err) { + ctx.addIssue({ + input: v, + code: 'custom', + message: `malformed json: ${err}`, + }); + return z.NEVER; + } + }) + .pipe(models.OpenResponsesStreamEvent$inboundSchema), }); export function createResponsesResponseBodyFromJSON( @@ -54,23 +58,23 @@ export function createResponsesResponseBodyFromJSON( } /** @internal */ -export const CreateResponsesResponse$inboundSchema: z.ZodType< - CreateResponsesResponse, - unknown -> = z.union([ - models.OpenResponsesNonStreamingResponse$inboundSchema, - z.custom>(x => x instanceof ReadableStream) - .transform(stream => { - return new EventStream(stream, rawEvent => { - if (rawEvent.data === "[DONE]") return { done: true }; - return { - value: z.lazy(() => CreateResponsesResponseBody$inboundSchema).parse( - rawEvent, - )?.data, - }; - }); - }), -]); +export const CreateResponsesResponse$inboundSchema: z.ZodType = + z.union([ + models.OpenResponsesNonStreamingResponse$inboundSchema, + z + .custom>((x) => x instanceof ReadableStream) + .transform((stream) => { + return new EventStream(stream, (rawEvent) => { + if (rawEvent.data === '[DONE]') + return { + done: true, + }; + return { + value: z.lazy(() => CreateResponsesResponseBody$inboundSchema).parse(rawEvent)?.data, + }; + }); + }), + ]); export function createResponsesResponseFromJSON( jsonString: string, diff --git a/src/models/operations/deletekeys.ts b/src/models/operations/deletekeys.ts index f939ec44..90cbd69f 100644 --- a/src/models/operations/deletekeys.ts +++ b/src/models/operations/deletekeys.ts @@ -3,10 +3,11 @@ * @generated-id: efa22339a3d6 */ -import * as z from "zod/v4"; -import { safeParse } from "../../lib/schemas.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../../lib/schemas.js'; export type DeleteKeysRequest = { /** @@ -38,19 +39,12 @@ export const DeleteKeysRequest$outboundSchema: z.ZodType< hash: z.string(), }); -export function deleteKeysRequestToJSON( - deleteKeysRequest: DeleteKeysRequest, -): string { - return JSON.stringify( - DeleteKeysRequest$outboundSchema.parse(deleteKeysRequest), - ); +export function deleteKeysRequestToJSON(deleteKeysRequest: DeleteKeysRequest): string { + return JSON.stringify(DeleteKeysRequest$outboundSchema.parse(deleteKeysRequest)); } /** @internal */ -export const DeleteKeysResponse$inboundSchema: z.ZodType< - DeleteKeysResponse, - unknown -> = z.object({ +export const DeleteKeysResponse$inboundSchema: z.ZodType = z.object({ deleted: z.literal(true), }); diff --git a/src/models/operations/exchangeauthcodeforapikey.ts b/src/models/operations/exchangeauthcodeforapikey.ts index 95540a83..a1798e25 100644 --- a/src/models/operations/exchangeauthcodeforapikey.ts +++ b/src/models/operations/exchangeauthcodeforapikey.ts @@ -3,20 +3,21 @@ * @generated-id: 440595fac2ad */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import { safeParse } from "../../lib/schemas.js"; -import * as openEnums from "../../types/enums.js"; -import { OpenEnum } from "../../types/enums.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; +import type { OpenEnum } from '../../types/enums.js'; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import { safeParse } from '../../lib/schemas.js'; +import * as openEnums from '../../types/enums.js'; /** * The method used to generate the code challenge */ export const ExchangeAuthCodeForAPIKeyCodeChallengeMethod = { - S256: "S256", - Plain: "plain", + S256: 'S256', + Plain: 'plain', } as const; /** * The method used to generate the code challenge @@ -37,10 +38,7 @@ export type ExchangeAuthCodeForAPIKeyRequest = { /** * The method used to generate the code challenge */ - codeChallengeMethod?: - | ExchangeAuthCodeForAPIKeyCodeChallengeMethod - | null - | undefined; + codeChallengeMethod?: ExchangeAuthCodeForAPIKeyCodeChallengeMethod | null | undefined; }; /** @@ -58,9 +56,10 @@ export type ExchangeAuthCodeForAPIKeyResponse = { }; /** @internal */ -export const ExchangeAuthCodeForAPIKeyCodeChallengeMethod$outboundSchema: - z.ZodType = openEnums - .outboundSchema(ExchangeAuthCodeForAPIKeyCodeChallengeMethod); +export const ExchangeAuthCodeForAPIKeyCodeChallengeMethod$outboundSchema: z.ZodType< + string, + ExchangeAuthCodeForAPIKeyCodeChallengeMethod +> = openEnums.outboundSchema(ExchangeAuthCodeForAPIKeyCodeChallengeMethod); /** @internal */ export type ExchangeAuthCodeForAPIKeyRequest$Outbound = { @@ -73,26 +72,26 @@ export type ExchangeAuthCodeForAPIKeyRequest$Outbound = { export const ExchangeAuthCodeForAPIKeyRequest$outboundSchema: z.ZodType< ExchangeAuthCodeForAPIKeyRequest$Outbound, ExchangeAuthCodeForAPIKeyRequest -> = z.object({ - code: z.string(), - codeVerifier: z.string().optional(), - codeChallengeMethod: z.nullable( - ExchangeAuthCodeForAPIKeyCodeChallengeMethod$outboundSchema, - ).optional(), -}).transform((v) => { - return remap$(v, { - codeVerifier: "code_verifier", - codeChallengeMethod: "code_challenge_method", +> = z + .object({ + code: z.string(), + codeVerifier: z.string().optional(), + codeChallengeMethod: z + .nullable(ExchangeAuthCodeForAPIKeyCodeChallengeMethod$outboundSchema) + .optional(), + }) + .transform((v) => { + return remap$(v, { + codeVerifier: 'code_verifier', + codeChallengeMethod: 'code_challenge_method', + }); }); -}); export function exchangeAuthCodeForAPIKeyRequestToJSON( exchangeAuthCodeForAPIKeyRequest: ExchangeAuthCodeForAPIKeyRequest, ): string { return JSON.stringify( - ExchangeAuthCodeForAPIKeyRequest$outboundSchema.parse( - exchangeAuthCodeForAPIKeyRequest, - ), + ExchangeAuthCodeForAPIKeyRequest$outboundSchema.parse(exchangeAuthCodeForAPIKeyRequest), ); } @@ -100,14 +99,16 @@ export function exchangeAuthCodeForAPIKeyRequestToJSON( export const ExchangeAuthCodeForAPIKeyResponse$inboundSchema: z.ZodType< ExchangeAuthCodeForAPIKeyResponse, unknown -> = z.object({ - key: z.string(), - user_id: z.nullable(z.string()), -}).transform((v) => { - return remap$(v, { - "user_id": "userId", +> = z + .object({ + key: z.string(), + user_id: z.nullable(z.string()), + }) + .transform((v) => { + return remap$(v, { + user_id: 'userId', + }); }); -}); export function exchangeAuthCodeForAPIKeyResponseFromJSON( jsonString: string, diff --git a/src/models/operations/getcredits.ts b/src/models/operations/getcredits.ts index 4fe313fe..8d795dc2 100644 --- a/src/models/operations/getcredits.ts +++ b/src/models/operations/getcredits.ts @@ -3,11 +3,12 @@ * @generated-id: 0e5a438307ae */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import { safeParse } from "../../lib/schemas.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import { safeParse } from '../../lib/schemas.js'; export type GetCreditsData = { /** @@ -28,14 +29,15 @@ export type GetCreditsResponse = { }; /** @internal */ -export const GetCreditsData$inboundSchema: z.ZodType = - z.object({ +export const GetCreditsData$inboundSchema: z.ZodType = z + .object({ total_credits: z.number(), total_usage: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "total_credits": "totalCredits", - "total_usage": "totalUsage", + total_credits: 'totalCredits', + total_usage: 'totalUsage', }); }); @@ -50,10 +52,7 @@ export function getCreditsDataFromJSON( } /** @internal */ -export const GetCreditsResponse$inboundSchema: z.ZodType< - GetCreditsResponse, - unknown -> = z.object({ +export const GetCreditsResponse$inboundSchema: z.ZodType = z.object({ data: z.lazy(() => GetCreditsData$inboundSchema), }); diff --git a/src/models/operations/getcurrentkey.ts b/src/models/operations/getcurrentkey.ts index 2c7c2dc7..11213df0 100644 --- a/src/models/operations/getcurrentkey.ts +++ b/src/models/operations/getcurrentkey.ts @@ -3,11 +3,12 @@ * @generated-id: ddb4fa558414 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import { safeParse } from "../../lib/schemas.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import { safeParse } from '../../lib/schemas.js'; /** * Legacy rate limit information about a key. Will always return -1. @@ -133,47 +134,52 @@ export function rateLimitFromJSON( } /** @internal */ -export const GetCurrentKeyData$inboundSchema: z.ZodType< - GetCurrentKeyData, - unknown -> = z.object({ - label: z.string(), - limit: z.nullable(z.number()), - usage: z.number(), - usage_daily: z.number(), - usage_weekly: z.number(), - usage_monthly: z.number(), - byok_usage: z.number(), - byok_usage_daily: z.number(), - byok_usage_weekly: z.number(), - byok_usage_monthly: z.number(), - is_free_tier: z.boolean(), - is_provisioning_key: z.boolean(), - limit_remaining: z.nullable(z.number()), - limit_reset: z.nullable(z.string()), - include_byok_in_limit: z.boolean(), - expires_at: z.nullable( - z.iso.datetime({ offset: true }).transform(v => new Date(v)), - ).optional(), - rate_limit: z.lazy(() => RateLimit$inboundSchema), -}).transform((v) => { - return remap$(v, { - "usage_daily": "usageDaily", - "usage_weekly": "usageWeekly", - "usage_monthly": "usageMonthly", - "byok_usage": "byokUsage", - "byok_usage_daily": "byokUsageDaily", - "byok_usage_weekly": "byokUsageWeekly", - "byok_usage_monthly": "byokUsageMonthly", - "is_free_tier": "isFreeTier", - "is_provisioning_key": "isProvisioningKey", - "limit_remaining": "limitRemaining", - "limit_reset": "limitReset", - "include_byok_in_limit": "includeByokInLimit", - "expires_at": "expiresAt", - "rate_limit": "rateLimit", +export const GetCurrentKeyData$inboundSchema: z.ZodType = z + .object({ + label: z.string(), + limit: z.nullable(z.number()), + usage: z.number(), + usage_daily: z.number(), + usage_weekly: z.number(), + usage_monthly: z.number(), + byok_usage: z.number(), + byok_usage_daily: z.number(), + byok_usage_weekly: z.number(), + byok_usage_monthly: z.number(), + is_free_tier: z.boolean(), + is_provisioning_key: z.boolean(), + limit_remaining: z.nullable(z.number()), + limit_reset: z.nullable(z.string()), + include_byok_in_limit: z.boolean(), + expires_at: z + .nullable( + z.iso + .datetime({ + offset: true, + }) + .transform((v) => new Date(v)), + ) + .optional(), + rate_limit: z.lazy(() => RateLimit$inboundSchema), + }) + .transform((v) => { + return remap$(v, { + usage_daily: 'usageDaily', + usage_weekly: 'usageWeekly', + usage_monthly: 'usageMonthly', + byok_usage: 'byokUsage', + byok_usage_daily: 'byokUsageDaily', + byok_usage_weekly: 'byokUsageWeekly', + byok_usage_monthly: 'byokUsageMonthly', + is_free_tier: 'isFreeTier', + is_provisioning_key: 'isProvisioningKey', + limit_remaining: 'limitRemaining', + limit_reset: 'limitReset', + include_byok_in_limit: 'includeByokInLimit', + expires_at: 'expiresAt', + rate_limit: 'rateLimit', + }); }); -}); export function getCurrentKeyDataFromJSON( jsonString: string, @@ -186,12 +192,10 @@ export function getCurrentKeyDataFromJSON( } /** @internal */ -export const GetCurrentKeyResponse$inboundSchema: z.ZodType< - GetCurrentKeyResponse, - unknown -> = z.object({ - data: z.lazy(() => GetCurrentKeyData$inboundSchema), -}); +export const GetCurrentKeyResponse$inboundSchema: z.ZodType = + z.object({ + data: z.lazy(() => GetCurrentKeyData$inboundSchema), + }); export function getCurrentKeyResponseFromJSON( jsonString: string, diff --git a/src/models/operations/getgeneration.ts b/src/models/operations/getgeneration.ts index 98e74eb7..4f767ad2 100644 --- a/src/models/operations/getgeneration.ts +++ b/src/models/operations/getgeneration.ts @@ -3,13 +3,14 @@ * @generated-id: 5cdb2959d2a5 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import { safeParse } from "../../lib/schemas.js"; -import * as openEnums from "../../types/enums.js"; -import { OpenEnum } from "../../types/enums.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; +import type { OpenEnum } from '../../types/enums.js'; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import { safeParse } from '../../lib/schemas.js'; +import * as openEnums from '../../types/enums.js'; export type GetGenerationRequest = { id: string; @@ -19,8 +20,8 @@ export type GetGenerationRequest = { * Type of API used for the generation */ export const ApiType = { - Completions: "completions", - Embeddings: "embeddings", + Completions: 'completions', + Embeddings: 'embeddings', } as const; /** * Type of API used for the generation @@ -184,84 +185,78 @@ export const GetGenerationRequest$outboundSchema: z.ZodType< id: z.string(), }); -export function getGenerationRequestToJSON( - getGenerationRequest: GetGenerationRequest, -): string { - return JSON.stringify( - GetGenerationRequest$outboundSchema.parse(getGenerationRequest), - ); +export function getGenerationRequestToJSON(getGenerationRequest: GetGenerationRequest): string { + return JSON.stringify(GetGenerationRequest$outboundSchema.parse(getGenerationRequest)); } /** @internal */ -export const ApiType$inboundSchema: z.ZodType = openEnums - .inboundSchema(ApiType); +export const ApiType$inboundSchema: z.ZodType = openEnums.inboundSchema(ApiType); /** @internal */ -export const GetGenerationData$inboundSchema: z.ZodType< - GetGenerationData, - unknown -> = z.object({ - id: z.string(), - upstream_id: z.nullable(z.string()), - total_cost: z.number(), - cache_discount: z.nullable(z.number()), - upstream_inference_cost: z.nullable(z.number()), - created_at: z.string(), - model: z.string(), - app_id: z.nullable(z.number()), - streamed: z.nullable(z.boolean()), - cancelled: z.nullable(z.boolean()), - provider_name: z.nullable(z.string()), - latency: z.nullable(z.number()), - moderation_latency: z.nullable(z.number()), - generation_time: z.nullable(z.number()), - finish_reason: z.nullable(z.string()), - tokens_prompt: z.nullable(z.number()), - tokens_completion: z.nullable(z.number()), - native_tokens_prompt: z.nullable(z.number()), - native_tokens_completion: z.nullable(z.number()), - native_tokens_completion_images: z.nullable(z.number()), - native_tokens_reasoning: z.nullable(z.number()), - native_tokens_cached: z.nullable(z.number()), - num_media_prompt: z.nullable(z.number()), - num_input_audio_prompt: z.nullable(z.number()), - num_media_completion: z.nullable(z.number()), - num_search_results: z.nullable(z.number()), - origin: z.string(), - usage: z.number(), - is_byok: z.boolean(), - native_finish_reason: z.nullable(z.string()), - external_user: z.nullable(z.string()), - api_type: z.nullable(ApiType$inboundSchema), -}).transform((v) => { - return remap$(v, { - "upstream_id": "upstreamId", - "total_cost": "totalCost", - "cache_discount": "cacheDiscount", - "upstream_inference_cost": "upstreamInferenceCost", - "created_at": "createdAt", - "app_id": "appId", - "provider_name": "providerName", - "moderation_latency": "moderationLatency", - "generation_time": "generationTime", - "finish_reason": "finishReason", - "tokens_prompt": "tokensPrompt", - "tokens_completion": "tokensCompletion", - "native_tokens_prompt": "nativeTokensPrompt", - "native_tokens_completion": "nativeTokensCompletion", - "native_tokens_completion_images": "nativeTokensCompletionImages", - "native_tokens_reasoning": "nativeTokensReasoning", - "native_tokens_cached": "nativeTokensCached", - "num_media_prompt": "numMediaPrompt", - "num_input_audio_prompt": "numInputAudioPrompt", - "num_media_completion": "numMediaCompletion", - "num_search_results": "numSearchResults", - "is_byok": "isByok", - "native_finish_reason": "nativeFinishReason", - "external_user": "externalUser", - "api_type": "apiType", +export const GetGenerationData$inboundSchema: z.ZodType = z + .object({ + id: z.string(), + upstream_id: z.nullable(z.string()), + total_cost: z.number(), + cache_discount: z.nullable(z.number()), + upstream_inference_cost: z.nullable(z.number()), + created_at: z.string(), + model: z.string(), + app_id: z.nullable(z.number()), + streamed: z.nullable(z.boolean()), + cancelled: z.nullable(z.boolean()), + provider_name: z.nullable(z.string()), + latency: z.nullable(z.number()), + moderation_latency: z.nullable(z.number()), + generation_time: z.nullable(z.number()), + finish_reason: z.nullable(z.string()), + tokens_prompt: z.nullable(z.number()), + tokens_completion: z.nullable(z.number()), + native_tokens_prompt: z.nullable(z.number()), + native_tokens_completion: z.nullable(z.number()), + native_tokens_completion_images: z.nullable(z.number()), + native_tokens_reasoning: z.nullable(z.number()), + native_tokens_cached: z.nullable(z.number()), + num_media_prompt: z.nullable(z.number()), + num_input_audio_prompt: z.nullable(z.number()), + num_media_completion: z.nullable(z.number()), + num_search_results: z.nullable(z.number()), + origin: z.string(), + usage: z.number(), + is_byok: z.boolean(), + native_finish_reason: z.nullable(z.string()), + external_user: z.nullable(z.string()), + api_type: z.nullable(ApiType$inboundSchema), + }) + .transform((v) => { + return remap$(v, { + upstream_id: 'upstreamId', + total_cost: 'totalCost', + cache_discount: 'cacheDiscount', + upstream_inference_cost: 'upstreamInferenceCost', + created_at: 'createdAt', + app_id: 'appId', + provider_name: 'providerName', + moderation_latency: 'moderationLatency', + generation_time: 'generationTime', + finish_reason: 'finishReason', + tokens_prompt: 'tokensPrompt', + tokens_completion: 'tokensCompletion', + native_tokens_prompt: 'nativeTokensPrompt', + native_tokens_completion: 'nativeTokensCompletion', + native_tokens_completion_images: 'nativeTokensCompletionImages', + native_tokens_reasoning: 'nativeTokensReasoning', + native_tokens_cached: 'nativeTokensCached', + num_media_prompt: 'numMediaPrompt', + num_input_audio_prompt: 'numInputAudioPrompt', + num_media_completion: 'numMediaCompletion', + num_search_results: 'numSearchResults', + is_byok: 'isByok', + native_finish_reason: 'nativeFinishReason', + external_user: 'externalUser', + api_type: 'apiType', + }); }); -}); export function getGenerationDataFromJSON( jsonString: string, @@ -274,12 +269,10 @@ export function getGenerationDataFromJSON( } /** @internal */ -export const GetGenerationResponse$inboundSchema: z.ZodType< - GetGenerationResponse, - unknown -> = z.object({ - data: z.lazy(() => GetGenerationData$inboundSchema), -}); +export const GetGenerationResponse$inboundSchema: z.ZodType = + z.object({ + data: z.lazy(() => GetGenerationData$inboundSchema), + }); export function getGenerationResponseFromJSON( jsonString: string, diff --git a/src/models/operations/getkey.ts b/src/models/operations/getkey.ts index 55d4f0f8..17f9a034 100644 --- a/src/models/operations/getkey.ts +++ b/src/models/operations/getkey.ts @@ -3,11 +3,12 @@ * @generated-id: 27d0f86c087f */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import { safeParse } from "../../lib/schemas.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import { safeParse } from '../../lib/schemas.js'; export type GetKeyRequest = { /** @@ -114,12 +115,10 @@ export type GetKeyRequest$Outbound = { }; /** @internal */ -export const GetKeyRequest$outboundSchema: z.ZodType< - GetKeyRequest$Outbound, - GetKeyRequest -> = z.object({ - hash: z.string(), -}); +export const GetKeyRequest$outboundSchema: z.ZodType = + z.object({ + hash: z.string(), + }); export function getKeyRequestToJSON(getKeyRequest: GetKeyRequest): string { return JSON.stringify(GetKeyRequest$outboundSchema.parse(getKeyRequest)); @@ -146,24 +145,31 @@ export const GetKeyData$inboundSchema: z.ZodType = z byok_usage_monthly: z.number(), created_at: z.string(), updated_at: z.nullable(z.string()), - expires_at: z.nullable( - z.iso.datetime({ offset: true }).transform(v => new Date(v)), - ).optional(), - }).transform((v) => { + expires_at: z + .nullable( + z.iso + .datetime({ + offset: true, + }) + .transform((v) => new Date(v)), + ) + .optional(), + }) + .transform((v) => { return remap$(v, { - "limit_remaining": "limitRemaining", - "limit_reset": "limitReset", - "include_byok_in_limit": "includeByokInLimit", - "usage_daily": "usageDaily", - "usage_weekly": "usageWeekly", - "usage_monthly": "usageMonthly", - "byok_usage": "byokUsage", - "byok_usage_daily": "byokUsageDaily", - "byok_usage_weekly": "byokUsageWeekly", - "byok_usage_monthly": "byokUsageMonthly", - "created_at": "createdAt", - "updated_at": "updatedAt", - "expires_at": "expiresAt", + limit_remaining: 'limitRemaining', + limit_reset: 'limitReset', + include_byok_in_limit: 'includeByokInLimit', + usage_daily: 'usageDaily', + usage_weekly: 'usageWeekly', + usage_monthly: 'usageMonthly', + byok_usage: 'byokUsage', + byok_usage_daily: 'byokUsageDaily', + byok_usage_weekly: 'byokUsageWeekly', + byok_usage_monthly: 'byokUsageMonthly', + created_at: 'createdAt', + updated_at: 'updatedAt', + expires_at: 'expiresAt', }); }); @@ -178,10 +184,9 @@ export function getKeyDataFromJSON( } /** @internal */ -export const GetKeyResponse$inboundSchema: z.ZodType = - z.object({ - data: z.lazy(() => GetKeyData$inboundSchema), - }); +export const GetKeyResponse$inboundSchema: z.ZodType = z.object({ + data: z.lazy(() => GetKeyData$inboundSchema), +}); export function getKeyResponseFromJSON( jsonString: string, diff --git a/src/models/operations/getmodels.ts b/src/models/operations/getmodels.ts index 97bb2f81..ef04b7e9 100644 --- a/src/models/operations/getmodels.ts +++ b/src/models/operations/getmodels.ts @@ -3,8 +3,8 @@ * @generated-id: f1343fbaaed5 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; export type GetModelsRequest = { category?: string | undefined; @@ -21,19 +21,17 @@ export type GetModelsRequest$Outbound = { export const GetModelsRequest$outboundSchema: z.ZodType< GetModelsRequest$Outbound, GetModelsRequest -> = z.object({ - category: z.string().optional(), - supportedParameters: z.string().optional(), -}).transform((v) => { - return remap$(v, { - supportedParameters: "supported_parameters", +> = z + .object({ + category: z.string().optional(), + supportedParameters: z.string().optional(), + }) + .transform((v) => { + return remap$(v, { + supportedParameters: 'supported_parameters', + }); }); -}); -export function getModelsRequestToJSON( - getModelsRequest: GetModelsRequest, -): string { - return JSON.stringify( - GetModelsRequest$outboundSchema.parse(getModelsRequest), - ); +export function getModelsRequestToJSON(getModelsRequest: GetModelsRequest): string { + return JSON.stringify(GetModelsRequest$outboundSchema.parse(getModelsRequest)); } diff --git a/src/models/operations/getparameters.ts b/src/models/operations/getparameters.ts index 8efe05fe..58cfcab4 100644 --- a/src/models/operations/getparameters.ts +++ b/src/models/operations/getparameters.ts @@ -3,14 +3,15 @@ * @generated-id: 9b364a4cca61 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import { safeParse } from "../../lib/schemas.js"; -import * as openEnums from "../../types/enums.js"; -import { OpenEnum } from "../../types/enums.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; -import * as models from "../index.js"; +import type { OpenEnum } from '../../types/enums.js'; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import { safeParse } from '../../lib/schemas.js'; +import * as openEnums from '../../types/enums.js'; +import * as models from '../index.js'; export type GetParametersSecurity = { bearer: string; @@ -23,30 +24,30 @@ export type GetParametersRequest = { }; export const SupportedParameter = { - Temperature: "temperature", - TopP: "top_p", - TopK: "top_k", - MinP: "min_p", - TopA: "top_a", - FrequencyPenalty: "frequency_penalty", - PresencePenalty: "presence_penalty", - RepetitionPenalty: "repetition_penalty", - MaxTokens: "max_tokens", - LogitBias: "logit_bias", - Logprobs: "logprobs", - TopLogprobs: "top_logprobs", - Seed: "seed", - ResponseFormat: "response_format", - StructuredOutputs: "structured_outputs", - Stop: "stop", - Tools: "tools", - ToolChoice: "tool_choice", - ParallelToolCalls: "parallel_tool_calls", - IncludeReasoning: "include_reasoning", - Reasoning: "reasoning", - ReasoningEffort: "reasoning_effort", - WebSearchOptions: "web_search_options", - Verbosity: "verbosity", + Temperature: 'temperature', + TopP: 'top_p', + TopK: 'top_k', + MinP: 'min_p', + TopA: 'top_a', + FrequencyPenalty: 'frequency_penalty', + PresencePenalty: 'presence_penalty', + RepetitionPenalty: 'repetition_penalty', + MaxTokens: 'max_tokens', + LogitBias: 'logit_bias', + Logprobs: 'logprobs', + TopLogprobs: 'top_logprobs', + Seed: 'seed', + ResponseFormat: 'response_format', + StructuredOutputs: 'structured_outputs', + Stop: 'stop', + Tools: 'tools', + ToolChoice: 'tool_choice', + ParallelToolCalls: 'parallel_tool_calls', + IncludeReasoning: 'include_reasoning', + Reasoning: 'reasoning', + ReasoningEffort: 'reasoning_effort', + WebSearchOptions: 'web_search_options', + Verbosity: 'verbosity', } as const; export type SupportedParameter = OpenEnum; @@ -87,12 +88,8 @@ export const GetParametersSecurity$outboundSchema: z.ZodType< bearer: z.string(), }); -export function getParametersSecurityToJSON( - getParametersSecurity: GetParametersSecurity, -): string { - return JSON.stringify( - GetParametersSecurity$outboundSchema.parse(getParametersSecurity), - ); +export function getParametersSecurityToJSON(getParametersSecurity: GetParametersSecurity): string { + return JSON.stringify(GetParametersSecurity$outboundSchema.parse(getParametersSecurity)); } /** @internal */ @@ -112,32 +109,25 @@ export const GetParametersRequest$outboundSchema: z.ZodType< provider: models.ProviderName$outboundSchema.optional(), }); -export function getParametersRequestToJSON( - getParametersRequest: GetParametersRequest, -): string { - return JSON.stringify( - GetParametersRequest$outboundSchema.parse(getParametersRequest), - ); +export function getParametersRequestToJSON(getParametersRequest: GetParametersRequest): string { + return JSON.stringify(GetParametersRequest$outboundSchema.parse(getParametersRequest)); } /** @internal */ -export const SupportedParameter$inboundSchema: z.ZodType< - SupportedParameter, - unknown -> = openEnums.inboundSchema(SupportedParameter); +export const SupportedParameter$inboundSchema: z.ZodType = + openEnums.inboundSchema(SupportedParameter); /** @internal */ -export const GetParametersData$inboundSchema: z.ZodType< - GetParametersData, - unknown -> = z.object({ - model: z.string(), - supported_parameters: z.array(SupportedParameter$inboundSchema), -}).transform((v) => { - return remap$(v, { - "supported_parameters": "supportedParameters", +export const GetParametersData$inboundSchema: z.ZodType = z + .object({ + model: z.string(), + supported_parameters: z.array(SupportedParameter$inboundSchema), + }) + .transform((v) => { + return remap$(v, { + supported_parameters: 'supportedParameters', + }); }); -}); export function getParametersDataFromJSON( jsonString: string, @@ -150,12 +140,10 @@ export function getParametersDataFromJSON( } /** @internal */ -export const GetParametersResponse$inboundSchema: z.ZodType< - GetParametersResponse, - unknown -> = z.object({ - data: z.lazy(() => GetParametersData$inboundSchema), -}); +export const GetParametersResponse$inboundSchema: z.ZodType = + z.object({ + data: z.lazy(() => GetParametersData$inboundSchema), + }); export function getParametersResponseFromJSON( jsonString: string, diff --git a/src/models/operations/getuseractivity.ts b/src/models/operations/getuseractivity.ts index fa427fbd..8c9dbc87 100644 --- a/src/models/operations/getuseractivity.ts +++ b/src/models/operations/getuseractivity.ts @@ -3,11 +3,12 @@ * @generated-id: 19535b4511a4 */ -import * as z from "zod/v4"; -import { safeParse } from "../../lib/schemas.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; -import * as models from "../index.js"; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../../lib/schemas.js'; +import * as models from '../index.js'; export type GetUserActivityRequest = { /** @@ -42,18 +43,14 @@ export const GetUserActivityRequest$outboundSchema: z.ZodType< export function getUserActivityRequestToJSON( getUserActivityRequest: GetUserActivityRequest, ): string { - return JSON.stringify( - GetUserActivityRequest$outboundSchema.parse(getUserActivityRequest), - ); + return JSON.stringify(GetUserActivityRequest$outboundSchema.parse(getUserActivityRequest)); } /** @internal */ -export const GetUserActivityResponse$inboundSchema: z.ZodType< - GetUserActivityResponse, - unknown -> = z.object({ - data: z.array(models.ActivityItem$inboundSchema), -}); +export const GetUserActivityResponse$inboundSchema: z.ZodType = + z.object({ + data: z.array(models.ActivityItem$inboundSchema), + }); export function getUserActivityResponseFromJSON( jsonString: string, diff --git a/src/models/operations/index.ts b/src/models/operations/index.ts index 5293b341..4d037807 100644 --- a/src/models/operations/index.ts +++ b/src/models/operations/index.ts @@ -3,24 +3,24 @@ * @generated-id: 0d9ffaf774d2 */ -export * from "./createauthkeyscode.js"; -export * from "./createcoinbasecharge.js"; -export * from "./createembeddings.js"; -export * from "./createkeys.js"; -export * from "./createresponses.js"; -export * from "./deletekeys.js"; -export * from "./exchangeauthcodeforapikey.js"; -export * from "./getcredits.js"; -export * from "./getcurrentkey.js"; -export * from "./getgeneration.js"; -export * from "./getkey.js"; -export * from "./getmodels.js"; -export * from "./getparameters.js"; -export * from "./getuseractivity.js"; -export * from "./list.js"; -export * from "./listendpoints.js"; -export * from "./listendpointszdr.js"; -export * from "./listmodelsuser.js"; -export * from "./listproviders.js"; -export * from "./sendchatcompletionrequest.js"; -export * from "./updatekeys.js"; +export * from './createauthkeyscode.js'; +export * from './createcoinbasecharge.js'; +export * from './createembeddings.js'; +export * from './createkeys.js'; +export * from './createresponses.js'; +export * from './deletekeys.js'; +export * from './exchangeauthcodeforapikey.js'; +export * from './getcredits.js'; +export * from './getcurrentkey.js'; +export * from './getgeneration.js'; +export * from './getkey.js'; +export * from './getmodels.js'; +export * from './getparameters.js'; +export * from './getuseractivity.js'; +export * from './list.js'; +export * from './listendpoints.js'; +export * from './listendpointszdr.js'; +export * from './listmodelsuser.js'; +export * from './listproviders.js'; +export * from './sendchatcompletionrequest.js'; +export * from './updatekeys.js'; diff --git a/src/models/operations/list.ts b/src/models/operations/list.ts index 64016f5b..a7fd7154 100644 --- a/src/models/operations/list.ts +++ b/src/models/operations/list.ts @@ -3,11 +3,12 @@ * @generated-id: ce11386ad30f */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import { safeParse } from "../../lib/schemas.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import { safeParse } from '../../lib/schemas.js'; export type ListRequest = { /** @@ -116,62 +117,69 @@ export type ListRequest$Outbound = { }; /** @internal */ -export const ListRequest$outboundSchema: z.ZodType< - ListRequest$Outbound, - ListRequest -> = z.object({ - includeDisabled: z.string().optional(), - offset: z.string().optional(), -}).transform((v) => { - return remap$(v, { - includeDisabled: "include_disabled", +export const ListRequest$outboundSchema: z.ZodType = z + .object({ + includeDisabled: z.string().optional(), + offset: z.string().optional(), + }) + .transform((v) => { + return remap$(v, { + includeDisabled: 'include_disabled', + }); }); -}); export function listRequestToJSON(listRequest: ListRequest): string { return JSON.stringify(ListRequest$outboundSchema.parse(listRequest)); } /** @internal */ -export const ListData$inboundSchema: z.ZodType = z.object({ - hash: z.string(), - name: z.string(), - label: z.string(), - disabled: z.boolean(), - limit: z.nullable(z.number()), - limit_remaining: z.nullable(z.number()), - limit_reset: z.nullable(z.string()), - include_byok_in_limit: z.boolean(), - usage: z.number(), - usage_daily: z.number(), - usage_weekly: z.number(), - usage_monthly: z.number(), - byok_usage: z.number(), - byok_usage_daily: z.number(), - byok_usage_weekly: z.number(), - byok_usage_monthly: z.number(), - created_at: z.string(), - updated_at: z.nullable(z.string()), - expires_at: z.nullable( - z.iso.datetime({ offset: true }).transform(v => new Date(v)), - ).optional(), -}).transform((v) => { - return remap$(v, { - "limit_remaining": "limitRemaining", - "limit_reset": "limitReset", - "include_byok_in_limit": "includeByokInLimit", - "usage_daily": "usageDaily", - "usage_weekly": "usageWeekly", - "usage_monthly": "usageMonthly", - "byok_usage": "byokUsage", - "byok_usage_daily": "byokUsageDaily", - "byok_usage_weekly": "byokUsageWeekly", - "byok_usage_monthly": "byokUsageMonthly", - "created_at": "createdAt", - "updated_at": "updatedAt", - "expires_at": "expiresAt", +export const ListData$inboundSchema: z.ZodType = z + .object({ + hash: z.string(), + name: z.string(), + label: z.string(), + disabled: z.boolean(), + limit: z.nullable(z.number()), + limit_remaining: z.nullable(z.number()), + limit_reset: z.nullable(z.string()), + include_byok_in_limit: z.boolean(), + usage: z.number(), + usage_daily: z.number(), + usage_weekly: z.number(), + usage_monthly: z.number(), + byok_usage: z.number(), + byok_usage_daily: z.number(), + byok_usage_weekly: z.number(), + byok_usage_monthly: z.number(), + created_at: z.string(), + updated_at: z.nullable(z.string()), + expires_at: z + .nullable( + z.iso + .datetime({ + offset: true, + }) + .transform((v) => new Date(v)), + ) + .optional(), + }) + .transform((v) => { + return remap$(v, { + limit_remaining: 'limitRemaining', + limit_reset: 'limitReset', + include_byok_in_limit: 'includeByokInLimit', + usage_daily: 'usageDaily', + usage_weekly: 'usageWeekly', + usage_monthly: 'usageMonthly', + byok_usage: 'byokUsage', + byok_usage_daily: 'byokUsageDaily', + byok_usage_weekly: 'byokUsageWeekly', + byok_usage_monthly: 'byokUsageMonthly', + created_at: 'createdAt', + updated_at: 'updatedAt', + expires_at: 'expiresAt', + }); }); -}); export function listDataFromJSON( jsonString: string, @@ -184,10 +192,9 @@ export function listDataFromJSON( } /** @internal */ -export const ListResponse$inboundSchema: z.ZodType = z - .object({ - data: z.array(z.lazy(() => ListData$inboundSchema)), - }); +export const ListResponse$inboundSchema: z.ZodType = z.object({ + data: z.array(z.lazy(() => ListData$inboundSchema)), +}); export function listResponseFromJSON( jsonString: string, diff --git a/src/models/operations/listendpoints.ts b/src/models/operations/listendpoints.ts index de8fe54b..e12ea902 100644 --- a/src/models/operations/listendpoints.ts +++ b/src/models/operations/listendpoints.ts @@ -3,11 +3,12 @@ * @generated-id: 253a81bc10af */ -import * as z from "zod/v4"; -import { safeParse } from "../../lib/schemas.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; -import * as models from "../index.js"; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../../lib/schemas.js'; +import * as models from '../index.js'; export type ListEndpointsRequest = { author: string; @@ -39,21 +40,15 @@ export const ListEndpointsRequest$outboundSchema: z.ZodType< slug: z.string(), }); -export function listEndpointsRequestToJSON( - listEndpointsRequest: ListEndpointsRequest, -): string { - return JSON.stringify( - ListEndpointsRequest$outboundSchema.parse(listEndpointsRequest), - ); +export function listEndpointsRequestToJSON(listEndpointsRequest: ListEndpointsRequest): string { + return JSON.stringify(ListEndpointsRequest$outboundSchema.parse(listEndpointsRequest)); } /** @internal */ -export const ListEndpointsResponse$inboundSchema: z.ZodType< - ListEndpointsResponse, - unknown -> = z.object({ - data: models.ListEndpointsResponse$inboundSchema, -}); +export const ListEndpointsResponse$inboundSchema: z.ZodType = + z.object({ + data: models.ListEndpointsResponse$inboundSchema, + }); export function listEndpointsResponseFromJSON( jsonString: string, diff --git a/src/models/operations/listendpointszdr.ts b/src/models/operations/listendpointszdr.ts index 9cbbeba4..ea21f0b4 100644 --- a/src/models/operations/listendpointszdr.ts +++ b/src/models/operations/listendpointszdr.ts @@ -3,11 +3,12 @@ * @generated-id: d52e6aeefb5e */ -import * as z from "zod/v4"; -import { safeParse } from "../../lib/schemas.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; -import * as models from "../index.js"; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../../lib/schemas.js'; +import * as models from '../index.js'; /** * Returns a list of endpoints @@ -17,12 +18,10 @@ export type ListEndpointsZdrResponse = { }; /** @internal */ -export const ListEndpointsZdrResponse$inboundSchema: z.ZodType< - ListEndpointsZdrResponse, - unknown -> = z.object({ - data: z.array(models.PublicEndpoint$inboundSchema), -}); +export const ListEndpointsZdrResponse$inboundSchema: z.ZodType = + z.object({ + data: z.array(models.PublicEndpoint$inboundSchema), + }); export function listEndpointsZdrResponseFromJSON( jsonString: string, diff --git a/src/models/operations/listmodelsuser.ts b/src/models/operations/listmodelsuser.ts index c0201c38..1436c8a0 100644 --- a/src/models/operations/listmodelsuser.ts +++ b/src/models/operations/listmodelsuser.ts @@ -3,7 +3,7 @@ * @generated-id: 0846aac6be02 */ -import * as z from "zod/v4"; +import * as z from 'zod/v4'; export type ListModelsUserSecurity = { bearer: string; @@ -25,7 +25,5 @@ export const ListModelsUserSecurity$outboundSchema: z.ZodType< export function listModelsUserSecurityToJSON( listModelsUserSecurity: ListModelsUserSecurity, ): string { - return JSON.stringify( - ListModelsUserSecurity$outboundSchema.parse(listModelsUserSecurity), - ); + return JSON.stringify(ListModelsUserSecurity$outboundSchema.parse(listModelsUserSecurity)); } diff --git a/src/models/operations/listproviders.ts b/src/models/operations/listproviders.ts index 45baf6eb..5f540533 100644 --- a/src/models/operations/listproviders.ts +++ b/src/models/operations/listproviders.ts @@ -3,11 +3,12 @@ * @generated-id: 76a35169de06 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import { safeParse } from "../../lib/schemas.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import { safeParse } from '../../lib/schemas.js'; export type ListProvidersData = { /** @@ -40,22 +41,21 @@ export type ListProvidersResponse = { }; /** @internal */ -export const ListProvidersData$inboundSchema: z.ZodType< - ListProvidersData, - unknown -> = z.object({ - name: z.string(), - slug: z.string(), - privacy_policy_url: z.nullable(z.string()), - terms_of_service_url: z.nullable(z.string()).optional(), - status_page_url: z.nullable(z.string()).optional(), -}).transform((v) => { - return remap$(v, { - "privacy_policy_url": "privacyPolicyUrl", - "terms_of_service_url": "termsOfServiceUrl", - "status_page_url": "statusPageUrl", +export const ListProvidersData$inboundSchema: z.ZodType = z + .object({ + name: z.string(), + slug: z.string(), + privacy_policy_url: z.nullable(z.string()), + terms_of_service_url: z.nullable(z.string()).optional(), + status_page_url: z.nullable(z.string()).optional(), + }) + .transform((v) => { + return remap$(v, { + privacy_policy_url: 'privacyPolicyUrl', + terms_of_service_url: 'termsOfServiceUrl', + status_page_url: 'statusPageUrl', + }); }); -}); export function listProvidersDataFromJSON( jsonString: string, @@ -68,12 +68,10 @@ export function listProvidersDataFromJSON( } /** @internal */ -export const ListProvidersResponse$inboundSchema: z.ZodType< - ListProvidersResponse, - unknown -> = z.object({ - data: z.array(z.lazy(() => ListProvidersData$inboundSchema)), -}); +export const ListProvidersResponse$inboundSchema: z.ZodType = + z.object({ + data: z.array(z.lazy(() => ListProvidersData$inboundSchema)), + }); export function listProvidersResponseFromJSON( jsonString: string, diff --git a/src/models/operations/sendchatcompletionrequest.ts b/src/models/operations/sendchatcompletionrequest.ts index 80091bf5..e9c04b9f 100644 --- a/src/models/operations/sendchatcompletionrequest.ts +++ b/src/models/operations/sendchatcompletionrequest.ts @@ -3,12 +3,13 @@ * @generated-id: 52a55a780d2d */ -import * as z from "zod/v4"; -import { EventStream } from "../../lib/event-streams.js"; -import { safeParse } from "../../lib/schemas.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; -import * as models from "../index.js"; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { EventStream } from '../../lib/event-streams.js'; +import { safeParse } from '../../lib/schemas.js'; +import * as models from '../index.js'; export type SendChatCompletionRequestResponse = | models.ChatResponse @@ -20,13 +21,16 @@ export const SendChatCompletionRequestResponse$inboundSchema: z.ZodType< unknown > = z.union([ models.ChatResponse$inboundSchema, - z.custom>(x => x instanceof ReadableStream) - .transform(stream => { - return new EventStream(stream, rawEvent => { - if (rawEvent.data === "[DONE]") return { done: true }; + z + .custom>((x) => x instanceof ReadableStream) + .transform((stream) => { + return new EventStream(stream, (rawEvent) => { + if (rawEvent.data === '[DONE]') + return { + done: true, + }; return { - value: models.ChatStreamingResponseChunk$inboundSchema.parse(rawEvent) - ?.data, + value: models.ChatStreamingResponseChunk$inboundSchema.parse(rawEvent)?.data, }; }); }), diff --git a/src/models/operations/updatekeys.ts b/src/models/operations/updatekeys.ts index 2cfcfae8..3123f6c4 100644 --- a/src/models/operations/updatekeys.ts +++ b/src/models/operations/updatekeys.ts @@ -3,21 +3,22 @@ * @generated-id: 30a0942aa2b9 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../../lib/primitives.js"; -import { safeParse } from "../../lib/schemas.js"; -import * as openEnums from "../../types/enums.js"; -import { OpenEnum } from "../../types/enums.js"; -import { Result as SafeParseResult } from "../../types/fp.js"; -import { SDKValidationError } from "../errors/sdkvalidationerror.js"; +import type { OpenEnum } from '../../types/enums.js'; +import type { Result as SafeParseResult } from '../../types/fp.js'; +import type { SDKValidationError } from '../errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../../lib/primitives.js'; +import { safeParse } from '../../lib/schemas.js'; +import * as openEnums from '../../types/enums.js'; /** * New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. */ export const UpdateKeysLimitReset = { - Daily: "daily", - Weekly: "weekly", - Monthly: "monthly", + Daily: 'daily', + Weekly: 'weekly', + Monthly: 'monthly', } as const; /** * New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. @@ -148,10 +149,8 @@ export type UpdateKeysResponse = { }; /** @internal */ -export const UpdateKeysLimitReset$outboundSchema: z.ZodType< - string, - UpdateKeysLimitReset -> = openEnums.outboundSchema(UpdateKeysLimitReset); +export const UpdateKeysLimitReset$outboundSchema: z.ZodType = + openEnums.outboundSchema(UpdateKeysLimitReset); /** @internal */ export type UpdateKeysRequestBody$Outbound = { @@ -166,25 +165,23 @@ export type UpdateKeysRequestBody$Outbound = { export const UpdateKeysRequestBody$outboundSchema: z.ZodType< UpdateKeysRequestBody$Outbound, UpdateKeysRequestBody -> = z.object({ - name: z.string().optional(), - disabled: z.boolean().optional(), - limit: z.nullable(z.number()).optional(), - limitReset: z.nullable(UpdateKeysLimitReset$outboundSchema).optional(), - includeByokInLimit: z.boolean().optional(), -}).transform((v) => { - return remap$(v, { - limitReset: "limit_reset", - includeByokInLimit: "include_byok_in_limit", +> = z + .object({ + name: z.string().optional(), + disabled: z.boolean().optional(), + limit: z.nullable(z.number()).optional(), + limitReset: z.nullable(UpdateKeysLimitReset$outboundSchema).optional(), + includeByokInLimit: z.boolean().optional(), + }) + .transform((v) => { + return remap$(v, { + limitReset: 'limit_reset', + includeByokInLimit: 'include_byok_in_limit', + }); }); -}); -export function updateKeysRequestBodyToJSON( - updateKeysRequestBody: UpdateKeysRequestBody, -): string { - return JSON.stringify( - UpdateKeysRequestBody$outboundSchema.parse(updateKeysRequestBody), - ); +export function updateKeysRequestBodyToJSON(updateKeysRequestBody: UpdateKeysRequestBody): string { + return JSON.stringify(UpdateKeysRequestBody$outboundSchema.parse(updateKeysRequestBody)); } /** @internal */ @@ -197,26 +194,24 @@ export type UpdateKeysRequest$Outbound = { export const UpdateKeysRequest$outboundSchema: z.ZodType< UpdateKeysRequest$Outbound, UpdateKeysRequest -> = z.object({ - hash: z.string(), - requestBody: z.lazy(() => UpdateKeysRequestBody$outboundSchema), -}).transform((v) => { - return remap$(v, { - requestBody: "RequestBody", +> = z + .object({ + hash: z.string(), + requestBody: z.lazy(() => UpdateKeysRequestBody$outboundSchema), + }) + .transform((v) => { + return remap$(v, { + requestBody: 'RequestBody', + }); }); -}); -export function updateKeysRequestToJSON( - updateKeysRequest: UpdateKeysRequest, -): string { - return JSON.stringify( - UpdateKeysRequest$outboundSchema.parse(updateKeysRequest), - ); +export function updateKeysRequestToJSON(updateKeysRequest: UpdateKeysRequest): string { + return JSON.stringify(UpdateKeysRequest$outboundSchema.parse(updateKeysRequest)); } /** @internal */ -export const UpdateKeysData$inboundSchema: z.ZodType = - z.object({ +export const UpdateKeysData$inboundSchema: z.ZodType = z + .object({ hash: z.string(), name: z.string(), label: z.string(), @@ -235,24 +230,31 @@ export const UpdateKeysData$inboundSchema: z.ZodType = byok_usage_monthly: z.number(), created_at: z.string(), updated_at: z.nullable(z.string()), - expires_at: z.nullable( - z.iso.datetime({ offset: true }).transform(v => new Date(v)), - ).optional(), - }).transform((v) => { + expires_at: z + .nullable( + z.iso + .datetime({ + offset: true, + }) + .transform((v) => new Date(v)), + ) + .optional(), + }) + .transform((v) => { return remap$(v, { - "limit_remaining": "limitRemaining", - "limit_reset": "limitReset", - "include_byok_in_limit": "includeByokInLimit", - "usage_daily": "usageDaily", - "usage_weekly": "usageWeekly", - "usage_monthly": "usageMonthly", - "byok_usage": "byokUsage", - "byok_usage_daily": "byokUsageDaily", - "byok_usage_weekly": "byokUsageWeekly", - "byok_usage_monthly": "byokUsageMonthly", - "created_at": "createdAt", - "updated_at": "updatedAt", - "expires_at": "expiresAt", + limit_remaining: 'limitRemaining', + limit_reset: 'limitReset', + include_byok_in_limit: 'includeByokInLimit', + usage_daily: 'usageDaily', + usage_weekly: 'usageWeekly', + usage_monthly: 'usageMonthly', + byok_usage: 'byokUsage', + byok_usage_daily: 'byokUsageDaily', + byok_usage_weekly: 'byokUsageWeekly', + byok_usage_monthly: 'byokUsageMonthly', + created_at: 'createdAt', + updated_at: 'updatedAt', + expires_at: 'expiresAt', }); }); @@ -267,10 +269,7 @@ export function updateKeysDataFromJSON( } /** @internal */ -export const UpdateKeysResponse$inboundSchema: z.ZodType< - UpdateKeysResponse, - unknown -> = z.object({ +export const UpdateKeysResponse$inboundSchema: z.ZodType = z.object({ data: z.lazy(() => UpdateKeysData$inboundSchema), }); diff --git a/src/models/outputitemimagegenerationcall.ts b/src/models/outputitemimagegenerationcall.ts index 1a292f67..0445c647 100644 --- a/src/models/outputitemimagegenerationcall.ts +++ b/src/models/outputitemimagegenerationcall.ts @@ -3,18 +3,17 @@ * @generated-id: 9c3ac6a7a9ad */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { - ImageGenerationStatus, - ImageGenerationStatus$inboundSchema, -} from "./imagegenerationstatus.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { ImageGenerationStatus } from './imagegenerationstatus.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import { ImageGenerationStatus$inboundSchema } from './imagegenerationstatus.js'; export const OutputItemImageGenerationCallType = { - ImageGenerationCall: "image_generation_call", + ImageGenerationCall: 'image_generation_call', } as const; export type OutputItemImageGenerationCallType = ClosedEnum< typeof OutputItemImageGenerationCallType diff --git a/src/models/outputmessage.ts b/src/models/outputmessage.ts index 76b98b2c..8d053053 100644 --- a/src/models/outputmessage.ts +++ b/src/models/outputmessage.ts @@ -3,59 +3,48 @@ * @generated-id: fa128cf87d51 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { - OpenAIResponsesRefusalContent, - OpenAIResponsesRefusalContent$inboundSchema, -} from "./openairesponsesrefusalcontent.js"; -import { - ResponseOutputText, - ResponseOutputText$inboundSchema, -} from "./responseoutputtext.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { OpenAIResponsesRefusalContent } from './openairesponsesrefusalcontent.js'; +import type { ResponseOutputText } from './responseoutputtext.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import { OpenAIResponsesRefusalContent$inboundSchema } from './openairesponsesrefusalcontent.js'; +import { ResponseOutputText$inboundSchema } from './responseoutputtext.js'; export const OutputMessageRole = { - Assistant: "assistant", + Assistant: 'assistant', } as const; export type OutputMessageRole = ClosedEnum; export const OutputMessageType = { - Message: "message", + Message: 'message', } as const; export type OutputMessageType = ClosedEnum; export const OutputMessageStatusInProgress = { - InProgress: "in_progress", + InProgress: 'in_progress', } as const; -export type OutputMessageStatusInProgress = ClosedEnum< - typeof OutputMessageStatusInProgress ->; +export type OutputMessageStatusInProgress = ClosedEnum; export const OutputMessageStatusIncomplete = { - Incomplete: "incomplete", + Incomplete: 'incomplete', } as const; -export type OutputMessageStatusIncomplete = ClosedEnum< - typeof OutputMessageStatusIncomplete ->; +export type OutputMessageStatusIncomplete = ClosedEnum; export const OutputMessageStatusCompleted = { - Completed: "completed", + Completed: 'completed', } as const; -export type OutputMessageStatusCompleted = ClosedEnum< - typeof OutputMessageStatusCompleted ->; +export type OutputMessageStatusCompleted = ClosedEnum; export type OutputMessageStatusUnion = | OutputMessageStatusCompleted | OutputMessageStatusIncomplete | OutputMessageStatusInProgress; -export type OutputMessageContent = - | ResponseOutputText - | OpenAIResponsesRefusalContent; +export type OutputMessageContent = ResponseOutputText | OpenAIResponsesRefusalContent; export type OutputMessage = { id: string; @@ -70,14 +59,12 @@ export type OutputMessage = { }; /** @internal */ -export const OutputMessageRole$inboundSchema: z.ZodEnum< - typeof OutputMessageRole -> = z.enum(OutputMessageRole); +export const OutputMessageRole$inboundSchema: z.ZodEnum = + z.enum(OutputMessageRole); /** @internal */ -export const OutputMessageType$inboundSchema: z.ZodEnum< - typeof OutputMessageType -> = z.enum(OutputMessageType); +export const OutputMessageType$inboundSchema: z.ZodEnum = + z.enum(OutputMessageType); /** @internal */ export const OutputMessageStatusInProgress$inboundSchema: z.ZodEnum< @@ -95,14 +82,12 @@ export const OutputMessageStatusCompleted$inboundSchema: z.ZodEnum< > = z.enum(OutputMessageStatusCompleted); /** @internal */ -export const OutputMessageStatusUnion$inboundSchema: z.ZodType< - OutputMessageStatusUnion, - unknown -> = z.union([ - OutputMessageStatusCompleted$inboundSchema, - OutputMessageStatusIncomplete$inboundSchema, - OutputMessageStatusInProgress$inboundSchema, -]); +export const OutputMessageStatusUnion$inboundSchema: z.ZodType = + z.union([ + OutputMessageStatusCompleted$inboundSchema, + OutputMessageStatusIncomplete$inboundSchema, + OutputMessageStatusInProgress$inboundSchema, + ]); export function outputMessageStatusUnionFromJSON( jsonString: string, @@ -115,13 +100,12 @@ export function outputMessageStatusUnionFromJSON( } /** @internal */ -export const OutputMessageContent$inboundSchema: z.ZodType< - OutputMessageContent, - unknown -> = z.union([ - ResponseOutputText$inboundSchema, - OpenAIResponsesRefusalContent$inboundSchema, -]); +export const OutputMessageContent$inboundSchema: z.ZodType = z.union( + [ + ResponseOutputText$inboundSchema, + OpenAIResponsesRefusalContent$inboundSchema, + ], +); export function outputMessageContentFromJSON( jsonString: string, @@ -134,23 +118,24 @@ export function outputMessageContentFromJSON( } /** @internal */ -export const OutputMessage$inboundSchema: z.ZodType = z - .object({ - id: z.string(), - role: OutputMessageRole$inboundSchema, - type: OutputMessageType$inboundSchema, - status: z.union([ +export const OutputMessage$inboundSchema: z.ZodType = z.object({ + id: z.string(), + role: OutputMessageRole$inboundSchema, + type: OutputMessageType$inboundSchema, + status: z + .union([ OutputMessageStatusCompleted$inboundSchema, OutputMessageStatusIncomplete$inboundSchema, OutputMessageStatusInProgress$inboundSchema, - ]).optional(), - content: z.array( - z.union([ - ResponseOutputText$inboundSchema, - OpenAIResponsesRefusalContent$inboundSchema, - ]), - ), - }); + ]) + .optional(), + content: z.array( + z.union([ + ResponseOutputText$inboundSchema, + OpenAIResponsesRefusalContent$inboundSchema, + ]), + ), +}); export function outputMessageFromJSON( jsonString: string, diff --git a/src/models/outputmodality.ts b/src/models/outputmodality.ts index fa199361..6bbdc298 100644 --- a/src/models/outputmodality.ts +++ b/src/models/outputmodality.ts @@ -3,14 +3,15 @@ * @generated-id: 6b2d2af692c7 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const OutputModality = { - Text: "text", - Image: "image", - Embeddings: "embeddings", + Text: 'text', + Image: 'image', + Embeddings: 'embeddings', } as const; export type OutputModality = OpenEnum; diff --git a/src/models/parameter.ts b/src/models/parameter.ts index df6c3118..99c0fa74 100644 --- a/src/models/parameter.ts +++ b/src/models/parameter.ts @@ -3,38 +3,39 @@ * @generated-id: 066287ded212 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const Parameter = { - Temperature: "temperature", - TopP: "top_p", - TopK: "top_k", - MinP: "min_p", - TopA: "top_a", - FrequencyPenalty: "frequency_penalty", - PresencePenalty: "presence_penalty", - RepetitionPenalty: "repetition_penalty", - MaxTokens: "max_tokens", - LogitBias: "logit_bias", - Logprobs: "logprobs", - TopLogprobs: "top_logprobs", - Seed: "seed", - ResponseFormat: "response_format", - StructuredOutputs: "structured_outputs", - Stop: "stop", - Tools: "tools", - ToolChoice: "tool_choice", - ParallelToolCalls: "parallel_tool_calls", - IncludeReasoning: "include_reasoning", - Reasoning: "reasoning", - ReasoningEffort: "reasoning_effort", - WebSearchOptions: "web_search_options", - Verbosity: "verbosity", + Temperature: 'temperature', + TopP: 'top_p', + TopK: 'top_k', + MinP: 'min_p', + TopA: 'top_a', + FrequencyPenalty: 'frequency_penalty', + PresencePenalty: 'presence_penalty', + RepetitionPenalty: 'repetition_penalty', + MaxTokens: 'max_tokens', + LogitBias: 'logit_bias', + Logprobs: 'logprobs', + TopLogprobs: 'top_logprobs', + Seed: 'seed', + ResponseFormat: 'response_format', + StructuredOutputs: 'structured_outputs', + Stop: 'stop', + Tools: 'tools', + ToolChoice: 'tool_choice', + ParallelToolCalls: 'parallel_tool_calls', + IncludeReasoning: 'include_reasoning', + Reasoning: 'reasoning', + ReasoningEffort: 'reasoning_effort', + WebSearchOptions: 'web_search_options', + Verbosity: 'verbosity', } as const; export type Parameter = OpenEnum; /** @internal */ -export const Parameter$inboundSchema: z.ZodType = openEnums - .inboundSchema(Parameter); +export const Parameter$inboundSchema: z.ZodType = + openEnums.inboundSchema(Parameter); diff --git a/src/models/payloadtoolargeresponseerrordata.ts b/src/models/payloadtoolargeresponseerrordata.ts index 7be78556..0e4bb27e 100644 --- a/src/models/payloadtoolargeresponseerrordata.ts +++ b/src/models/payloadtoolargeresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: 59c2c424ea9b */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for PayloadTooLargeResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type PayloadTooLargeResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ diff --git a/src/models/paymentrequiredresponseerrordata.ts b/src/models/paymentrequiredresponseerrordata.ts index e11a0a71..363e8017 100644 --- a/src/models/paymentrequiredresponseerrordata.ts +++ b/src/models/paymentrequiredresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: b38a7e0e1166 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for PaymentRequiredResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type PaymentRequiredResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ diff --git a/src/models/pdfparserengine.ts b/src/models/pdfparserengine.ts index dcbfbed0..6e46b25f 100644 --- a/src/models/pdfparserengine.ts +++ b/src/models/pdfparserengine.ts @@ -3,17 +3,18 @@ * @generated-id: 3c0c5ac60652 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; /** * The engine to use for parsing PDF files. */ export const PDFParserEngine = { - MistralOcr: "mistral-ocr", - PdfText: "pdf-text", - Native: "native", + MistralOcr: 'mistral-ocr', + PdfText: 'pdf-text', + Native: 'native', } as const; /** * The engine to use for parsing PDF files. @@ -21,7 +22,5 @@ export const PDFParserEngine = { export type PDFParserEngine = OpenEnum; /** @internal */ -export const PDFParserEngine$outboundSchema: z.ZodType< - string, - PDFParserEngine -> = openEnums.outboundSchema(PDFParserEngine); +export const PDFParserEngine$outboundSchema: z.ZodType = + openEnums.outboundSchema(PDFParserEngine); diff --git a/src/models/pdfparseroptions.ts b/src/models/pdfparseroptions.ts index d32dc10b..ce8354d9 100644 --- a/src/models/pdfparseroptions.ts +++ b/src/models/pdfparseroptions.ts @@ -3,11 +3,10 @@ * @generated-id: 704f51d4a5f7 */ -import * as z from "zod/v4"; -import { - PDFParserEngine, - PDFParserEngine$outboundSchema, -} from "./pdfparserengine.js"; +import type { PDFParserEngine } from './pdfparserengine.js'; + +import * as z from 'zod/v4'; +import { PDFParserEngine$outboundSchema } from './pdfparserengine.js'; /** * Options for PDF parsing. @@ -32,10 +31,6 @@ export const PDFParserOptions$outboundSchema: z.ZodType< engine: PDFParserEngine$outboundSchema.optional(), }); -export function pdfParserOptionsToJSON( - pdfParserOptions: PDFParserOptions, -): string { - return JSON.stringify( - PDFParserOptions$outboundSchema.parse(pdfParserOptions), - ); +export function pdfParserOptionsToJSON(pdfParserOptions: PDFParserOptions): string { + return JSON.stringify(PDFParserOptions$outboundSchema.parse(pdfParserOptions)); } diff --git a/src/models/perrequestlimits.ts b/src/models/perrequestlimits.ts index a5bfb5dc..b7775e96 100644 --- a/src/models/perrequestlimits.ts +++ b/src/models/perrequestlimits.ts @@ -3,11 +3,12 @@ * @generated-id: 2b2b6cf6a019 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * Per-request token limits @@ -24,18 +25,17 @@ export type PerRequestLimits = { }; /** @internal */ -export const PerRequestLimits$inboundSchema: z.ZodType< - PerRequestLimits, - unknown -> = z.object({ - prompt_tokens: z.number(), - completion_tokens: z.number(), -}).transform((v) => { - return remap$(v, { - "prompt_tokens": "promptTokens", - "completion_tokens": "completionTokens", +export const PerRequestLimits$inboundSchema: z.ZodType = z + .object({ + prompt_tokens: z.number(), + completion_tokens: z.number(), + }) + .transform((v) => { + return remap$(v, { + prompt_tokens: 'promptTokens', + completion_tokens: 'completionTokens', + }); }); -}); export function perRequestLimitsFromJSON( jsonString: string, diff --git a/src/models/providername.ts b/src/models/providername.ts index db7996c0..0428cb33 100644 --- a/src/models/providername.ts +++ b/src/models/providername.ts @@ -3,80 +3,81 @@ * @generated-id: 89e536fb023a */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const ProviderName = { - Ai21: "AI21", - AionLabs: "AionLabs", - Alibaba: "Alibaba", - AmazonBedrock: "Amazon Bedrock", - AmazonNova: "Amazon Nova", - Anthropic: "Anthropic", - ArceeAI: "Arcee AI", - AtlasCloud: "AtlasCloud", - Avian: "Avian", - Azure: "Azure", - BaseTen: "BaseTen", - BytePlus: "BytePlus", - BlackForestLabs: "Black Forest Labs", - Cerebras: "Cerebras", - Chutes: "Chutes", - Cirrascale: "Cirrascale", - Clarifai: "Clarifai", - Cloudflare: "Cloudflare", - Cohere: "Cohere", - Crusoe: "Crusoe", - DeepInfra: "DeepInfra", - DeepSeek: "DeepSeek", - Featherless: "Featherless", - Fireworks: "Fireworks", - Friendli: "Friendli", - GMICloud: "GMICloud", - GoPomelo: "GoPomelo", - Google: "Google", - GoogleAIStudio: "Google AI Studio", - Groq: "Groq", - Hyperbolic: "Hyperbolic", - Inception: "Inception", - InferenceNet: "InferenceNet", - Infermatic: "Infermatic", - Inflection: "Inflection", - Liquid: "Liquid", - Mara: "Mara", - Mancer2: "Mancer 2", - Minimax: "Minimax", - ModelRun: "ModelRun", - Mistral: "Mistral", - Modular: "Modular", - MoonshotAI: "Moonshot AI", - Morph: "Morph", - NCompass: "NCompass", - Nebius: "Nebius", - NextBit: "NextBit", - Novita: "Novita", - Nvidia: "Nvidia", - OpenAI: "OpenAI", - OpenInference: "OpenInference", - Parasail: "Parasail", - Perplexity: "Perplexity", - Phala: "Phala", - Relace: "Relace", - SambaNova: "SambaNova", - SiliconFlow: "SiliconFlow", - Sourceful: "Sourceful", - Stealth: "Stealth", - StreamLake: "StreamLake", - Switchpoint: "Switchpoint", - Targon: "Targon", - Together: "Together", - Venice: "Venice", - WandB: "WandB", - Xiaomi: "Xiaomi", - XAI: "xAI", - ZAi: "Z.AI", - FakeProvider: "FakeProvider", + Ai21: 'AI21', + AionLabs: 'AionLabs', + Alibaba: 'Alibaba', + AmazonBedrock: 'Amazon Bedrock', + AmazonNova: 'Amazon Nova', + Anthropic: 'Anthropic', + ArceeAI: 'Arcee AI', + AtlasCloud: 'AtlasCloud', + Avian: 'Avian', + Azure: 'Azure', + BaseTen: 'BaseTen', + BytePlus: 'BytePlus', + BlackForestLabs: 'Black Forest Labs', + Cerebras: 'Cerebras', + Chutes: 'Chutes', + Cirrascale: 'Cirrascale', + Clarifai: 'Clarifai', + Cloudflare: 'Cloudflare', + Cohere: 'Cohere', + Crusoe: 'Crusoe', + DeepInfra: 'DeepInfra', + DeepSeek: 'DeepSeek', + Featherless: 'Featherless', + Fireworks: 'Fireworks', + Friendli: 'Friendli', + GMICloud: 'GMICloud', + GoPomelo: 'GoPomelo', + Google: 'Google', + GoogleAIStudio: 'Google AI Studio', + Groq: 'Groq', + Hyperbolic: 'Hyperbolic', + Inception: 'Inception', + InferenceNet: 'InferenceNet', + Infermatic: 'Infermatic', + Inflection: 'Inflection', + Liquid: 'Liquid', + Mara: 'Mara', + Mancer2: 'Mancer 2', + Minimax: 'Minimax', + ModelRun: 'ModelRun', + Mistral: 'Mistral', + Modular: 'Modular', + MoonshotAI: 'Moonshot AI', + Morph: 'Morph', + NCompass: 'NCompass', + Nebius: 'Nebius', + NextBit: 'NextBit', + Novita: 'Novita', + Nvidia: 'Nvidia', + OpenAI: 'OpenAI', + OpenInference: 'OpenInference', + Parasail: 'Parasail', + Perplexity: 'Perplexity', + Phala: 'Phala', + Relace: 'Relace', + SambaNova: 'SambaNova', + SiliconFlow: 'SiliconFlow', + Sourceful: 'Sourceful', + Stealth: 'Stealth', + StreamLake: 'StreamLake', + Switchpoint: 'Switchpoint', + Targon: 'Targon', + Together: 'Together', + Venice: 'Venice', + WandB: 'WandB', + Xiaomi: 'Xiaomi', + XAI: 'xAI', + ZAi: 'Z.AI', + FakeProvider: 'FakeProvider', } as const; export type ProviderName = OpenEnum; diff --git a/src/models/provideroverloadedresponseerrordata.ts b/src/models/provideroverloadedresponseerrordata.ts index a4299469..4833b9ff 100644 --- a/src/models/provideroverloadedresponseerrordata.ts +++ b/src/models/provideroverloadedresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: 379f1256314f */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for ProviderOverloadedResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type ProviderOverloadedResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ @@ -32,8 +38,7 @@ export function providerOverloadedResponseErrorDataFromJSON( ): SafeParseResult { return safeParse( jsonString, - (x) => - ProviderOverloadedResponseErrorData$inboundSchema.parse(JSON.parse(x)), + (x) => ProviderOverloadedResponseErrorData$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'ProviderOverloadedResponseErrorData' from JSON`, ); } diff --git a/src/models/providerpreferences.ts b/src/models/providerpreferences.ts index d783498d..0abb72f3 100644 --- a/src/models/providerpreferences.ts +++ b/src/models/providerpreferences.ts @@ -3,17 +3,19 @@ * @generated-id: 3a47295d7b91 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import * as openEnums from "../types/enums.js"; -import { ClosedEnum, OpenEnum } from "../types/enums.js"; -import { - DataCollection, - DataCollection$outboundSchema, -} from "./datacollection.js"; -import { ProviderName, ProviderName$outboundSchema } from "./providername.js"; -import { ProviderSort, ProviderSort$outboundSchema } from "./providersort.js"; -import { Quantization, Quantization$outboundSchema } from "./quantization.js"; +import type { ClosedEnum, OpenEnum } from '../types/enums.js'; +import type { DataCollection } from './datacollection.js'; +import type { ProviderName } from './providername.js'; +import type { ProviderSort } from './providersort.js'; +import type { Quantization } from './quantization.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import * as openEnums from '../types/enums.js'; +import { DataCollection$outboundSchema } from './datacollection.js'; +import { ProviderName$outboundSchema } from './providername.js'; +import { ProviderSort$outboundSchema } from './providersort.js'; +import { Quantization$outboundSchema } from './quantization.js'; export type ProviderPreferencesOrder = ProviderName | string; @@ -22,26 +24,24 @@ export type ProviderPreferencesOnly = ProviderName | string; export type ProviderPreferencesIgnore = ProviderName | string; export const SortEnum = { - Price: "price", - Throughput: "throughput", - Latency: "latency", + Price: 'price', + Throughput: 'throughput', + Latency: 'latency', } as const; export type SortEnum = OpenEnum; export const ProviderSortConfigEnum = { - Price: "price", - Throughput: "throughput", - Latency: "latency", + Price: 'price', + Throughput: 'throughput', + Latency: 'latency', } as const; export type ProviderSortConfigEnum = ClosedEnum; export const ProviderPreferencesPartition = { - Model: "model", - None: "none", + Model: 'model', + None: 'none', } as const; -export type ProviderPreferencesPartition = OpenEnum< - typeof ProviderPreferencesPartition ->; +export type ProviderPreferencesPartition = OpenEnum; export type ProviderPreferencesProviderSortConfig = { by?: ProviderSort | null | undefined; @@ -53,13 +53,11 @@ export type ProviderSortConfigUnion = | ProviderSortConfigEnum; export const ProviderPreferencesProviderSort = { - Price: "price", - Throughput: "throughput", - Latency: "latency", + Price: 'price', + Throughput: 'throughput', + Latency: 'latency', } as const; -export type ProviderPreferencesProviderSort = OpenEnum< - typeof ProviderPreferencesProviderSort ->; +export type ProviderPreferencesProviderSort = OpenEnum; /** * The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed. @@ -185,14 +183,15 @@ export type ProviderPreferencesOrder$Outbound = string | string; export const ProviderPreferencesOrder$outboundSchema: z.ZodType< ProviderPreferencesOrder$Outbound, ProviderPreferencesOrder -> = z.union([ProviderName$outboundSchema, z.string()]); +> = z.union([ + ProviderName$outboundSchema, + z.string(), +]); export function providerPreferencesOrderToJSON( providerPreferencesOrder: ProviderPreferencesOrder, ): string { - return JSON.stringify( - ProviderPreferencesOrder$outboundSchema.parse(providerPreferencesOrder), - ); + return JSON.stringify(ProviderPreferencesOrder$outboundSchema.parse(providerPreferencesOrder)); } /** @internal */ @@ -202,14 +201,15 @@ export type ProviderPreferencesOnly$Outbound = string | string; export const ProviderPreferencesOnly$outboundSchema: z.ZodType< ProviderPreferencesOnly$Outbound, ProviderPreferencesOnly -> = z.union([ProviderName$outboundSchema, z.string()]); +> = z.union([ + ProviderName$outboundSchema, + z.string(), +]); export function providerPreferencesOnlyToJSON( providerPreferencesOnly: ProviderPreferencesOnly, ): string { - return JSON.stringify( - ProviderPreferencesOnly$outboundSchema.parse(providerPreferencesOnly), - ); + return JSON.stringify(ProviderPreferencesOnly$outboundSchema.parse(providerPreferencesOnly)); } /** @internal */ @@ -219,24 +219,24 @@ export type ProviderPreferencesIgnore$Outbound = string | string; export const ProviderPreferencesIgnore$outboundSchema: z.ZodType< ProviderPreferencesIgnore$Outbound, ProviderPreferencesIgnore -> = z.union([ProviderName$outboundSchema, z.string()]); +> = z.union([ + ProviderName$outboundSchema, + z.string(), +]); export function providerPreferencesIgnoreToJSON( providerPreferencesIgnore: ProviderPreferencesIgnore, ): string { - return JSON.stringify( - ProviderPreferencesIgnore$outboundSchema.parse(providerPreferencesIgnore), - ); + return JSON.stringify(ProviderPreferencesIgnore$outboundSchema.parse(providerPreferencesIgnore)); } /** @internal */ -export const SortEnum$outboundSchema: z.ZodType = openEnums - .outboundSchema(SortEnum); +export const SortEnum$outboundSchema: z.ZodType = + openEnums.outboundSchema(SortEnum); /** @internal */ -export const ProviderSortConfigEnum$outboundSchema: z.ZodEnum< - typeof ProviderSortConfigEnum -> = z.enum(ProviderSortConfigEnum); +export const ProviderSortConfigEnum$outboundSchema: z.ZodEnum = + z.enum(ProviderSortConfigEnum); /** @internal */ export const ProviderPreferencesPartition$outboundSchema: z.ZodType< @@ -286,9 +286,7 @@ export const ProviderSortConfigUnion$outboundSchema: z.ZodType< export function providerSortConfigUnionToJSON( providerSortConfigUnion: ProviderSortConfigUnion, ): string { - return JSON.stringify( - ProviderSortConfigUnion$outboundSchema.parse(providerSortConfigUnion), - ); + return JSON.stringify(ProviderSortConfigUnion$outboundSchema.parse(providerSortConfigUnion)); } /** @internal */ @@ -321,9 +319,7 @@ export function providerPreferencesSortUnionToJSON( providerPreferencesSortUnion: ProviderPreferencesSortUnion, ): string { return JSON.stringify( - ProviderPreferencesSortUnion$outboundSchema.parse( - providerPreferencesSortUnion, - ), + ProviderPreferencesSortUnion$outboundSchema.parse(providerPreferencesSortUnion), ); } @@ -352,9 +348,7 @@ export function providerPreferencesMaxPriceToJSON( providerPreferencesMaxPrice: ProviderPreferencesMaxPrice, ): string { return JSON.stringify( - ProviderPreferencesMaxPrice$outboundSchema.parse( - providerPreferencesMaxPrice, - ), + ProviderPreferencesMaxPrice$outboundSchema.parse(providerPreferencesMaxPrice), ); } @@ -387,53 +381,76 @@ export type ProviderPreferences$Outbound = { export const ProviderPreferences$outboundSchema: z.ZodType< ProviderPreferences$Outbound, ProviderPreferences -> = z.object({ - allowFallbacks: z.nullable(z.boolean()).optional(), - requireParameters: z.nullable(z.boolean()).optional(), - dataCollection: z.nullable(DataCollection$outboundSchema).optional(), - zdr: z.nullable(z.boolean()).optional(), - enforceDistillableText: z.nullable(z.boolean()).optional(), - order: z.nullable(z.array(z.union([ProviderName$outboundSchema, z.string()]))) - .optional(), - only: z.nullable(z.array(z.union([ProviderName$outboundSchema, z.string()]))) - .optional(), - ignore: z.nullable( - z.array(z.union([ProviderName$outboundSchema, z.string()])), - ).optional(), - quantizations: z.nullable(z.array(Quantization$outboundSchema)).optional(), - sort: z.nullable( - z.union([ - ProviderPreferencesProviderSort$outboundSchema, - z.union([ - z.lazy(() => ProviderPreferencesProviderSortConfig$outboundSchema), - ProviderSortConfigEnum$outboundSchema, - ]), - SortEnum$outboundSchema, - ]), - ).optional(), - maxPrice: z.lazy(() => ProviderPreferencesMaxPrice$outboundSchema).optional(), - preferredMinThroughput: z.nullable(z.number()).optional(), - preferredMaxLatency: z.nullable(z.number()).optional(), - minThroughput: z.nullable(z.number()).optional(), - maxLatency: z.nullable(z.number()).optional(), -}).transform((v) => { - return remap$(v, { - allowFallbacks: "allow_fallbacks", - requireParameters: "require_parameters", - dataCollection: "data_collection", - enforceDistillableText: "enforce_distillable_text", - maxPrice: "max_price", - preferredMinThroughput: "preferred_min_throughput", - preferredMaxLatency: "preferred_max_latency", - minThroughput: "min_throughput", - maxLatency: "max_latency", +> = z + .object({ + allowFallbacks: z.nullable(z.boolean()).optional(), + requireParameters: z.nullable(z.boolean()).optional(), + dataCollection: z.nullable(DataCollection$outboundSchema).optional(), + zdr: z.nullable(z.boolean()).optional(), + enforceDistillableText: z.nullable(z.boolean()).optional(), + order: z + .nullable( + z.array( + z.union([ + ProviderName$outboundSchema, + z.string(), + ]), + ), + ) + .optional(), + only: z + .nullable( + z.array( + z.union([ + ProviderName$outboundSchema, + z.string(), + ]), + ), + ) + .optional(), + ignore: z + .nullable( + z.array( + z.union([ + ProviderName$outboundSchema, + z.string(), + ]), + ), + ) + .optional(), + quantizations: z.nullable(z.array(Quantization$outboundSchema)).optional(), + sort: z + .nullable( + z.union([ + ProviderPreferencesProviderSort$outboundSchema, + z.union([ + z.lazy(() => ProviderPreferencesProviderSortConfig$outboundSchema), + ProviderSortConfigEnum$outboundSchema, + ]), + SortEnum$outboundSchema, + ]), + ) + .optional(), + maxPrice: z.lazy(() => ProviderPreferencesMaxPrice$outboundSchema).optional(), + preferredMinThroughput: z.nullable(z.number()).optional(), + preferredMaxLatency: z.nullable(z.number()).optional(), + minThroughput: z.nullable(z.number()).optional(), + maxLatency: z.nullable(z.number()).optional(), + }) + .transform((v) => { + return remap$(v, { + allowFallbacks: 'allow_fallbacks', + requireParameters: 'require_parameters', + dataCollection: 'data_collection', + enforceDistillableText: 'enforce_distillable_text', + maxPrice: 'max_price', + preferredMinThroughput: 'preferred_min_throughput', + preferredMaxLatency: 'preferred_max_latency', + minThroughput: 'min_throughput', + maxLatency: 'max_latency', + }); }); -}); -export function providerPreferencesToJSON( - providerPreferences: ProviderPreferences, -): string { - return JSON.stringify( - ProviderPreferences$outboundSchema.parse(providerPreferences), - ); +export function providerPreferencesToJSON(providerPreferences: ProviderPreferences): string { + return JSON.stringify(ProviderPreferences$outboundSchema.parse(providerPreferences)); } diff --git a/src/models/providersort.ts b/src/models/providersort.ts index 2d28a616..2502ac82 100644 --- a/src/models/providersort.ts +++ b/src/models/providersort.ts @@ -3,14 +3,15 @@ * @generated-id: 7d1e919d1ec3 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const ProviderSort = { - Price: "price", - Throughput: "throughput", - Latency: "latency", + Price: 'price', + Throughput: 'throughput', + Latency: 'latency', } as const; export type ProviderSort = OpenEnum; diff --git a/src/models/providersortconfig.ts b/src/models/providersortconfig.ts index 56f70b24..afe17060 100644 --- a/src/models/providersortconfig.ts +++ b/src/models/providersortconfig.ts @@ -3,14 +3,16 @@ * @generated-id: 1491329aae16 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { ProviderSort, ProviderSort$outboundSchema } from "./providersort.js"; +import type { OpenEnum } from '../types/enums.js'; +import type { ProviderSort } from './providersort.js'; + +import * as z from 'zod/v4'; +import * as openEnums from '../types/enums.js'; +import { ProviderSort$outboundSchema } from './providersort.js'; export const Partition = { - Model: "model", - None: "none", + Model: 'model', + None: 'none', } as const; export type Partition = OpenEnum; @@ -20,8 +22,8 @@ export type ProviderSortConfig = { }; /** @internal */ -export const Partition$outboundSchema: z.ZodType = openEnums - .outboundSchema(Partition); +export const Partition$outboundSchema: z.ZodType = + openEnums.outboundSchema(Partition); /** @internal */ export type ProviderSortConfig$Outbound = { @@ -38,10 +40,6 @@ export const ProviderSortConfig$outboundSchema: z.ZodType< partition: z.nullable(Partition$outboundSchema).optional(), }); -export function providerSortConfigToJSON( - providerSortConfig: ProviderSortConfig, -): string { - return JSON.stringify( - ProviderSortConfig$outboundSchema.parse(providerSortConfig), - ); +export function providerSortConfigToJSON(providerSortConfig: ProviderSortConfig): string { + return JSON.stringify(ProviderSortConfig$outboundSchema.parse(providerSortConfig)); } diff --git a/src/models/providersortunion.ts b/src/models/providersortunion.ts index ab212a4c..dbc4a820 100644 --- a/src/models/providersortunion.ts +++ b/src/models/providersortunion.ts @@ -3,13 +3,12 @@ * @generated-id: 7a2d23baab80 */ -import * as z from "zod/v4"; -import { ProviderSort, ProviderSort$outboundSchema } from "./providersort.js"; -import { - ProviderSortConfig, - ProviderSortConfig$Outbound, - ProviderSortConfig$outboundSchema, -} from "./providersortconfig.js"; +import type { ProviderSort } from './providersort.js'; +import type { ProviderSortConfig, ProviderSortConfig$Outbound } from './providersortconfig.js'; + +import * as z from 'zod/v4'; +import { ProviderSort$outboundSchema } from './providersort.js'; +import { ProviderSortConfig$outboundSchema } from './providersortconfig.js'; export type ProviderSortUnion = ProviderSort | ProviderSortConfig; @@ -20,12 +19,11 @@ export type ProviderSortUnion$Outbound = string | ProviderSortConfig$Outbound; export const ProviderSortUnion$outboundSchema: z.ZodType< ProviderSortUnion$Outbound, ProviderSortUnion -> = z.union([ProviderSort$outboundSchema, ProviderSortConfig$outboundSchema]); +> = z.union([ + ProviderSort$outboundSchema, + ProviderSortConfig$outboundSchema, +]); -export function providerSortUnionToJSON( - providerSortUnion: ProviderSortUnion, -): string { - return JSON.stringify( - ProviderSortUnion$outboundSchema.parse(providerSortUnion), - ); +export function providerSortUnionToJSON(providerSortUnion: ProviderSortUnion): string { + return JSON.stringify(ProviderSortUnion$outboundSchema.parse(providerSortUnion)); } diff --git a/src/models/publicendpoint.ts b/src/models/publicendpoint.ts index 23f47a30..95e3d083 100644 --- a/src/models/publicendpoint.ts +++ b/src/models/publicendpoint.ts @@ -3,19 +3,20 @@ * @generated-id: 396ce3186017 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { - EndpointStatus, - EndpointStatus$inboundSchema, -} from "./endpointstatus.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { Parameter, Parameter$inboundSchema } from "./parameter.js"; -import { ProviderName, ProviderName$inboundSchema } from "./providername.js"; +import type { OpenEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { EndpointStatus } from './endpointstatus.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { Parameter } from './parameter.js'; +import type { ProviderName } from './providername.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import * as openEnums from '../types/enums.js'; +import { EndpointStatus$inboundSchema } from './endpointstatus.js'; +import { Parameter$inboundSchema } from './parameter.js'; +import { ProviderName$inboundSchema } from './providername.js'; export type Pricing = { /** @@ -70,19 +71,17 @@ export type Pricing = { }; export const PublicEndpointQuantization = { - Int4: "int4", - Int8: "int8", - Fp4: "fp4", - Fp6: "fp6", - Fp8: "fp8", - Fp16: "fp16", - Bf16: "bf16", - Fp32: "fp32", - Unknown: "unknown", + Int4: 'int4', + Int8: 'int8', + Fp4: 'fp4', + Fp6: 'fp6', + Fp8: 'fp8', + Fp16: 'fp16', + Bf16: 'bf16', + Fp32: 'fp32', + Unknown: 'unknown', } as const; -export type PublicEndpointQuantization = OpenEnum< - typeof PublicEndpointQuantization ->; +export type PublicEndpointQuantization = OpenEnum; /** * Information about a specific model endpoint @@ -104,35 +103,35 @@ export type PublicEndpoint = { }; /** @internal */ -export const Pricing$inboundSchema: z.ZodType = z.object({ - prompt: z.string(), - completion: z.string(), - request: z.string().optional(), - image: z.string().optional(), - image_token: z.string().optional(), - image_output: z.string().optional(), - audio: z.string().optional(), - input_audio_cache: z.string().optional(), - web_search: z.string().optional(), - internal_reasoning: z.string().optional(), - input_cache_read: z.string().optional(), - input_cache_write: z.string().optional(), - discount: z.number().optional(), -}).transform((v) => { - return remap$(v, { - "image_token": "imageToken", - "image_output": "imageOutput", - "input_audio_cache": "inputAudioCache", - "web_search": "webSearch", - "internal_reasoning": "internalReasoning", - "input_cache_read": "inputCacheRead", - "input_cache_write": "inputCacheWrite", +export const Pricing$inboundSchema: z.ZodType = z + .object({ + prompt: z.string(), + completion: z.string(), + request: z.string().optional(), + image: z.string().optional(), + image_token: z.string().optional(), + image_output: z.string().optional(), + audio: z.string().optional(), + input_audio_cache: z.string().optional(), + web_search: z.string().optional(), + internal_reasoning: z.string().optional(), + input_cache_read: z.string().optional(), + input_cache_write: z.string().optional(), + discount: z.number().optional(), + }) + .transform((v) => { + return remap$(v, { + image_token: 'imageToken', + image_output: 'imageOutput', + input_audio_cache: 'inputAudioCache', + web_search: 'webSearch', + internal_reasoning: 'internalReasoning', + input_cache_read: 'inputCacheRead', + input_cache_write: 'inputCacheWrite', + }); }); -}); -export function pricingFromJSON( - jsonString: string, -): SafeParseResult { +export function pricingFromJSON(jsonString: string): SafeParseResult { return safeParse( jsonString, (x) => Pricing$inboundSchema.parse(JSON.parse(x)), @@ -147,8 +146,8 @@ export const PublicEndpointQuantization$inboundSchema: z.ZodType< > = openEnums.inboundSchema(PublicEndpointQuantization); /** @internal */ -export const PublicEndpoint$inboundSchema: z.ZodType = - z.object({ +export const PublicEndpoint$inboundSchema: z.ZodType = z + .object({ name: z.string(), model_name: z.string(), context_length: z.number(), @@ -162,16 +161,17 @@ export const PublicEndpoint$inboundSchema: z.ZodType = status: EndpointStatus$inboundSchema.optional(), uptime_last_30m: z.nullable(z.number()), supports_implicit_caching: z.boolean(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "model_name": "modelName", - "context_length": "contextLength", - "provider_name": "providerName", - "max_completion_tokens": "maxCompletionTokens", - "max_prompt_tokens": "maxPromptTokens", - "supported_parameters": "supportedParameters", - "uptime_last_30m": "uptimeLast30m", - "supports_implicit_caching": "supportsImplicitCaching", + model_name: 'modelName', + context_length: 'contextLength', + provider_name: 'providerName', + max_completion_tokens: 'maxCompletionTokens', + max_prompt_tokens: 'maxPromptTokens', + supported_parameters: 'supportedParameters', + uptime_last_30m: 'uptimeLast30m', + supports_implicit_caching: 'supportsImplicitCaching', }); }); diff --git a/src/models/publicpricing.ts b/src/models/publicpricing.ts index 7b271af0..5c4ffccb 100644 --- a/src/models/publicpricing.ts +++ b/src/models/publicpricing.ts @@ -3,11 +3,12 @@ * @generated-id: 0a44a1c3bab5 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * Pricing information for the model @@ -80,15 +81,16 @@ export const PublicPricing$inboundSchema: z.ZodType = z input_cache_read: z.string().optional(), input_cache_write: z.string().optional(), discount: z.number().optional(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "image_token": "imageToken", - "image_output": "imageOutput", - "input_audio_cache": "inputAudioCache", - "web_search": "webSearch", - "internal_reasoning": "internalReasoning", - "input_cache_read": "inputCacheRead", - "input_cache_write": "inputCacheWrite", + image_token: 'imageToken', + image_output: 'imageOutput', + input_audio_cache: 'inputAudioCache', + web_search: 'webSearch', + internal_reasoning: 'internalReasoning', + input_cache_read: 'inputCacheRead', + input_cache_write: 'inputCacheWrite', }); }); diff --git a/src/models/quantization.ts b/src/models/quantization.ts index 55082b7e..17adc662 100644 --- a/src/models/quantization.ts +++ b/src/models/quantization.ts @@ -3,20 +3,21 @@ * @generated-id: b28328f1822c */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const Quantization = { - Int4: "int4", - Int8: "int8", - Fp4: "fp4", - Fp6: "fp6", - Fp8: "fp8", - Fp16: "fp16", - Bf16: "bf16", - Fp32: "fp32", - Unknown: "unknown", + Int4: 'int4', + Int8: 'int8', + Fp4: 'fp4', + Fp6: 'fp6', + Fp8: 'fp8', + Fp16: 'fp16', + Bf16: 'bf16', + Fp32: 'fp32', + Unknown: 'unknown', } as const; export type Quantization = OpenEnum; diff --git a/src/models/reasoningsummarytext.ts b/src/models/reasoningsummarytext.ts index b9720f51..b49aa361 100644 --- a/src/models/reasoningsummarytext.ts +++ b/src/models/reasoningsummarytext.ts @@ -3,18 +3,17 @@ * @generated-id: 9c06c18de6d6 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; export const ReasoningSummaryTextType = { - SummaryText: "summary_text", + SummaryText: 'summary_text', } as const; -export type ReasoningSummaryTextType = ClosedEnum< - typeof ReasoningSummaryTextType ->; +export type ReasoningSummaryTextType = ClosedEnum; export type ReasoningSummaryText = { type: ReasoningSummaryTextType; @@ -22,22 +21,18 @@ export type ReasoningSummaryText = { }; /** @internal */ -export const ReasoningSummaryTextType$inboundSchema: z.ZodEnum< - typeof ReasoningSummaryTextType -> = z.enum(ReasoningSummaryTextType); +export const ReasoningSummaryTextType$inboundSchema: z.ZodEnum = + z.enum(ReasoningSummaryTextType); /** @internal */ -export const ReasoningSummaryTextType$outboundSchema: z.ZodEnum< - typeof ReasoningSummaryTextType -> = ReasoningSummaryTextType$inboundSchema; +export const ReasoningSummaryTextType$outboundSchema: z.ZodEnum = + ReasoningSummaryTextType$inboundSchema; /** @internal */ -export const ReasoningSummaryText$inboundSchema: z.ZodType< - ReasoningSummaryText, - unknown -> = z.object({ - type: ReasoningSummaryTextType$inboundSchema, - text: z.string(), -}); +export const ReasoningSummaryText$inboundSchema: z.ZodType = + z.object({ + type: ReasoningSummaryTextType$inboundSchema, + text: z.string(), + }); /** @internal */ export type ReasoningSummaryText$Outbound = { type: string; @@ -53,12 +48,8 @@ export const ReasoningSummaryText$outboundSchema: z.ZodType< text: z.string(), }); -export function reasoningSummaryTextToJSON( - reasoningSummaryText: ReasoningSummaryText, -): string { - return JSON.stringify( - ReasoningSummaryText$outboundSchema.parse(reasoningSummaryText), - ); +export function reasoningSummaryTextToJSON(reasoningSummaryText: ReasoningSummaryText): string { + return JSON.stringify(ReasoningSummaryText$outboundSchema.parse(reasoningSummaryText)); } export function reasoningSummaryTextFromJSON( jsonString: string, diff --git a/src/models/reasoningsummaryverbosity.ts b/src/models/reasoningsummaryverbosity.ts index 58291795..ae768abf 100644 --- a/src/models/reasoningsummaryverbosity.ts +++ b/src/models/reasoningsummaryverbosity.ts @@ -3,18 +3,17 @@ * @generated-id: a51c85f04729 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const ReasoningSummaryVerbosity = { - Auto: "auto", - Concise: "concise", - Detailed: "detailed", + Auto: 'auto', + Concise: 'concise', + Detailed: 'detailed', } as const; -export type ReasoningSummaryVerbosity = OpenEnum< - typeof ReasoningSummaryVerbosity ->; +export type ReasoningSummaryVerbosity = OpenEnum; /** @internal */ export const ReasoningSummaryVerbosity$inboundSchema: z.ZodType< diff --git a/src/models/reasoningtextcontent.ts b/src/models/reasoningtextcontent.ts index 10912a90..ef53b7d7 100644 --- a/src/models/reasoningtextcontent.ts +++ b/src/models/reasoningtextcontent.ts @@ -3,18 +3,17 @@ * @generated-id: e5520210e3cb */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; export const ReasoningTextContentType = { - ReasoningText: "reasoning_text", + ReasoningText: 'reasoning_text', } as const; -export type ReasoningTextContentType = ClosedEnum< - typeof ReasoningTextContentType ->; +export type ReasoningTextContentType = ClosedEnum; export type ReasoningTextContent = { type: ReasoningTextContentType; @@ -22,22 +21,18 @@ export type ReasoningTextContent = { }; /** @internal */ -export const ReasoningTextContentType$inboundSchema: z.ZodEnum< - typeof ReasoningTextContentType -> = z.enum(ReasoningTextContentType); +export const ReasoningTextContentType$inboundSchema: z.ZodEnum = + z.enum(ReasoningTextContentType); /** @internal */ -export const ReasoningTextContentType$outboundSchema: z.ZodEnum< - typeof ReasoningTextContentType -> = ReasoningTextContentType$inboundSchema; +export const ReasoningTextContentType$outboundSchema: z.ZodEnum = + ReasoningTextContentType$inboundSchema; /** @internal */ -export const ReasoningTextContent$inboundSchema: z.ZodType< - ReasoningTextContent, - unknown -> = z.object({ - type: ReasoningTextContentType$inboundSchema, - text: z.string(), -}); +export const ReasoningTextContent$inboundSchema: z.ZodType = + z.object({ + type: ReasoningTextContentType$inboundSchema, + text: z.string(), + }); /** @internal */ export type ReasoningTextContent$Outbound = { type: string; @@ -53,12 +48,8 @@ export const ReasoningTextContent$outboundSchema: z.ZodType< text: z.string(), }); -export function reasoningTextContentToJSON( - reasoningTextContent: ReasoningTextContent, -): string { - return JSON.stringify( - ReasoningTextContent$outboundSchema.parse(reasoningTextContent), - ); +export function reasoningTextContentToJSON(reasoningTextContent: ReasoningTextContent): string { + return JSON.stringify(ReasoningTextContent$outboundSchema.parse(reasoningTextContent)); } export function reasoningTextContentFromJSON( jsonString: string, diff --git a/src/models/requesttimeoutresponseerrordata.ts b/src/models/requesttimeoutresponseerrordata.ts index c9eac87a..91379327 100644 --- a/src/models/requesttimeoutresponseerrordata.ts +++ b/src/models/requesttimeoutresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: a08eeff8786c */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for RequestTimeoutResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type RequestTimeoutResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ diff --git a/src/models/responseformatjsonschema.ts b/src/models/responseformatjsonschema.ts index cb2913fd..a63d4c31 100644 --- a/src/models/responseformatjsonschema.ts +++ b/src/models/responseformatjsonschema.ts @@ -3,22 +3,20 @@ * @generated-id: ff0b42f802dc */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { - JSONSchemaConfig, - JSONSchemaConfig$Outbound, - JSONSchemaConfig$outboundSchema, -} from "./jsonschemaconfig.js"; +import type { JSONSchemaConfig, JSONSchemaConfig$Outbound } from './jsonschemaconfig.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { JSONSchemaConfig$outboundSchema } from './jsonschemaconfig.js'; export type ResponseFormatJSONSchema = { - type: "json_schema"; + type: 'json_schema'; jsonSchema: JSONSchemaConfig; }; /** @internal */ export type ResponseFormatJSONSchema$Outbound = { - type: "json_schema"; + type: 'json_schema'; json_schema: JSONSchemaConfig$Outbound; }; @@ -26,19 +24,19 @@ export type ResponseFormatJSONSchema$Outbound = { export const ResponseFormatJSONSchema$outboundSchema: z.ZodType< ResponseFormatJSONSchema$Outbound, ResponseFormatJSONSchema -> = z.object({ - type: z.literal("json_schema"), - jsonSchema: JSONSchemaConfig$outboundSchema, -}).transform((v) => { - return remap$(v, { - jsonSchema: "json_schema", +> = z + .object({ + type: z.literal('json_schema'), + jsonSchema: JSONSchemaConfig$outboundSchema, + }) + .transform((v) => { + return remap$(v, { + jsonSchema: 'json_schema', + }); }); -}); export function responseFormatJSONSchemaToJSON( responseFormatJSONSchema: ResponseFormatJSONSchema, ): string { - return JSON.stringify( - ResponseFormatJSONSchema$outboundSchema.parse(responseFormatJSONSchema), - ); + return JSON.stringify(ResponseFormatJSONSchema$outboundSchema.parse(responseFormatJSONSchema)); } diff --git a/src/models/responseformattextconfig.ts b/src/models/responseformattextconfig.ts index 09480e22..bc45d2e4 100644 --- a/src/models/responseformattextconfig.ts +++ b/src/models/responseformattextconfig.ts @@ -3,28 +3,32 @@ * @generated-id: 4408142ee314 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { ResponsesFormatJSONObject, - ResponsesFormatJSONObject$inboundSchema, ResponsesFormatJSONObject$Outbound, +} from './responsesformatjsonobject.js'; +import type { ResponsesFormatText, ResponsesFormatText$Outbound } from './responsesformattext.js'; +import type { + ResponsesFormatTextJSONSchemaConfig, + ResponsesFormatTextJSONSchemaConfig$Outbound, +} from './responsesformattextjsonschemaconfig.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import { + ResponsesFormatJSONObject$inboundSchema, ResponsesFormatJSONObject$outboundSchema, -} from "./responsesformatjsonobject.js"; +} from './responsesformatjsonobject.js'; import { - ResponsesFormatText, ResponsesFormatText$inboundSchema, - ResponsesFormatText$Outbound, ResponsesFormatText$outboundSchema, -} from "./responsesformattext.js"; +} from './responsesformattext.js'; import { - ResponsesFormatTextJSONSchemaConfig, ResponsesFormatTextJSONSchemaConfig$inboundSchema, - ResponsesFormatTextJSONSchemaConfig$Outbound, ResponsesFormatTextJSONSchemaConfig$outboundSchema, -} from "./responsesformattextjsonschemaconfig.js"; +} from './responsesformattextjsonschemaconfig.js'; /** * Text response format configuration @@ -35,14 +39,12 @@ export type ResponseFormatTextConfig = | ResponsesFormatTextJSONSchemaConfig; /** @internal */ -export const ResponseFormatTextConfig$inboundSchema: z.ZodType< - ResponseFormatTextConfig, - unknown -> = z.union([ - ResponsesFormatText$inboundSchema, - ResponsesFormatJSONObject$inboundSchema, - ResponsesFormatTextJSONSchemaConfig$inboundSchema, -]); +export const ResponseFormatTextConfig$inboundSchema: z.ZodType = + z.union([ + ResponsesFormatText$inboundSchema, + ResponsesFormatJSONObject$inboundSchema, + ResponsesFormatTextJSONSchemaConfig$inboundSchema, + ]); /** @internal */ export type ResponseFormatTextConfig$Outbound = | ResponsesFormatText$Outbound @@ -62,9 +64,7 @@ export const ResponseFormatTextConfig$outboundSchema: z.ZodType< export function responseFormatTextConfigToJSON( responseFormatTextConfig: ResponseFormatTextConfig, ): string { - return JSON.stringify( - ResponseFormatTextConfig$outboundSchema.parse(responseFormatTextConfig), - ); + return JSON.stringify(ResponseFormatTextConfig$outboundSchema.parse(responseFormatTextConfig)); } export function responseFormatTextConfigFromJSON( jsonString: string, diff --git a/src/models/responseformattextgrammar.ts b/src/models/responseformattextgrammar.ts index 407bdc01..a91d5191 100644 --- a/src/models/responseformattextgrammar.ts +++ b/src/models/responseformattextgrammar.ts @@ -3,16 +3,16 @@ * @generated-id: 5bc0a32fad4c */ -import * as z from "zod/v4"; +import * as z from 'zod/v4'; export type ResponseFormatTextGrammar = { - type: "grammar"; + type: 'grammar'; grammar: string; }; /** @internal */ export type ResponseFormatTextGrammar$Outbound = { - type: "grammar"; + type: 'grammar'; grammar: string; }; @@ -21,14 +21,12 @@ export const ResponseFormatTextGrammar$outboundSchema: z.ZodType< ResponseFormatTextGrammar$Outbound, ResponseFormatTextGrammar > = z.object({ - type: z.literal("grammar"), + type: z.literal('grammar'), grammar: z.string(), }); export function responseFormatTextGrammarToJSON( responseFormatTextGrammar: ResponseFormatTextGrammar, ): string { - return JSON.stringify( - ResponseFormatTextGrammar$outboundSchema.parse(responseFormatTextGrammar), - ); + return JSON.stringify(ResponseFormatTextGrammar$outboundSchema.parse(responseFormatTextGrammar)); } diff --git a/src/models/responseinputaudio.ts b/src/models/responseinputaudio.ts index 9201796d..c33f0fd7 100644 --- a/src/models/responseinputaudio.ts +++ b/src/models/responseinputaudio.ts @@ -3,21 +3,20 @@ * @generated-id: 259dfb8718b4 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { OpenEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import * as openEnums from '../types/enums.js'; export const ResponseInputAudioFormat = { - Mp3: "mp3", - Wav: "wav", + Mp3: 'mp3', + Wav: 'wav', } as const; -export type ResponseInputAudioFormat = OpenEnum< - typeof ResponseInputAudioFormat ->; +export type ResponseInputAudioFormat = OpenEnum; export type ResponseInputAudioInputAudio = { data: string; @@ -28,20 +27,16 @@ export type ResponseInputAudioInputAudio = { * Audio input content item */ export type ResponseInputAudio = { - type: "input_audio"; + type: 'input_audio'; inputAudio: ResponseInputAudioInputAudio; }; /** @internal */ -export const ResponseInputAudioFormat$inboundSchema: z.ZodType< - ResponseInputAudioFormat, - unknown -> = openEnums.inboundSchema(ResponseInputAudioFormat); +export const ResponseInputAudioFormat$inboundSchema: z.ZodType = + openEnums.inboundSchema(ResponseInputAudioFormat); /** @internal */ -export const ResponseInputAudioFormat$outboundSchema: z.ZodType< - string, - ResponseInputAudioFormat -> = openEnums.outboundSchema(ResponseInputAudioFormat); +export const ResponseInputAudioFormat$outboundSchema: z.ZodType = + openEnums.outboundSchema(ResponseInputAudioFormat); /** @internal */ export const ResponseInputAudioInputAudio$inboundSchema: z.ZodType< @@ -70,9 +65,7 @@ export function responseInputAudioInputAudioToJSON( responseInputAudioInputAudio: ResponseInputAudioInputAudio, ): string { return JSON.stringify( - ResponseInputAudioInputAudio$outboundSchema.parse( - responseInputAudioInputAudio, - ), + ResponseInputAudioInputAudio$outboundSchema.parse(responseInputAudioInputAudio), ); } export function responseInputAudioInputAudioFromJSON( @@ -86,20 +79,19 @@ export function responseInputAudioInputAudioFromJSON( } /** @internal */ -export const ResponseInputAudio$inboundSchema: z.ZodType< - ResponseInputAudio, - unknown -> = z.object({ - type: z.literal("input_audio"), - input_audio: z.lazy(() => ResponseInputAudioInputAudio$inboundSchema), -}).transform((v) => { - return remap$(v, { - "input_audio": "inputAudio", +export const ResponseInputAudio$inboundSchema: z.ZodType = z + .object({ + type: z.literal('input_audio'), + input_audio: z.lazy(() => ResponseInputAudioInputAudio$inboundSchema), + }) + .transform((v) => { + return remap$(v, { + input_audio: 'inputAudio', + }); }); -}); /** @internal */ export type ResponseInputAudio$Outbound = { - type: "input_audio"; + type: 'input_audio'; input_audio: ResponseInputAudioInputAudio$Outbound; }; @@ -107,21 +99,19 @@ export type ResponseInputAudio$Outbound = { export const ResponseInputAudio$outboundSchema: z.ZodType< ResponseInputAudio$Outbound, ResponseInputAudio -> = z.object({ - type: z.literal("input_audio"), - inputAudio: z.lazy(() => ResponseInputAudioInputAudio$outboundSchema), -}).transform((v) => { - return remap$(v, { - inputAudio: "input_audio", +> = z + .object({ + type: z.literal('input_audio'), + inputAudio: z.lazy(() => ResponseInputAudioInputAudio$outboundSchema), + }) + .transform((v) => { + return remap$(v, { + inputAudio: 'input_audio', + }); }); -}); -export function responseInputAudioToJSON( - responseInputAudio: ResponseInputAudio, -): string { - return JSON.stringify( - ResponseInputAudio$outboundSchema.parse(responseInputAudio), - ); +export function responseInputAudioToJSON(responseInputAudio: ResponseInputAudio): string { + return JSON.stringify(ResponseInputAudio$outboundSchema.parse(responseInputAudio)); } export function responseInputAudioFromJSON( jsonString: string, diff --git a/src/models/responseinputfile.ts b/src/models/responseinputfile.ts index 1d2aefa1..c005aaf2 100644 --- a/src/models/responseinputfile.ts +++ b/src/models/responseinputfile.ts @@ -3,17 +3,18 @@ * @generated-id: f449677cc221 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * File input content item */ export type ResponseInputFile = { - type: "input_file"; + type: 'input_file'; fileId?: string | null | undefined; fileData?: string | undefined; filename?: string | undefined; @@ -21,25 +22,24 @@ export type ResponseInputFile = { }; /** @internal */ -export const ResponseInputFile$inboundSchema: z.ZodType< - ResponseInputFile, - unknown -> = z.object({ - type: z.literal("input_file"), - file_id: z.nullable(z.string()).optional(), - file_data: z.string().optional(), - filename: z.string().optional(), - file_url: z.string().optional(), -}).transform((v) => { - return remap$(v, { - "file_id": "fileId", - "file_data": "fileData", - "file_url": "fileUrl", +export const ResponseInputFile$inboundSchema: z.ZodType = z + .object({ + type: z.literal('input_file'), + file_id: z.nullable(z.string()).optional(), + file_data: z.string().optional(), + filename: z.string().optional(), + file_url: z.string().optional(), + }) + .transform((v) => { + return remap$(v, { + file_id: 'fileId', + file_data: 'fileData', + file_url: 'fileUrl', + }); }); -}); /** @internal */ export type ResponseInputFile$Outbound = { - type: "input_file"; + type: 'input_file'; file_id?: string | null | undefined; file_data?: string | undefined; filename?: string | undefined; @@ -50,26 +50,24 @@ export type ResponseInputFile$Outbound = { export const ResponseInputFile$outboundSchema: z.ZodType< ResponseInputFile$Outbound, ResponseInputFile -> = z.object({ - type: z.literal("input_file"), - fileId: z.nullable(z.string()).optional(), - fileData: z.string().optional(), - filename: z.string().optional(), - fileUrl: z.string().optional(), -}).transform((v) => { - return remap$(v, { - fileId: "file_id", - fileData: "file_data", - fileUrl: "file_url", +> = z + .object({ + type: z.literal('input_file'), + fileId: z.nullable(z.string()).optional(), + fileData: z.string().optional(), + filename: z.string().optional(), + fileUrl: z.string().optional(), + }) + .transform((v) => { + return remap$(v, { + fileId: 'file_id', + fileData: 'file_data', + fileUrl: 'file_url', + }); }); -}); -export function responseInputFileToJSON( - responseInputFile: ResponseInputFile, -): string { - return JSON.stringify( - ResponseInputFile$outboundSchema.parse(responseInputFile), - ); +export function responseInputFileToJSON(responseInputFile: ResponseInputFile): string { + return JSON.stringify(ResponseInputFile$outboundSchema.parse(responseInputFile)); } export function responseInputFileFromJSON( jsonString: string, diff --git a/src/models/responseinputimage.ts b/src/models/responseinputimage.ts index 44c63262..f38c717e 100644 --- a/src/models/responseinputimage.ts +++ b/src/models/responseinputimage.ts @@ -3,59 +3,53 @@ * @generated-id: 9c7a50d121df */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { OpenEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import * as openEnums from '../types/enums.js'; export const ResponseInputImageDetail = { - Auto: "auto", - High: "high", - Low: "low", + Auto: 'auto', + High: 'high', + Low: 'low', } as const; -export type ResponseInputImageDetail = OpenEnum< - typeof ResponseInputImageDetail ->; +export type ResponseInputImageDetail = OpenEnum; /** * Image input content item */ export type ResponseInputImage = { - type: "input_image"; + type: 'input_image'; detail: ResponseInputImageDetail; imageUrl?: string | null | undefined; }; /** @internal */ -export const ResponseInputImageDetail$inboundSchema: z.ZodType< - ResponseInputImageDetail, - unknown -> = openEnums.inboundSchema(ResponseInputImageDetail); +export const ResponseInputImageDetail$inboundSchema: z.ZodType = + openEnums.inboundSchema(ResponseInputImageDetail); /** @internal */ -export const ResponseInputImageDetail$outboundSchema: z.ZodType< - string, - ResponseInputImageDetail -> = openEnums.outboundSchema(ResponseInputImageDetail); +export const ResponseInputImageDetail$outboundSchema: z.ZodType = + openEnums.outboundSchema(ResponseInputImageDetail); /** @internal */ -export const ResponseInputImage$inboundSchema: z.ZodType< - ResponseInputImage, - unknown -> = z.object({ - type: z.literal("input_image"), - detail: ResponseInputImageDetail$inboundSchema, - image_url: z.nullable(z.string()).optional(), -}).transform((v) => { - return remap$(v, { - "image_url": "imageUrl", +export const ResponseInputImage$inboundSchema: z.ZodType = z + .object({ + type: z.literal('input_image'), + detail: ResponseInputImageDetail$inboundSchema, + image_url: z.nullable(z.string()).optional(), + }) + .transform((v) => { + return remap$(v, { + image_url: 'imageUrl', + }); }); -}); /** @internal */ export type ResponseInputImage$Outbound = { - type: "input_image"; + type: 'input_image'; detail: string; image_url?: string | null | undefined; }; @@ -64,22 +58,20 @@ export type ResponseInputImage$Outbound = { export const ResponseInputImage$outboundSchema: z.ZodType< ResponseInputImage$Outbound, ResponseInputImage -> = z.object({ - type: z.literal("input_image"), - detail: ResponseInputImageDetail$outboundSchema, - imageUrl: z.nullable(z.string()).optional(), -}).transform((v) => { - return remap$(v, { - imageUrl: "image_url", +> = z + .object({ + type: z.literal('input_image'), + detail: ResponseInputImageDetail$outboundSchema, + imageUrl: z.nullable(z.string()).optional(), + }) + .transform((v) => { + return remap$(v, { + imageUrl: 'image_url', + }); }); -}); -export function responseInputImageToJSON( - responseInputImage: ResponseInputImage, -): string { - return JSON.stringify( - ResponseInputImage$outboundSchema.parse(responseInputImage), - ); +export function responseInputImageToJSON(responseInputImage: ResponseInputImage): string { + return JSON.stringify(ResponseInputImage$outboundSchema.parse(responseInputImage)); } export function responseInputImageFromJSON( jsonString: string, diff --git a/src/models/responseinputtext.ts b/src/models/responseinputtext.ts index 5b8f3dec..2f5536aa 100644 --- a/src/models/responseinputtext.ts +++ b/src/models/responseinputtext.ts @@ -3,30 +3,28 @@ * @generated-id: 841523070a3c */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Text input content item */ export type ResponseInputText = { - type: "input_text"; + type: 'input_text'; text: string; }; /** @internal */ -export const ResponseInputText$inboundSchema: z.ZodType< - ResponseInputText, - unknown -> = z.object({ - type: z.literal("input_text"), +export const ResponseInputText$inboundSchema: z.ZodType = z.object({ + type: z.literal('input_text'), text: z.string(), }); /** @internal */ export type ResponseInputText$Outbound = { - type: "input_text"; + type: 'input_text'; text: string; }; @@ -35,16 +33,12 @@ export const ResponseInputText$outboundSchema: z.ZodType< ResponseInputText$Outbound, ResponseInputText > = z.object({ - type: z.literal("input_text"), + type: z.literal('input_text'), text: z.string(), }); -export function responseInputTextToJSON( - responseInputText: ResponseInputText, -): string { - return JSON.stringify( - ResponseInputText$outboundSchema.parse(responseInputText), - ); +export function responseInputTextToJSON(responseInputText: ResponseInputText): string { + return JSON.stringify(ResponseInputText$outboundSchema.parse(responseInputText)); } export function responseInputTextFromJSON( jsonString: string, diff --git a/src/models/responseoutputtext.ts b/src/models/responseoutputtext.ts index 5028e794..dde60ed6 100644 --- a/src/models/responseoutputtext.ts +++ b/src/models/responseoutputtext.ts @@ -3,35 +3,35 @@ * @generated-id: 2d5e61e53c46 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { OpenAIResponsesAnnotation, - OpenAIResponsesAnnotation$inboundSchema, OpenAIResponsesAnnotation$Outbound, +} from './openairesponsesannotation.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import { + OpenAIResponsesAnnotation$inboundSchema, OpenAIResponsesAnnotation$outboundSchema, -} from "./openairesponsesannotation.js"; +} from './openairesponsesannotation.js'; export type ResponseOutputText = { - type: "output_text"; + type: 'output_text'; text: string; annotations?: Array | undefined; }; /** @internal */ -export const ResponseOutputText$inboundSchema: z.ZodType< - ResponseOutputText, - unknown -> = z.object({ - type: z.literal("output_text"), +export const ResponseOutputText$inboundSchema: z.ZodType = z.object({ + type: z.literal('output_text'), text: z.string(), annotations: z.array(OpenAIResponsesAnnotation$inboundSchema).optional(), }); /** @internal */ export type ResponseOutputText$Outbound = { - type: "output_text"; + type: 'output_text'; text: string; annotations?: Array | undefined; }; @@ -41,17 +41,13 @@ export const ResponseOutputText$outboundSchema: z.ZodType< ResponseOutputText$Outbound, ResponseOutputText > = z.object({ - type: z.literal("output_text"), + type: z.literal('output_text'), text: z.string(), annotations: z.array(OpenAIResponsesAnnotation$outboundSchema).optional(), }); -export function responseOutputTextToJSON( - responseOutputText: ResponseOutputText, -): string { - return JSON.stringify( - ResponseOutputText$outboundSchema.parse(responseOutputText), - ); +export function responseOutputTextToJSON(responseOutputText: ResponseOutputText): string { + return JSON.stringify(ResponseOutputText$outboundSchema.parse(responseOutputText)); } export function responseOutputTextFromJSON( jsonString: string, diff --git a/src/models/responseserrorfield.ts b/src/models/responseserrorfield.ts index 9672f19f..c3772307 100644 --- a/src/models/responseserrorfield.ts +++ b/src/models/responseserrorfield.ts @@ -3,32 +3,33 @@ * @generated-id: 830ea3d3b590 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { OpenEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import * as openEnums from '../types/enums.js'; export const CodeEnum = { - ServerError: "server_error", - RateLimitExceeded: "rate_limit_exceeded", - InvalidPrompt: "invalid_prompt", - VectorStoreTimeout: "vector_store_timeout", - InvalidImage: "invalid_image", - InvalidImageFormat: "invalid_image_format", - InvalidBase64Image: "invalid_base64_image", - InvalidImageUrl: "invalid_image_url", - ImageTooLarge: "image_too_large", - ImageTooSmall: "image_too_small", - ImageParseError: "image_parse_error", - ImageContentPolicyViolation: "image_content_policy_violation", - InvalidImageMode: "invalid_image_mode", - ImageFileTooLarge: "image_file_too_large", - UnsupportedImageMediaType: "unsupported_image_media_type", - EmptyImageFile: "empty_image_file", - FailedToDownloadImage: "failed_to_download_image", - ImageFileNotFound: "image_file_not_found", + ServerError: 'server_error', + RateLimitExceeded: 'rate_limit_exceeded', + InvalidPrompt: 'invalid_prompt', + VectorStoreTimeout: 'vector_store_timeout', + InvalidImage: 'invalid_image', + InvalidImageFormat: 'invalid_image_format', + InvalidBase64Image: 'invalid_base64_image', + InvalidImageUrl: 'invalid_image_url', + ImageTooLarge: 'image_too_large', + ImageTooSmall: 'image_too_small', + ImageParseError: 'image_parse_error', + ImageContentPolicyViolation: 'image_content_policy_violation', + InvalidImageMode: 'invalid_image_mode', + ImageFileTooLarge: 'image_file_too_large', + UnsupportedImageMediaType: 'unsupported_image_media_type', + EmptyImageFile: 'empty_image_file', + FailedToDownloadImage: 'failed_to_download_image', + ImageFileNotFound: 'image_file_not_found', } as const; export type CodeEnum = OpenEnum; @@ -41,14 +42,11 @@ export type ResponsesErrorField = { }; /** @internal */ -export const CodeEnum$inboundSchema: z.ZodType = openEnums - .inboundSchema(CodeEnum); +export const CodeEnum$inboundSchema: z.ZodType = + openEnums.inboundSchema(CodeEnum); /** @internal */ -export const ResponsesErrorField$inboundSchema: z.ZodType< - ResponsesErrorField, - unknown -> = z.object({ +export const ResponsesErrorField$inboundSchema: z.ZodType = z.object({ code: CodeEnum$inboundSchema, message: z.string(), }); diff --git a/src/models/responsesformatjsonobject.ts b/src/models/responsesformatjsonobject.ts index 8da5d102..ad93347b 100644 --- a/src/models/responsesformatjsonobject.ts +++ b/src/models/responsesformatjsonobject.ts @@ -3,16 +3,17 @@ * @generated-id: cd67052e598c */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * JSON object response format */ export type ResponsesFormatJSONObject = { - type: "json_object"; + type: 'json_object'; }; /** @internal */ @@ -20,11 +21,11 @@ export const ResponsesFormatJSONObject$inboundSchema: z.ZodType< ResponsesFormatJSONObject, unknown > = z.object({ - type: z.literal("json_object"), + type: z.literal('json_object'), }); /** @internal */ export type ResponsesFormatJSONObject$Outbound = { - type: "json_object"; + type: 'json_object'; }; /** @internal */ @@ -32,15 +33,13 @@ export const ResponsesFormatJSONObject$outboundSchema: z.ZodType< ResponsesFormatJSONObject$Outbound, ResponsesFormatJSONObject > = z.object({ - type: z.literal("json_object"), + type: z.literal('json_object'), }); export function responsesFormatJSONObjectToJSON( responsesFormatJSONObject: ResponsesFormatJSONObject, ): string { - return JSON.stringify( - ResponsesFormatJSONObject$outboundSchema.parse(responsesFormatJSONObject), - ); + return JSON.stringify(ResponsesFormatJSONObject$outboundSchema.parse(responsesFormatJSONObject)); } export function responsesFormatJSONObjectFromJSON( jsonString: string, diff --git a/src/models/responsesformattext.ts b/src/models/responsesformattext.ts index ae37ccd5..07634381 100644 --- a/src/models/responsesformattext.ts +++ b/src/models/responsesformattext.ts @@ -3,28 +3,26 @@ * @generated-id: 30c4a4421b1d */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Plain text response format */ export type ResponsesFormatText = { - type: "text"; + type: 'text'; }; /** @internal */ -export const ResponsesFormatText$inboundSchema: z.ZodType< - ResponsesFormatText, - unknown -> = z.object({ - type: z.literal("text"), +export const ResponsesFormatText$inboundSchema: z.ZodType = z.object({ + type: z.literal('text'), }); /** @internal */ export type ResponsesFormatText$Outbound = { - type: "text"; + type: 'text'; }; /** @internal */ @@ -32,15 +30,11 @@ export const ResponsesFormatText$outboundSchema: z.ZodType< ResponsesFormatText$Outbound, ResponsesFormatText > = z.object({ - type: z.literal("text"), + type: z.literal('text'), }); -export function responsesFormatTextToJSON( - responsesFormatText: ResponsesFormatText, -): string { - return JSON.stringify( - ResponsesFormatText$outboundSchema.parse(responsesFormatText), - ); +export function responsesFormatTextToJSON(responsesFormatText: ResponsesFormatText): string { + return JSON.stringify(ResponsesFormatText$outboundSchema.parse(responsesFormatText)); } export function responsesFormatTextFromJSON( jsonString: string, diff --git a/src/models/responsesformattextjsonschemaconfig.ts b/src/models/responsesformattextjsonschemaconfig.ts index c4101884..eafe4395 100644 --- a/src/models/responsesformattextjsonschemaconfig.ts +++ b/src/models/responsesformattextjsonschemaconfig.ts @@ -3,20 +3,23 @@ * @generated-id: 631c61a1b658 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * JSON schema constrained response format */ export type ResponsesFormatTextJSONSchemaConfig = { - type: "json_schema"; + type: 'json_schema'; name: string; description?: string | undefined; strict?: boolean | null | undefined; - schema: { [k: string]: any | null }; + schema: { + [k: string]: any | null; + }; }; /** @internal */ @@ -24,7 +27,7 @@ export const ResponsesFormatTextJSONSchemaConfig$inboundSchema: z.ZodType< ResponsesFormatTextJSONSchemaConfig, unknown > = z.object({ - type: z.literal("json_schema"), + type: z.literal('json_schema'), name: z.string(), description: z.string().optional(), strict: z.nullable(z.boolean()).optional(), @@ -32,11 +35,13 @@ export const ResponsesFormatTextJSONSchemaConfig$inboundSchema: z.ZodType< }); /** @internal */ export type ResponsesFormatTextJSONSchemaConfig$Outbound = { - type: "json_schema"; + type: 'json_schema'; name: string; description?: string | undefined; strict?: boolean | null | undefined; - schema: { [k: string]: any | null }; + schema: { + [k: string]: any | null; + }; }; /** @internal */ @@ -44,7 +49,7 @@ export const ResponsesFormatTextJSONSchemaConfig$outboundSchema: z.ZodType< ResponsesFormatTextJSONSchemaConfig$Outbound, ResponsesFormatTextJSONSchemaConfig > = z.object({ - type: z.literal("json_schema"), + type: z.literal('json_schema'), name: z.string(), description: z.string().optional(), strict: z.nullable(z.boolean()).optional(), @@ -55,9 +60,7 @@ export function responsesFormatTextJSONSchemaConfigToJSON( responsesFormatTextJSONSchemaConfig: ResponsesFormatTextJSONSchemaConfig, ): string { return JSON.stringify( - ResponsesFormatTextJSONSchemaConfig$outboundSchema.parse( - responsesFormatTextJSONSchemaConfig, - ), + ResponsesFormatTextJSONSchemaConfig$outboundSchema.parse(responsesFormatTextJSONSchemaConfig), ); } export function responsesFormatTextJSONSchemaConfigFromJSON( @@ -65,8 +68,7 @@ export function responsesFormatTextJSONSchemaConfigFromJSON( ): SafeParseResult { return safeParse( jsonString, - (x) => - ResponsesFormatTextJSONSchemaConfig$inboundSchema.parse(JSON.parse(x)), + (x) => ResponsesFormatTextJSONSchemaConfig$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'ResponsesFormatTextJSONSchemaConfig' from JSON`, ); } diff --git a/src/models/responsesimagegenerationcall.ts b/src/models/responsesimagegenerationcall.ts index c27555dd..5e390205 100644 --- a/src/models/responsesimagegenerationcall.ts +++ b/src/models/responsesimagegenerationcall.ts @@ -3,23 +3,22 @@ * @generated-id: 51f0104f0dbf */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { ImageGenerationStatus } from './imagegenerationstatus.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; import { - ImageGenerationStatus, ImageGenerationStatus$inboundSchema, ImageGenerationStatus$outboundSchema, -} from "./imagegenerationstatus.js"; +} from './imagegenerationstatus.js'; export const ResponsesImageGenerationCallType = { - ImageGenerationCall: "image_generation_call", + ImageGenerationCall: 'image_generation_call', } as const; -export type ResponsesImageGenerationCallType = ClosedEnum< - typeof ResponsesImageGenerationCallType ->; +export type ResponsesImageGenerationCallType = ClosedEnum; export type ResponsesImageGenerationCall = { type: ResponsesImageGenerationCallType; @@ -70,9 +69,7 @@ export function responsesImageGenerationCallToJSON( responsesImageGenerationCall: ResponsesImageGenerationCall, ): string { return JSON.stringify( - ResponsesImageGenerationCall$outboundSchema.parse( - responsesImageGenerationCall, - ), + ResponsesImageGenerationCall$outboundSchema.parse(responsesImageGenerationCall), ); } export function responsesImageGenerationCallFromJSON( diff --git a/src/models/responsesoutputitem.ts b/src/models/responsesoutputitem.ts index 796f37fd..8a7905a9 100644 --- a/src/models/responsesoutputitem.ts +++ b/src/models/responsesoutputitem.ts @@ -3,68 +3,78 @@ * @generated-id: 4e7df3e415cd */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { - ResponsesImageGenerationCall, - ResponsesImageGenerationCall$inboundSchema, -} from "./responsesimagegenerationcall.js"; -import { - ResponsesOutputItemFileSearchCall, - ResponsesOutputItemFileSearchCall$inboundSchema, -} from "./responsesoutputitemfilesearchcall.js"; -import { - ResponsesOutputItemFunctionCall, - ResponsesOutputItemFunctionCall$inboundSchema, -} from "./responsesoutputitemfunctioncall.js"; -import { - ResponsesOutputItemReasoning, - ResponsesOutputItemReasoning$inboundSchema, -} from "./responsesoutputitemreasoning.js"; -import { - ResponsesOutputMessage, - ResponsesOutputMessage$inboundSchema, -} from "./responsesoutputmessage.js"; -import { - ResponsesWebSearchCallOutput, - ResponsesWebSearchCallOutput$inboundSchema, -} from "./responseswebsearchcalloutput.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { ResponsesImageGenerationCall } from './responsesimagegenerationcall.js'; +import type { ResponsesOutputItemFileSearchCall } from './responsesoutputitemfilesearchcall.js'; +import type { ResponsesOutputItemFunctionCall } from './responsesoutputitemfunctioncall.js'; +import type { ResponsesOutputItemReasoning } from './responsesoutputitemreasoning.js'; +import type { ResponsesOutputMessage } from './responsesoutputmessage.js'; +import type { ResponsesWebSearchCallOutput } from './responseswebsearchcalloutput.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import { ResponsesImageGenerationCall$inboundSchema } from './responsesimagegenerationcall.js'; +import { ResponsesOutputItemFileSearchCall$inboundSchema } from './responsesoutputitemfilesearchcall.js'; +import { ResponsesOutputItemFunctionCall$inboundSchema } from './responsesoutputitemfunctioncall.js'; +import { ResponsesOutputItemReasoning$inboundSchema } from './responsesoutputitemreasoning.js'; +import { ResponsesOutputMessage$inboundSchema } from './responsesoutputmessage.js'; +import { ResponsesWebSearchCallOutput$inboundSchema } from './responseswebsearchcalloutput.js'; /** * An output item from the response */ export type ResponsesOutputItem = - | (ResponsesOutputMessage & { type: "message" }) - | (ResponsesOutputItemReasoning & { type: "reasoning" }) - | (ResponsesOutputItemFunctionCall & { type: "function_call" }) - | (ResponsesWebSearchCallOutput & { type: "web_search_call" }) - | (ResponsesOutputItemFileSearchCall & { type: "file_search_call" }) - | (ResponsesImageGenerationCall & { type: "image_generation_call" }); + | (ResponsesOutputMessage & { + type: 'message'; + }) + | (ResponsesOutputItemReasoning & { + type: 'reasoning'; + }) + | (ResponsesOutputItemFunctionCall & { + type: 'function_call'; + }) + | (ResponsesWebSearchCallOutput & { + type: 'web_search_call'; + }) + | (ResponsesOutputItemFileSearchCall & { + type: 'file_search_call'; + }) + | (ResponsesImageGenerationCall & { + type: 'image_generation_call'; + }); /** @internal */ -export const ResponsesOutputItem$inboundSchema: z.ZodType< - ResponsesOutputItem, - unknown -> = z.union([ +export const ResponsesOutputItem$inboundSchema: z.ZodType = z.union([ ResponsesOutputMessage$inboundSchema.and( - z.object({ type: z.literal("message") }), + z.object({ + type: z.literal('message'), + }), ), ResponsesOutputItemReasoning$inboundSchema.and( - z.object({ type: z.literal("reasoning") }), + z.object({ + type: z.literal('reasoning'), + }), ), ResponsesOutputItemFunctionCall$inboundSchema.and( - z.object({ type: z.literal("function_call") }), + z.object({ + type: z.literal('function_call'), + }), ), ResponsesWebSearchCallOutput$inboundSchema.and( - z.object({ type: z.literal("web_search_call") }), + z.object({ + type: z.literal('web_search_call'), + }), ), ResponsesOutputItemFileSearchCall$inboundSchema.and( - z.object({ type: z.literal("file_search_call") }), + z.object({ + type: z.literal('file_search_call'), + }), ), ResponsesImageGenerationCall$inboundSchema.and( - z.object({ type: z.literal("image_generation_call") }), + z.object({ + type: z.literal('image_generation_call'), + }), ), ]); diff --git a/src/models/responsesoutputitemfilesearchcall.ts b/src/models/responsesoutputitemfilesearchcall.ts index 740c6fec..523021fe 100644 --- a/src/models/responsesoutputitemfilesearchcall.ts +++ b/src/models/responsesoutputitemfilesearchcall.ts @@ -3,19 +3,20 @@ * @generated-id: e5ac80adf28b */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { WebSearchStatus } from './websearchstatus.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; import { - WebSearchStatus, WebSearchStatus$inboundSchema, WebSearchStatus$outboundSchema, -} from "./websearchstatus.js"; +} from './websearchstatus.js'; export const ResponsesOutputItemFileSearchCallType = { - FileSearchCall: "file_search_call", + FileSearchCall: 'file_search_call', } as const; export type ResponsesOutputItemFileSearchCallType = ClosedEnum< typeof ResponsesOutputItemFileSearchCallType @@ -70,9 +71,7 @@ export function responsesOutputItemFileSearchCallToJSON( responsesOutputItemFileSearchCall: ResponsesOutputItemFileSearchCall, ): string { return JSON.stringify( - ResponsesOutputItemFileSearchCall$outboundSchema.parse( - responsesOutputItemFileSearchCall, - ), + ResponsesOutputItemFileSearchCall$outboundSchema.parse(responsesOutputItemFileSearchCall), ); } export function responsesOutputItemFileSearchCallFromJSON( diff --git a/src/models/responsesoutputitemfunctioncall.ts b/src/models/responsesoutputitemfunctioncall.ts index 4b2a84ba..c1aa92bd 100644 --- a/src/models/responsesoutputitemfunctioncall.ts +++ b/src/models/responsesoutputitemfunctioncall.ts @@ -3,36 +3,37 @@ * @generated-id: ff553c6d83b4 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; export const ResponsesOutputItemFunctionCallType = { - FunctionCall: "function_call", + FunctionCall: 'function_call', } as const; export type ResponsesOutputItemFunctionCallType = ClosedEnum< typeof ResponsesOutputItemFunctionCallType >; export const ResponsesOutputItemFunctionCallStatusInProgress = { - InProgress: "in_progress", + InProgress: 'in_progress', } as const; export type ResponsesOutputItemFunctionCallStatusInProgress = ClosedEnum< typeof ResponsesOutputItemFunctionCallStatusInProgress >; export const ResponsesOutputItemFunctionCallStatusIncomplete = { - Incomplete: "incomplete", + Incomplete: 'incomplete', } as const; export type ResponsesOutputItemFunctionCallStatusIncomplete = ClosedEnum< typeof ResponsesOutputItemFunctionCallStatusIncomplete >; export const ResponsesOutputItemFunctionCallStatusCompleted = { - Completed: "completed", + Completed: 'completed', } as const; export type ResponsesOutputItemFunctionCallStatusCompleted = ClosedEnum< typeof ResponsesOutputItemFunctionCallStatusCompleted @@ -66,62 +67,56 @@ export const ResponsesOutputItemFunctionCallType$outboundSchema: z.ZodEnum< > = ResponsesOutputItemFunctionCallType$inboundSchema; /** @internal */ -export const ResponsesOutputItemFunctionCallStatusInProgress$inboundSchema: - z.ZodEnum = z.enum( - ResponsesOutputItemFunctionCallStatusInProgress, - ); +export const ResponsesOutputItemFunctionCallStatusInProgress$inboundSchema: z.ZodEnum< + typeof ResponsesOutputItemFunctionCallStatusInProgress +> = z.enum(ResponsesOutputItemFunctionCallStatusInProgress); /** @internal */ -export const ResponsesOutputItemFunctionCallStatusInProgress$outboundSchema: - z.ZodEnum = - ResponsesOutputItemFunctionCallStatusInProgress$inboundSchema; +export const ResponsesOutputItemFunctionCallStatusInProgress$outboundSchema: z.ZodEnum< + typeof ResponsesOutputItemFunctionCallStatusInProgress +> = ResponsesOutputItemFunctionCallStatusInProgress$inboundSchema; /** @internal */ -export const ResponsesOutputItemFunctionCallStatusIncomplete$inboundSchema: - z.ZodEnum = z.enum( - ResponsesOutputItemFunctionCallStatusIncomplete, - ); +export const ResponsesOutputItemFunctionCallStatusIncomplete$inboundSchema: z.ZodEnum< + typeof ResponsesOutputItemFunctionCallStatusIncomplete +> = z.enum(ResponsesOutputItemFunctionCallStatusIncomplete); /** @internal */ -export const ResponsesOutputItemFunctionCallStatusIncomplete$outboundSchema: - z.ZodEnum = - ResponsesOutputItemFunctionCallStatusIncomplete$inboundSchema; +export const ResponsesOutputItemFunctionCallStatusIncomplete$outboundSchema: z.ZodEnum< + typeof ResponsesOutputItemFunctionCallStatusIncomplete +> = ResponsesOutputItemFunctionCallStatusIncomplete$inboundSchema; /** @internal */ -export const ResponsesOutputItemFunctionCallStatusCompleted$inboundSchema: - z.ZodEnum = z.enum( - ResponsesOutputItemFunctionCallStatusCompleted, - ); +export const ResponsesOutputItemFunctionCallStatusCompleted$inboundSchema: z.ZodEnum< + typeof ResponsesOutputItemFunctionCallStatusCompleted +> = z.enum(ResponsesOutputItemFunctionCallStatusCompleted); /** @internal */ -export const ResponsesOutputItemFunctionCallStatusCompleted$outboundSchema: - z.ZodEnum = - ResponsesOutputItemFunctionCallStatusCompleted$inboundSchema; +export const ResponsesOutputItemFunctionCallStatusCompleted$outboundSchema: z.ZodEnum< + typeof ResponsesOutputItemFunctionCallStatusCompleted +> = ResponsesOutputItemFunctionCallStatusCompleted$inboundSchema; /** @internal */ -export const ResponsesOutputItemFunctionCallStatusUnion$inboundSchema: - z.ZodType = z.union([ - ResponsesOutputItemFunctionCallStatusCompleted$inboundSchema, - ResponsesOutputItemFunctionCallStatusIncomplete$inboundSchema, - ResponsesOutputItemFunctionCallStatusInProgress$inboundSchema, - ]); +export const ResponsesOutputItemFunctionCallStatusUnion$inboundSchema: z.ZodType< + ResponsesOutputItemFunctionCallStatusUnion, + unknown +> = z.union([ + ResponsesOutputItemFunctionCallStatusCompleted$inboundSchema, + ResponsesOutputItemFunctionCallStatusIncomplete$inboundSchema, + ResponsesOutputItemFunctionCallStatusInProgress$inboundSchema, +]); /** @internal */ -export type ResponsesOutputItemFunctionCallStatusUnion$Outbound = - | string - | string - | string; +export type ResponsesOutputItemFunctionCallStatusUnion$Outbound = string | string | string; /** @internal */ -export const ResponsesOutputItemFunctionCallStatusUnion$outboundSchema: - z.ZodType< - ResponsesOutputItemFunctionCallStatusUnion$Outbound, - ResponsesOutputItemFunctionCallStatusUnion - > = z.union([ - ResponsesOutputItemFunctionCallStatusCompleted$outboundSchema, - ResponsesOutputItemFunctionCallStatusIncomplete$outboundSchema, - ResponsesOutputItemFunctionCallStatusInProgress$outboundSchema, - ]); +export const ResponsesOutputItemFunctionCallStatusUnion$outboundSchema: z.ZodType< + ResponsesOutputItemFunctionCallStatusUnion$Outbound, + ResponsesOutputItemFunctionCallStatusUnion +> = z.union([ + ResponsesOutputItemFunctionCallStatusCompleted$outboundSchema, + ResponsesOutputItemFunctionCallStatusIncomplete$outboundSchema, + ResponsesOutputItemFunctionCallStatusInProgress$outboundSchema, +]); export function responsesOutputItemFunctionCallStatusUnionToJSON( - responsesOutputItemFunctionCallStatusUnion: - ResponsesOutputItemFunctionCallStatusUnion, + responsesOutputItemFunctionCallStatusUnion: ResponsesOutputItemFunctionCallStatusUnion, ): string { return JSON.stringify( ResponsesOutputItemFunctionCallStatusUnion$outboundSchema.parse( @@ -131,16 +126,10 @@ export function responsesOutputItemFunctionCallStatusUnionToJSON( } export function responsesOutputItemFunctionCallStatusUnionFromJSON( jsonString: string, -): SafeParseResult< - ResponsesOutputItemFunctionCallStatusUnion, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - ResponsesOutputItemFunctionCallStatusUnion$inboundSchema.parse( - JSON.parse(x), - ), + (x) => ResponsesOutputItemFunctionCallStatusUnion$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'ResponsesOutputItemFunctionCallStatusUnion' from JSON`, ); } @@ -149,22 +138,26 @@ export function responsesOutputItemFunctionCallStatusUnionFromJSON( export const ResponsesOutputItemFunctionCall$inboundSchema: z.ZodType< ResponsesOutputItemFunctionCall, unknown -> = z.object({ - type: ResponsesOutputItemFunctionCallType$inboundSchema, - id: z.string().optional(), - name: z.string(), - arguments: z.string(), - call_id: z.string(), - status: z.union([ - ResponsesOutputItemFunctionCallStatusCompleted$inboundSchema, - ResponsesOutputItemFunctionCallStatusIncomplete$inboundSchema, - ResponsesOutputItemFunctionCallStatusInProgress$inboundSchema, - ]).optional(), -}).transform((v) => { - return remap$(v, { - "call_id": "callId", +> = z + .object({ + type: ResponsesOutputItemFunctionCallType$inboundSchema, + id: z.string().optional(), + name: z.string(), + arguments: z.string(), + call_id: z.string(), + status: z + .union([ + ResponsesOutputItemFunctionCallStatusCompleted$inboundSchema, + ResponsesOutputItemFunctionCallStatusIncomplete$inboundSchema, + ResponsesOutputItemFunctionCallStatusInProgress$inboundSchema, + ]) + .optional(), + }) + .transform((v) => { + return remap$(v, { + call_id: 'callId', + }); }); -}); /** @internal */ export type ResponsesOutputItemFunctionCall$Outbound = { type: string; @@ -179,30 +172,32 @@ export type ResponsesOutputItemFunctionCall$Outbound = { export const ResponsesOutputItemFunctionCall$outboundSchema: z.ZodType< ResponsesOutputItemFunctionCall$Outbound, ResponsesOutputItemFunctionCall -> = z.object({ - type: ResponsesOutputItemFunctionCallType$outboundSchema, - id: z.string().optional(), - name: z.string(), - arguments: z.string(), - callId: z.string(), - status: z.union([ - ResponsesOutputItemFunctionCallStatusCompleted$outboundSchema, - ResponsesOutputItemFunctionCallStatusIncomplete$outboundSchema, - ResponsesOutputItemFunctionCallStatusInProgress$outboundSchema, - ]).optional(), -}).transform((v) => { - return remap$(v, { - callId: "call_id", +> = z + .object({ + type: ResponsesOutputItemFunctionCallType$outboundSchema, + id: z.string().optional(), + name: z.string(), + arguments: z.string(), + callId: z.string(), + status: z + .union([ + ResponsesOutputItemFunctionCallStatusCompleted$outboundSchema, + ResponsesOutputItemFunctionCallStatusIncomplete$outboundSchema, + ResponsesOutputItemFunctionCallStatusInProgress$outboundSchema, + ]) + .optional(), + }) + .transform((v) => { + return remap$(v, { + callId: 'call_id', + }); }); -}); export function responsesOutputItemFunctionCallToJSON( responsesOutputItemFunctionCall: ResponsesOutputItemFunctionCall, ): string { return JSON.stringify( - ResponsesOutputItemFunctionCall$outboundSchema.parse( - responsesOutputItemFunctionCall, - ), + ResponsesOutputItemFunctionCall$outboundSchema.parse(responsesOutputItemFunctionCall), ); } export function responsesOutputItemFunctionCallFromJSON( diff --git a/src/models/responsesoutputitemreasoning.ts b/src/models/responsesoutputitemreasoning.ts index 60b06c0e..70cf7d54 100644 --- a/src/models/responsesoutputitemreasoning.ts +++ b/src/models/responsesoutputitemreasoning.ts @@ -3,48 +3,51 @@ * @generated-id: 191f7f61ea84 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { ReasoningSummaryText, - ReasoningSummaryText$inboundSchema, ReasoningSummaryText$Outbound, +} from './reasoningsummarytext.js'; +import type { + ReasoningTextContent, + ReasoningTextContent$Outbound, +} from './reasoningtextcontent.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; +import { + ReasoningSummaryText$inboundSchema, ReasoningSummaryText$outboundSchema, -} from "./reasoningsummarytext.js"; +} from './reasoningsummarytext.js'; import { - ReasoningTextContent, ReasoningTextContent$inboundSchema, - ReasoningTextContent$Outbound, ReasoningTextContent$outboundSchema, -} from "./reasoningtextcontent.js"; +} from './reasoningtextcontent.js'; export const ResponsesOutputItemReasoningType = { - Reasoning: "reasoning", + Reasoning: 'reasoning', } as const; -export type ResponsesOutputItemReasoningType = ClosedEnum< - typeof ResponsesOutputItemReasoningType ->; +export type ResponsesOutputItemReasoningType = ClosedEnum; export const ResponsesOutputItemReasoningStatusInProgress = { - InProgress: "in_progress", + InProgress: 'in_progress', } as const; export type ResponsesOutputItemReasoningStatusInProgress = ClosedEnum< typeof ResponsesOutputItemReasoningStatusInProgress >; export const ResponsesOutputItemReasoningStatusIncomplete = { - Incomplete: "incomplete", + Incomplete: 'incomplete', } as const; export type ResponsesOutputItemReasoningStatusIncomplete = ClosedEnum< typeof ResponsesOutputItemReasoningStatusIncomplete >; export const ResponsesOutputItemReasoningStatusCompleted = { - Completed: "completed", + Completed: 'completed', } as const; export type ResponsesOutputItemReasoningStatusCompleted = ClosedEnum< typeof ResponsesOutputItemReasoningStatusCompleted @@ -81,34 +84,31 @@ export const ResponsesOutputItemReasoningType$outboundSchema: z.ZodEnum< > = ResponsesOutputItemReasoningType$inboundSchema; /** @internal */ -export const ResponsesOutputItemReasoningStatusInProgress$inboundSchema: - z.ZodEnum = z.enum( - ResponsesOutputItemReasoningStatusInProgress, - ); +export const ResponsesOutputItemReasoningStatusInProgress$inboundSchema: z.ZodEnum< + typeof ResponsesOutputItemReasoningStatusInProgress +> = z.enum(ResponsesOutputItemReasoningStatusInProgress); /** @internal */ -export const ResponsesOutputItemReasoningStatusInProgress$outboundSchema: - z.ZodEnum = - ResponsesOutputItemReasoningStatusInProgress$inboundSchema; +export const ResponsesOutputItemReasoningStatusInProgress$outboundSchema: z.ZodEnum< + typeof ResponsesOutputItemReasoningStatusInProgress +> = ResponsesOutputItemReasoningStatusInProgress$inboundSchema; /** @internal */ -export const ResponsesOutputItemReasoningStatusIncomplete$inboundSchema: - z.ZodEnum = z.enum( - ResponsesOutputItemReasoningStatusIncomplete, - ); +export const ResponsesOutputItemReasoningStatusIncomplete$inboundSchema: z.ZodEnum< + typeof ResponsesOutputItemReasoningStatusIncomplete +> = z.enum(ResponsesOutputItemReasoningStatusIncomplete); /** @internal */ -export const ResponsesOutputItemReasoningStatusIncomplete$outboundSchema: - z.ZodEnum = - ResponsesOutputItemReasoningStatusIncomplete$inboundSchema; +export const ResponsesOutputItemReasoningStatusIncomplete$outboundSchema: z.ZodEnum< + typeof ResponsesOutputItemReasoningStatusIncomplete +> = ResponsesOutputItemReasoningStatusIncomplete$inboundSchema; /** @internal */ -export const ResponsesOutputItemReasoningStatusCompleted$inboundSchema: - z.ZodEnum = z.enum( - ResponsesOutputItemReasoningStatusCompleted, - ); +export const ResponsesOutputItemReasoningStatusCompleted$inboundSchema: z.ZodEnum< + typeof ResponsesOutputItemReasoningStatusCompleted +> = z.enum(ResponsesOutputItemReasoningStatusCompleted); /** @internal */ -export const ResponsesOutputItemReasoningStatusCompleted$outboundSchema: - z.ZodEnum = - ResponsesOutputItemReasoningStatusCompleted$inboundSchema; +export const ResponsesOutputItemReasoningStatusCompleted$outboundSchema: z.ZodEnum< + typeof ResponsesOutputItemReasoningStatusCompleted +> = ResponsesOutputItemReasoningStatusCompleted$inboundSchema; /** @internal */ export const ResponsesOutputItemReasoningStatusUnion$inboundSchema: z.ZodType< @@ -120,10 +120,7 @@ export const ResponsesOutputItemReasoningStatusUnion$inboundSchema: z.ZodType< ResponsesOutputItemReasoningStatusInProgress$inboundSchema, ]); /** @internal */ -export type ResponsesOutputItemReasoningStatusUnion$Outbound = - | string - | string - | string; +export type ResponsesOutputItemReasoningStatusUnion$Outbound = string | string | string; /** @internal */ export const ResponsesOutputItemReasoningStatusUnion$outboundSchema: z.ZodType< @@ -136,8 +133,7 @@ export const ResponsesOutputItemReasoningStatusUnion$outboundSchema: z.ZodType< ]); export function responsesOutputItemReasoningStatusUnionToJSON( - responsesOutputItemReasoningStatusUnion: - ResponsesOutputItemReasoningStatusUnion, + responsesOutputItemReasoningStatusUnion: ResponsesOutputItemReasoningStatusUnion, ): string { return JSON.stringify( ResponsesOutputItemReasoningStatusUnion$outboundSchema.parse( @@ -147,16 +143,10 @@ export function responsesOutputItemReasoningStatusUnionToJSON( } export function responsesOutputItemReasoningStatusUnionFromJSON( jsonString: string, -): SafeParseResult< - ResponsesOutputItemReasoningStatusUnion, - SDKValidationError -> { +): SafeParseResult { return safeParse( jsonString, - (x) => - ResponsesOutputItemReasoningStatusUnion$inboundSchema.parse( - JSON.parse(x), - ), + (x) => ResponsesOutputItemReasoningStatusUnion$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'ResponsesOutputItemReasoningStatusUnion' from JSON`, ); } @@ -165,22 +155,26 @@ export function responsesOutputItemReasoningStatusUnionFromJSON( export const ResponsesOutputItemReasoning$inboundSchema: z.ZodType< ResponsesOutputItemReasoning, unknown -> = z.object({ - type: ResponsesOutputItemReasoningType$inboundSchema, - id: z.string(), - content: z.array(ReasoningTextContent$inboundSchema).optional(), - summary: z.array(ReasoningSummaryText$inboundSchema), - encrypted_content: z.nullable(z.string()).optional(), - status: z.union([ - ResponsesOutputItemReasoningStatusCompleted$inboundSchema, - ResponsesOutputItemReasoningStatusIncomplete$inboundSchema, - ResponsesOutputItemReasoningStatusInProgress$inboundSchema, - ]).optional(), -}).transform((v) => { - return remap$(v, { - "encrypted_content": "encryptedContent", +> = z + .object({ + type: ResponsesOutputItemReasoningType$inboundSchema, + id: z.string(), + content: z.array(ReasoningTextContent$inboundSchema).optional(), + summary: z.array(ReasoningSummaryText$inboundSchema), + encrypted_content: z.nullable(z.string()).optional(), + status: z + .union([ + ResponsesOutputItemReasoningStatusCompleted$inboundSchema, + ResponsesOutputItemReasoningStatusIncomplete$inboundSchema, + ResponsesOutputItemReasoningStatusInProgress$inboundSchema, + ]) + .optional(), + }) + .transform((v) => { + return remap$(v, { + encrypted_content: 'encryptedContent', + }); }); -}); /** @internal */ export type ResponsesOutputItemReasoning$Outbound = { type: string; @@ -195,30 +189,32 @@ export type ResponsesOutputItemReasoning$Outbound = { export const ResponsesOutputItemReasoning$outboundSchema: z.ZodType< ResponsesOutputItemReasoning$Outbound, ResponsesOutputItemReasoning -> = z.object({ - type: ResponsesOutputItemReasoningType$outboundSchema, - id: z.string(), - content: z.array(ReasoningTextContent$outboundSchema).optional(), - summary: z.array(ReasoningSummaryText$outboundSchema), - encryptedContent: z.nullable(z.string()).optional(), - status: z.union([ - ResponsesOutputItemReasoningStatusCompleted$outboundSchema, - ResponsesOutputItemReasoningStatusIncomplete$outboundSchema, - ResponsesOutputItemReasoningStatusInProgress$outboundSchema, - ]).optional(), -}).transform((v) => { - return remap$(v, { - encryptedContent: "encrypted_content", +> = z + .object({ + type: ResponsesOutputItemReasoningType$outboundSchema, + id: z.string(), + content: z.array(ReasoningTextContent$outboundSchema).optional(), + summary: z.array(ReasoningSummaryText$outboundSchema), + encryptedContent: z.nullable(z.string()).optional(), + status: z + .union([ + ResponsesOutputItemReasoningStatusCompleted$outboundSchema, + ResponsesOutputItemReasoningStatusIncomplete$outboundSchema, + ResponsesOutputItemReasoningStatusInProgress$outboundSchema, + ]) + .optional(), + }) + .transform((v) => { + return remap$(v, { + encryptedContent: 'encrypted_content', + }); }); -}); export function responsesOutputItemReasoningToJSON( responsesOutputItemReasoning: ResponsesOutputItemReasoning, ): string { return JSON.stringify( - ResponsesOutputItemReasoning$outboundSchema.parse( - responsesOutputItemReasoning, - ), + ResponsesOutputItemReasoning$outboundSchema.parse(responsesOutputItemReasoning), ); } export function responsesOutputItemReasoningFromJSON( diff --git a/src/models/responsesoutputmessage.ts b/src/models/responsesoutputmessage.ts index dc3999ba..92963080 100644 --- a/src/models/responsesoutputmessage.ts +++ b/src/models/responsesoutputmessage.ts @@ -3,54 +3,52 @@ * @generated-id: 32cb33488ea2 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { OpenAIResponsesRefusalContent, - OpenAIResponsesRefusalContent$inboundSchema, OpenAIResponsesRefusalContent$Outbound, +} from './openairesponsesrefusalcontent.js'; +import type { ResponseOutputText, ResponseOutputText$Outbound } from './responseoutputtext.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import { + OpenAIResponsesRefusalContent$inboundSchema, OpenAIResponsesRefusalContent$outboundSchema, -} from "./openairesponsesrefusalcontent.js"; +} from './openairesponsesrefusalcontent.js'; import { - ResponseOutputText, ResponseOutputText$inboundSchema, - ResponseOutputText$Outbound, ResponseOutputText$outboundSchema, -} from "./responseoutputtext.js"; +} from './responseoutputtext.js'; export const ResponsesOutputMessageRole = { - Assistant: "assistant", + Assistant: 'assistant', } as const; -export type ResponsesOutputMessageRole = ClosedEnum< - typeof ResponsesOutputMessageRole ->; +export type ResponsesOutputMessageRole = ClosedEnum; export const ResponsesOutputMessageType = { - Message: "message", + Message: 'message', } as const; -export type ResponsesOutputMessageType = ClosedEnum< - typeof ResponsesOutputMessageType ->; +export type ResponsesOutputMessageType = ClosedEnum; export const ResponsesOutputMessageStatusInProgress = { - InProgress: "in_progress", + InProgress: 'in_progress', } as const; export type ResponsesOutputMessageStatusInProgress = ClosedEnum< typeof ResponsesOutputMessageStatusInProgress >; export const ResponsesOutputMessageStatusIncomplete = { - Incomplete: "incomplete", + Incomplete: 'incomplete', } as const; export type ResponsesOutputMessageStatusIncomplete = ClosedEnum< typeof ResponsesOutputMessageStatusIncomplete >; export const ResponsesOutputMessageStatusCompleted = { - Completed: "completed", + Completed: 'completed', } as const; export type ResponsesOutputMessageStatusCompleted = ClosedEnum< typeof ResponsesOutputMessageStatusCompleted @@ -61,9 +59,7 @@ export type ResponsesOutputMessageStatusUnion = | ResponsesOutputMessageStatusIncomplete | ResponsesOutputMessageStatusInProgress; -export type ResponsesOutputMessageContent = - | ResponseOutputText - | OpenAIResponsesRefusalContent; +export type ResponsesOutputMessageContent = ResponseOutputText | OpenAIResponsesRefusalContent; /** * An output message item @@ -135,10 +131,7 @@ export const ResponsesOutputMessageStatusUnion$inboundSchema: z.ZodType< ResponsesOutputMessageStatusInProgress$inboundSchema, ]); /** @internal */ -export type ResponsesOutputMessageStatusUnion$Outbound = - | string - | string - | string; +export type ResponsesOutputMessageStatusUnion$Outbound = string | string | string; /** @internal */ export const ResponsesOutputMessageStatusUnion$outboundSchema: z.ZodType< @@ -154,9 +147,7 @@ export function responsesOutputMessageStatusUnionToJSON( responsesOutputMessageStatusUnion: ResponsesOutputMessageStatusUnion, ): string { return JSON.stringify( - ResponsesOutputMessageStatusUnion$outboundSchema.parse( - responsesOutputMessageStatusUnion, - ), + ResponsesOutputMessageStatusUnion$outboundSchema.parse(responsesOutputMessageStatusUnion), ); } export function responsesOutputMessageStatusUnionFromJSON( @@ -195,9 +186,7 @@ export function responsesOutputMessageContentToJSON( responsesOutputMessageContent: ResponsesOutputMessageContent, ): string { return JSON.stringify( - ResponsesOutputMessageContent$outboundSchema.parse( - responsesOutputMessageContent, - ), + ResponsesOutputMessageContent$outboundSchema.parse(responsesOutputMessageContent), ); } export function responsesOutputMessageContentFromJSON( @@ -211,34 +200,32 @@ export function responsesOutputMessageContentFromJSON( } /** @internal */ -export const ResponsesOutputMessage$inboundSchema: z.ZodType< - ResponsesOutputMessage, - unknown -> = z.object({ - id: z.string(), - role: ResponsesOutputMessageRole$inboundSchema, - type: ResponsesOutputMessageType$inboundSchema, - status: z.union([ - ResponsesOutputMessageStatusCompleted$inboundSchema, - ResponsesOutputMessageStatusIncomplete$inboundSchema, - ResponsesOutputMessageStatusInProgress$inboundSchema, - ]).optional(), - content: z.array( - z.union([ - ResponseOutputText$inboundSchema, - OpenAIResponsesRefusalContent$inboundSchema, - ]), - ), -}); +export const ResponsesOutputMessage$inboundSchema: z.ZodType = + z.object({ + id: z.string(), + role: ResponsesOutputMessageRole$inboundSchema, + type: ResponsesOutputMessageType$inboundSchema, + status: z + .union([ + ResponsesOutputMessageStatusCompleted$inboundSchema, + ResponsesOutputMessageStatusIncomplete$inboundSchema, + ResponsesOutputMessageStatusInProgress$inboundSchema, + ]) + .optional(), + content: z.array( + z.union([ + ResponseOutputText$inboundSchema, + OpenAIResponsesRefusalContent$inboundSchema, + ]), + ), + }); /** @internal */ export type ResponsesOutputMessage$Outbound = { id: string; role: string; type: string; status?: string | string | string | undefined; - content: Array< - ResponseOutputText$Outbound | OpenAIResponsesRefusalContent$Outbound - >; + content: Array; }; /** @internal */ @@ -249,11 +236,13 @@ export const ResponsesOutputMessage$outboundSchema: z.ZodType< id: z.string(), role: ResponsesOutputMessageRole$outboundSchema, type: ResponsesOutputMessageType$outboundSchema, - status: z.union([ - ResponsesOutputMessageStatusCompleted$outboundSchema, - ResponsesOutputMessageStatusIncomplete$outboundSchema, - ResponsesOutputMessageStatusInProgress$outboundSchema, - ]).optional(), + status: z + .union([ + ResponsesOutputMessageStatusCompleted$outboundSchema, + ResponsesOutputMessageStatusIncomplete$outboundSchema, + ResponsesOutputMessageStatusInProgress$outboundSchema, + ]) + .optional(), content: z.array( z.union([ ResponseOutputText$outboundSchema, @@ -265,9 +254,7 @@ export const ResponsesOutputMessage$outboundSchema: z.ZodType< export function responsesOutputMessageToJSON( responsesOutputMessage: ResponsesOutputMessage, ): string { - return JSON.stringify( - ResponsesOutputMessage$outboundSchema.parse(responsesOutputMessage), - ); + return JSON.stringify(ResponsesOutputMessage$outboundSchema.parse(responsesOutputMessage)); } export function responsesOutputMessageFromJSON( jsonString: string, diff --git a/src/models/responsessearchcontextsize.ts b/src/models/responsessearchcontextsize.ts index cd259586..87c7d40f 100644 --- a/src/models/responsessearchcontextsize.ts +++ b/src/models/responsessearchcontextsize.ts @@ -3,24 +3,23 @@ * @generated-id: 3c1dd9e04db4 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; /** * Size of the search context for web search tools */ export const ResponsesSearchContextSize = { - Low: "low", - Medium: "medium", - High: "high", + Low: 'low', + Medium: 'medium', + High: 'high', } as const; /** * Size of the search context for web search tools */ -export type ResponsesSearchContextSize = OpenEnum< - typeof ResponsesSearchContextSize ->; +export type ResponsesSearchContextSize = OpenEnum; /** @internal */ export const ResponsesSearchContextSize$inboundSchema: z.ZodType< diff --git a/src/models/responseswebsearchcalloutput.ts b/src/models/responseswebsearchcalloutput.ts index 8858d5bb..bb61f40d 100644 --- a/src/models/responseswebsearchcalloutput.ts +++ b/src/models/responseswebsearchcalloutput.ts @@ -3,23 +3,22 @@ * @generated-id: c1c0ab68e92c */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { WebSearchStatus } from './websearchstatus.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; import { - WebSearchStatus, WebSearchStatus$inboundSchema, WebSearchStatus$outboundSchema, -} from "./websearchstatus.js"; +} from './websearchstatus.js'; export const ResponsesWebSearchCallOutputType = { - WebSearchCall: "web_search_call", + WebSearchCall: 'web_search_call', } as const; -export type ResponsesWebSearchCallOutputType = ClosedEnum< - typeof ResponsesWebSearchCallOutputType ->; +export type ResponsesWebSearchCallOutputType = ClosedEnum; export type ResponsesWebSearchCallOutput = { type: ResponsesWebSearchCallOutputType; @@ -66,9 +65,7 @@ export function responsesWebSearchCallOutputToJSON( responsesWebSearchCallOutput: ResponsesWebSearchCallOutput, ): string { return JSON.stringify( - ResponsesWebSearchCallOutput$outboundSchema.parse( - responsesWebSearchCallOutput, - ), + ResponsesWebSearchCallOutput$outboundSchema.parse(responsesWebSearchCallOutput), ); } export function responsesWebSearchCallOutputFromJSON( diff --git a/src/models/responseswebsearchuserlocation.ts b/src/models/responseswebsearchuserlocation.ts index 036cdd23..b05c62d7 100644 --- a/src/models/responseswebsearchuserlocation.ts +++ b/src/models/responseswebsearchuserlocation.ts @@ -3,14 +3,15 @@ * @generated-id: 08377a5f88b1 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; export const ResponsesWebSearchUserLocationType = { - Approximate: "approximate", + Approximate: 'approximate', } as const; export type ResponsesWebSearchUserLocationType = ClosedEnum< typeof ResponsesWebSearchUserLocationType @@ -72,9 +73,7 @@ export function responsesWebSearchUserLocationToJSON( responsesWebSearchUserLocation: ResponsesWebSearchUserLocation, ): string { return JSON.stringify( - ResponsesWebSearchUserLocation$outboundSchema.parse( - responsesWebSearchUserLocation, - ), + ResponsesWebSearchUserLocation$outboundSchema.parse(responsesWebSearchUserLocation), ); } export function responsesWebSearchUserLocationFromJSON( diff --git a/src/models/responsetextconfig.ts b/src/models/responsetextconfig.ts index ad0047e3..6c44ce9d 100644 --- a/src/models/responsetextconfig.ts +++ b/src/models/responsetextconfig.ts @@ -3,25 +3,22 @@ * @generated-id: 0f516033ff9c */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; -import { - ResponseFormatTextConfig, - ResponseFormatTextConfig$inboundSchema, -} from "./responseformattextconfig.js"; +import type { OpenEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; +import type { ResponseFormatTextConfig } from './responseformattextconfig.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import * as openEnums from '../types/enums.js'; +import { ResponseFormatTextConfig$inboundSchema } from './responseformattextconfig.js'; export const ResponseTextConfigVerbosity = { - High: "high", - Low: "low", - Medium: "medium", + High: 'high', + Low: 'low', + Medium: 'medium', } as const; -export type ResponseTextConfigVerbosity = OpenEnum< - typeof ResponseTextConfigVerbosity ->; +export type ResponseTextConfigVerbosity = OpenEnum; /** * Text output configuration including format and verbosity @@ -41,10 +38,7 @@ export const ResponseTextConfigVerbosity$inboundSchema: z.ZodType< > = openEnums.inboundSchema(ResponseTextConfigVerbosity); /** @internal */ -export const ResponseTextConfig$inboundSchema: z.ZodType< - ResponseTextConfig, - unknown -> = z.object({ +export const ResponseTextConfig$inboundSchema: z.ZodType = z.object({ format: ResponseFormatTextConfig$inboundSchema.optional(), verbosity: z.nullable(ResponseTextConfigVerbosity$inboundSchema).optional(), }); diff --git a/src/models/schema0.ts b/src/models/schema0.ts index b2669445..617819bb 100644 --- a/src/models/schema0.ts +++ b/src/models/schema0.ts @@ -3,80 +3,81 @@ * @generated-id: 14bff3bd8497 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type { OpenEnum } from '../types/enums.js'; + +import * as z from 'zod/v4'; +import * as openEnums from '../types/enums.js'; export const Schema0Enum = { - Ai21: "AI21", - AionLabs: "AionLabs", - Alibaba: "Alibaba", - AmazonBedrock: "Amazon Bedrock", - AmazonNova: "Amazon Nova", - Anthropic: "Anthropic", - ArceeAI: "Arcee AI", - AtlasCloud: "AtlasCloud", - Avian: "Avian", - Azure: "Azure", - BaseTen: "BaseTen", - BytePlus: "BytePlus", - BlackForestLabs: "Black Forest Labs", - Cerebras: "Cerebras", - Chutes: "Chutes", - Cirrascale: "Cirrascale", - Clarifai: "Clarifai", - Cloudflare: "Cloudflare", - Cohere: "Cohere", - Crusoe: "Crusoe", - DeepInfra: "DeepInfra", - DeepSeek: "DeepSeek", - Featherless: "Featherless", - Fireworks: "Fireworks", - Friendli: "Friendli", - GMICloud: "GMICloud", - GoPomelo: "GoPomelo", - Google: "Google", - GoogleAIStudio: "Google AI Studio", - Groq: "Groq", - Hyperbolic: "Hyperbolic", - Inception: "Inception", - InferenceNet: "InferenceNet", - Infermatic: "Infermatic", - Inflection: "Inflection", - Liquid: "Liquid", - Mara: "Mara", - Mancer2: "Mancer 2", - Minimax: "Minimax", - ModelRun: "ModelRun", - Mistral: "Mistral", - Modular: "Modular", - MoonshotAI: "Moonshot AI", - Morph: "Morph", - NCompass: "NCompass", - Nebius: "Nebius", - NextBit: "NextBit", - Novita: "Novita", - Nvidia: "Nvidia", - OpenAI: "OpenAI", - OpenInference: "OpenInference", - Parasail: "Parasail", - Perplexity: "Perplexity", - Phala: "Phala", - Relace: "Relace", - SambaNova: "SambaNova", - SiliconFlow: "SiliconFlow", - Sourceful: "Sourceful", - Stealth: "Stealth", - StreamLake: "StreamLake", - Switchpoint: "Switchpoint", - Targon: "Targon", - Together: "Together", - Venice: "Venice", - WandB: "WandB", - Xiaomi: "Xiaomi", - XAI: "xAI", - ZAi: "Z.AI", - FakeProvider: "FakeProvider", + Ai21: 'AI21', + AionLabs: 'AionLabs', + Alibaba: 'Alibaba', + AmazonBedrock: 'Amazon Bedrock', + AmazonNova: 'Amazon Nova', + Anthropic: 'Anthropic', + ArceeAI: 'Arcee AI', + AtlasCloud: 'AtlasCloud', + Avian: 'Avian', + Azure: 'Azure', + BaseTen: 'BaseTen', + BytePlus: 'BytePlus', + BlackForestLabs: 'Black Forest Labs', + Cerebras: 'Cerebras', + Chutes: 'Chutes', + Cirrascale: 'Cirrascale', + Clarifai: 'Clarifai', + Cloudflare: 'Cloudflare', + Cohere: 'Cohere', + Crusoe: 'Crusoe', + DeepInfra: 'DeepInfra', + DeepSeek: 'DeepSeek', + Featherless: 'Featherless', + Fireworks: 'Fireworks', + Friendli: 'Friendli', + GMICloud: 'GMICloud', + GoPomelo: 'GoPomelo', + Google: 'Google', + GoogleAIStudio: 'Google AI Studio', + Groq: 'Groq', + Hyperbolic: 'Hyperbolic', + Inception: 'Inception', + InferenceNet: 'InferenceNet', + Infermatic: 'Infermatic', + Inflection: 'Inflection', + Liquid: 'Liquid', + Mara: 'Mara', + Mancer2: 'Mancer 2', + Minimax: 'Minimax', + ModelRun: 'ModelRun', + Mistral: 'Mistral', + Modular: 'Modular', + MoonshotAI: 'Moonshot AI', + Morph: 'Morph', + NCompass: 'NCompass', + Nebius: 'Nebius', + NextBit: 'NextBit', + Novita: 'Novita', + Nvidia: 'Nvidia', + OpenAI: 'OpenAI', + OpenInference: 'OpenInference', + Parasail: 'Parasail', + Perplexity: 'Perplexity', + Phala: 'Phala', + Relace: 'Relace', + SambaNova: 'SambaNova', + SiliconFlow: 'SiliconFlow', + Sourceful: 'Sourceful', + Stealth: 'Stealth', + StreamLake: 'StreamLake', + Switchpoint: 'Switchpoint', + Targon: 'Targon', + Together: 'Together', + Venice: 'Venice', + WandB: 'WandB', + Xiaomi: 'Xiaomi', + XAI: 'xAI', + ZAi: 'Z.AI', + FakeProvider: 'FakeProvider', } as const; export type Schema0Enum = OpenEnum; @@ -90,8 +91,10 @@ export const Schema0Enum$outboundSchema: z.ZodType = export type Schema0$Outbound = string | string; /** @internal */ -export const Schema0$outboundSchema: z.ZodType = z - .union([Schema0Enum$outboundSchema, z.string()]); +export const Schema0$outboundSchema: z.ZodType = z.union([ + Schema0Enum$outboundSchema, + z.string(), +]); export function schema0ToJSON(schema0: Schema0): string { return JSON.stringify(Schema0$outboundSchema.parse(schema0)); diff --git a/src/models/schema3.ts b/src/models/schema3.ts index 366ab7b1..4bb97940 100644 --- a/src/models/schema3.ts +++ b/src/models/schema3.ts @@ -3,24 +3,25 @@ * @generated-id: 6f7380bcbcea */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { OpenEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; +import * as openEnums from '../types/enums.js'; export const Schema5 = { - Unknown: "unknown", - OpenaiResponsesV1: "openai-responses-v1", - XaiResponsesV1: "xai-responses-v1", - AnthropicClaudeV1: "anthropic-claude-v1", - GoogleGeminiV1: "google-gemini-v1", + Unknown: 'unknown', + OpenaiResponsesV1: 'openai-responses-v1', + XaiResponsesV1: 'xai-responses-v1', + AnthropicClaudeV1: 'anthropic-claude-v1', + GoogleGeminiV1: 'google-gemini-v1', } as const; export type Schema5 = OpenEnum; export type Schema3ReasoningText = { - type: "reasoning.text"; + type: 'reasoning.text'; text?: string | null | undefined; signature?: string | null | undefined; id?: string | null | undefined; @@ -29,7 +30,7 @@ export type Schema3ReasoningText = { }; export type Schema3ReasoningEncrypted = { - type: "reasoning.encrypted"; + type: 'reasoning.encrypted'; data: string; id?: string | null | undefined; format?: Schema5 | null | undefined; @@ -37,34 +38,28 @@ export type Schema3ReasoningEncrypted = { }; export type Schema3ReasoningSummary = { - type: "reasoning.summary"; + type: 'reasoning.summary'; summary: string; id?: string | null | undefined; format?: Schema5 | null | undefined; index?: number | undefined; }; -export type Schema3 = - | Schema3ReasoningSummary - | Schema3ReasoningEncrypted - | Schema3ReasoningText; +export type Schema3 = Schema3ReasoningSummary | Schema3ReasoningEncrypted | Schema3ReasoningText; /** @internal */ -export const Schema5$inboundSchema: z.ZodType = openEnums - .inboundSchema(Schema5); +export const Schema5$inboundSchema: z.ZodType = openEnums.inboundSchema(Schema5); /** @internal */ -export const Schema3ReasoningText$inboundSchema: z.ZodType< - Schema3ReasoningText, - unknown -> = z.object({ - type: z.literal("reasoning.text"), - text: z.nullable(z.string()).optional(), - signature: z.nullable(z.string()).optional(), - id: z.nullable(z.string()).optional(), - format: z.nullable(Schema5$inboundSchema).optional(), - index: z.number().optional(), -}); +export const Schema3ReasoningText$inboundSchema: z.ZodType = + z.object({ + type: z.literal('reasoning.text'), + text: z.nullable(z.string()).optional(), + signature: z.nullable(z.string()).optional(), + id: z.nullable(z.string()).optional(), + format: z.nullable(Schema5$inboundSchema).optional(), + index: z.number().optional(), + }); export function schema3ReasoningTextFromJSON( jsonString: string, @@ -81,7 +76,7 @@ export const Schema3ReasoningEncrypted$inboundSchema: z.ZodType< Schema3ReasoningEncrypted, unknown > = z.object({ - type: z.literal("reasoning.encrypted"), + type: z.literal('reasoning.encrypted'), data: z.string(), id: z.nullable(z.string()).optional(), format: z.nullable(Schema5$inboundSchema).optional(), @@ -99,16 +94,14 @@ export function schema3ReasoningEncryptedFromJSON( } /** @internal */ -export const Schema3ReasoningSummary$inboundSchema: z.ZodType< - Schema3ReasoningSummary, - unknown -> = z.object({ - type: z.literal("reasoning.summary"), - summary: z.string(), - id: z.nullable(z.string()).optional(), - format: z.nullable(Schema5$inboundSchema).optional(), - index: z.number().optional(), -}); +export const Schema3ReasoningSummary$inboundSchema: z.ZodType = + z.object({ + type: z.literal('reasoning.summary'), + summary: z.string(), + id: z.nullable(z.string()).optional(), + format: z.nullable(Schema5$inboundSchema).optional(), + index: z.number().optional(), + }); export function schema3ReasoningSummaryFromJSON( jsonString: string, @@ -127,9 +120,7 @@ export const Schema3$inboundSchema: z.ZodType = z.union([ z.lazy(() => Schema3ReasoningText$inboundSchema), ]); -export function schema3FromJSON( - jsonString: string, -): SafeParseResult { +export function schema3FromJSON(jsonString: string): SafeParseResult { return safeParse( jsonString, (x) => Schema3$inboundSchema.parse(JSON.parse(x)), diff --git a/src/models/security.ts b/src/models/security.ts index af44b3ab..9da23dd8 100644 --- a/src/models/security.ts +++ b/src/models/security.ts @@ -3,7 +3,7 @@ * @generated-id: d90c6c784ca5 */ -import * as z from "zod/v4"; +import * as z from 'zod/v4'; export type Security = { apiKey?: string | undefined; @@ -15,10 +15,9 @@ export type Security$Outbound = { }; /** @internal */ -export const Security$outboundSchema: z.ZodType = z - .object({ - apiKey: z.string().optional(), - }); +export const Security$outboundSchema: z.ZodType = z.object({ + apiKey: z.string().optional(), +}); export function securityToJSON(security: Security): string { return JSON.stringify(Security$outboundSchema.parse(security)); diff --git a/src/models/serviceunavailableresponseerrordata.ts b/src/models/serviceunavailableresponseerrordata.ts index f6242052..4d603414 100644 --- a/src/models/serviceunavailableresponseerrordata.ts +++ b/src/models/serviceunavailableresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: 842927f7dc14 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for ServiceUnavailableResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type ServiceUnavailableResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ @@ -32,8 +38,7 @@ export function serviceUnavailableResponseErrorDataFromJSON( ): SafeParseResult { return safeParse( jsonString, - (x) => - ServiceUnavailableResponseErrorData$inboundSchema.parse(JSON.parse(x)), + (x) => ServiceUnavailableResponseErrorData$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'ServiceUnavailableResponseErrorData' from JSON`, ); } diff --git a/src/models/systemmessage.ts b/src/models/systemmessage.ts index 68f3666f..be561ec5 100644 --- a/src/models/systemmessage.ts +++ b/src/models/systemmessage.ts @@ -3,59 +3,55 @@ * @generated-id: 2a179ca48627 */ -import * as z from "zod/v4"; -import { +import type { ChatMessageContentItemText, ChatMessageContentItemText$Outbound, - ChatMessageContentItemText$outboundSchema, -} from "./chatmessagecontentitemtext.js"; +} from './chatmessagecontentitemtext.js'; + +import * as z from 'zod/v4'; +import { ChatMessageContentItemText$outboundSchema } from './chatmessagecontentitemtext.js'; export type SystemMessageContent = string | Array; export type SystemMessage = { - role: "system"; + role: 'system'; content: string | Array; name?: string | undefined; }; /** @internal */ -export type SystemMessageContent$Outbound = - | string - | Array; +export type SystemMessageContent$Outbound = string | Array; /** @internal */ export const SystemMessageContent$outboundSchema: z.ZodType< SystemMessageContent$Outbound, SystemMessageContent -> = z.union([z.string(), z.array(ChatMessageContentItemText$outboundSchema)]); - -export function systemMessageContentToJSON( - systemMessageContent: SystemMessageContent, -): string { - return JSON.stringify( - SystemMessageContent$outboundSchema.parse(systemMessageContent), - ); +> = z.union([ + z.string(), + z.array(ChatMessageContentItemText$outboundSchema), +]); + +export function systemMessageContentToJSON(systemMessageContent: SystemMessageContent): string { + return JSON.stringify(SystemMessageContent$outboundSchema.parse(systemMessageContent)); } /** @internal */ export type SystemMessage$Outbound = { - role: "system"; + role: 'system'; content: string | Array; name?: string | undefined; }; /** @internal */ -export const SystemMessage$outboundSchema: z.ZodType< - SystemMessage$Outbound, - SystemMessage -> = z.object({ - role: z.literal("system"), - content: z.union([ - z.string(), - z.array(ChatMessageContentItemText$outboundSchema), - ]), - name: z.string().optional(), -}); +export const SystemMessage$outboundSchema: z.ZodType = + z.object({ + role: z.literal('system'), + content: z.union([ + z.string(), + z.array(ChatMessageContentItemText$outboundSchema), + ]), + name: z.string().optional(), + }); export function systemMessageToJSON(systemMessage: SystemMessage): string { return JSON.stringify(SystemMessage$outboundSchema.parse(systemMessage)); diff --git a/src/models/toolcallstatus.ts b/src/models/toolcallstatus.ts index 1585e3f9..f5585555 100644 --- a/src/models/toolcallstatus.ts +++ b/src/models/toolcallstatus.ts @@ -3,14 +3,15 @@ * @generated-id: 54eb9c06bedb */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const ToolCallStatus = { - InProgress: "in_progress", - Completed: "completed", - Incomplete: "incomplete", + InProgress: 'in_progress', + Completed: 'completed', + Incomplete: 'incomplete', } as const; export type ToolCallStatus = OpenEnum; diff --git a/src/models/tooldefinitionjson.ts b/src/models/tooldefinitionjson.ts index 8456579f..80ce848c 100644 --- a/src/models/tooldefinitionjson.ts +++ b/src/models/tooldefinitionjson.ts @@ -3,17 +3,21 @@ * @generated-id: 546c340f3013 */ -import * as z from "zod/v4"; +import * as z from 'zod/v4'; export type ToolDefinitionJsonFunction = { name: string; description?: string | undefined; - parameters?: { [k: string]: any } | undefined; + parameters?: + | { + [k: string]: any; + } + | undefined; strict?: boolean | null | undefined; }; export type ToolDefinitionJson = { - type: "function"; + type: 'function'; function: ToolDefinitionJsonFunction; }; @@ -21,7 +25,11 @@ export type ToolDefinitionJson = { export type ToolDefinitionJsonFunction$Outbound = { name: string; description?: string | undefined; - parameters?: { [k: string]: any } | undefined; + parameters?: + | { + [k: string]: any; + } + | undefined; strict?: boolean | null | undefined; }; @@ -46,7 +54,7 @@ export function toolDefinitionJsonFunctionToJSON( /** @internal */ export type ToolDefinitionJson$Outbound = { - type: "function"; + type: 'function'; function: ToolDefinitionJsonFunction$Outbound; }; @@ -55,14 +63,10 @@ export const ToolDefinitionJson$outboundSchema: z.ZodType< ToolDefinitionJson$Outbound, ToolDefinitionJson > = z.object({ - type: z.literal("function"), + type: z.literal('function'), function: z.lazy(() => ToolDefinitionJsonFunction$outboundSchema), }); -export function toolDefinitionJsonToJSON( - toolDefinitionJson: ToolDefinitionJson, -): string { - return JSON.stringify( - ToolDefinitionJson$outboundSchema.parse(toolDefinitionJson), - ); +export function toolDefinitionJsonToJSON(toolDefinitionJson: ToolDefinitionJson): string { + return JSON.stringify(ToolDefinitionJson$outboundSchema.parse(toolDefinitionJson)); } diff --git a/src/models/toolresponsemessage.ts b/src/models/toolresponsemessage.ts index 1cadd683..01bfdf27 100644 --- a/src/models/toolresponsemessage.ts +++ b/src/models/toolresponsemessage.ts @@ -3,32 +3,34 @@ * @generated-id: 1122bbfb530b */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { +import type { ChatMessageContentItem, ChatMessageContentItem$Outbound, - ChatMessageContentItem$outboundSchema, -} from "./chatmessagecontentitem.js"; +} from './chatmessagecontentitem.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { ChatMessageContentItem$outboundSchema } from './chatmessagecontentitem.js'; export type ToolResponseMessageContent = string | Array; export type ToolResponseMessage = { - role: "tool"; + role: 'tool'; content: string | Array; toolCallId: string; }; /** @internal */ -export type ToolResponseMessageContent$Outbound = - | string - | Array; +export type ToolResponseMessageContent$Outbound = string | Array; /** @internal */ export const ToolResponseMessageContent$outboundSchema: z.ZodType< ToolResponseMessageContent$Outbound, ToolResponseMessageContent -> = z.union([z.string(), z.array(ChatMessageContentItem$outboundSchema)]); +> = z.union([ + z.string(), + z.array(ChatMessageContentItem$outboundSchema), +]); export function toolResponseMessageContentToJSON( toolResponseMessageContent: ToolResponseMessageContent, @@ -40,7 +42,7 @@ export function toolResponseMessageContentToJSON( /** @internal */ export type ToolResponseMessage$Outbound = { - role: "tool"; + role: 'tool'; content: string | Array; tool_call_id: string; }; @@ -49,23 +51,21 @@ export type ToolResponseMessage$Outbound = { export const ToolResponseMessage$outboundSchema: z.ZodType< ToolResponseMessage$Outbound, ToolResponseMessage -> = z.object({ - role: z.literal("tool"), - content: z.union([ - z.string(), - z.array(ChatMessageContentItem$outboundSchema), - ]), - toolCallId: z.string(), -}).transform((v) => { - return remap$(v, { - toolCallId: "tool_call_id", +> = z + .object({ + role: z.literal('tool'), + content: z.union([ + z.string(), + z.array(ChatMessageContentItem$outboundSchema), + ]), + toolCallId: z.string(), + }) + .transform((v) => { + return remap$(v, { + toolCallId: 'tool_call_id', + }); }); -}); -export function toolResponseMessageToJSON( - toolResponseMessage: ToolResponseMessage, -): string { - return JSON.stringify( - ToolResponseMessage$outboundSchema.parse(toolResponseMessage), - ); +export function toolResponseMessageToJSON(toolResponseMessage: ToolResponseMessage): string { + return JSON.stringify(ToolResponseMessage$outboundSchema.parse(toolResponseMessage)); } diff --git a/src/models/toomanyrequestsresponseerrordata.ts b/src/models/toomanyrequestsresponseerrordata.ts index 5b47d772..e1d9eb44 100644 --- a/src/models/toomanyrequestsresponseerrordata.ts +++ b/src/models/toomanyrequestsresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: ff9492357bd9 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for TooManyRequestsResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type TooManyRequestsResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ diff --git a/src/models/topproviderinfo.ts b/src/models/topproviderinfo.ts index c95a2f12..0e9e4980 100644 --- a/src/models/topproviderinfo.ts +++ b/src/models/topproviderinfo.ts @@ -3,11 +3,12 @@ * @generated-id: 7439c7b1a9c6 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; /** * Information about the top provider for this model @@ -28,20 +29,19 @@ export type TopProviderInfo = { }; /** @internal */ -export const TopProviderInfo$inboundSchema: z.ZodType< - TopProviderInfo, - unknown -> = z.object({ - context_length: z.nullable(z.number()).optional(), - max_completion_tokens: z.nullable(z.number()).optional(), - is_moderated: z.boolean(), -}).transform((v) => { - return remap$(v, { - "context_length": "contextLength", - "max_completion_tokens": "maxCompletionTokens", - "is_moderated": "isModerated", +export const TopProviderInfo$inboundSchema: z.ZodType = z + .object({ + context_length: z.nullable(z.number()).optional(), + max_completion_tokens: z.nullable(z.number()).optional(), + is_moderated: z.boolean(), + }) + .transform((v) => { + return remap$(v, { + context_length: 'contextLength', + max_completion_tokens: 'maxCompletionTokens', + is_moderated: 'isModerated', + }); }); -}); export function topProviderInfoFromJSON( jsonString: string, diff --git a/src/models/unauthorizedresponseerrordata.ts b/src/models/unauthorizedresponseerrordata.ts index 3b24025f..e807fa2b 100644 --- a/src/models/unauthorizedresponseerrordata.ts +++ b/src/models/unauthorizedresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: d335c48e0c3e */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for UnauthorizedResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type UnauthorizedResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ diff --git a/src/models/unprocessableentityresponseerrordata.ts b/src/models/unprocessableentityresponseerrordata.ts index 0c68c696..7cab4b93 100644 --- a/src/models/unprocessableentityresponseerrordata.ts +++ b/src/models/unprocessableentityresponseerrordata.ts @@ -3,10 +3,11 @@ * @generated-id: 557063315301 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; /** * Error data for UnprocessableEntityResponse @@ -14,7 +15,12 @@ import { SDKValidationError } from "./errors/sdkvalidationerror.js"; export type UnprocessableEntityResponseErrorData = { code: number; message: string; - metadata?: { [k: string]: any | null } | null | undefined; + metadata?: + | { + [k: string]: any | null; + } + | null + | undefined; }; /** @internal */ @@ -32,8 +38,7 @@ export function unprocessableEntityResponseErrorDataFromJSON( ): SafeParseResult { return safeParse( jsonString, - (x) => - UnprocessableEntityResponseErrorData$inboundSchema.parse(JSON.parse(x)), + (x) => UnprocessableEntityResponseErrorData$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'UnprocessableEntityResponseErrorData' from JSON`, ); } diff --git a/src/models/urlcitation.ts b/src/models/urlcitation.ts index 4d03e2fd..b15ad2e4 100644 --- a/src/models/urlcitation.ts +++ b/src/models/urlcitation.ts @@ -3,14 +3,15 @@ * @generated-id: ccd6ecd62c64 */ -import * as z from "zod/v4"; -import { remap as remap$ } from "../lib/primitives.js"; -import { safeParse } from "../lib/schemas.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { remap as remap$ } from '../lib/primitives.js'; +import { safeParse } from '../lib/schemas.js'; export type URLCitation = { - type: "url_citation"; + type: 'url_citation'; url: string; title: string; startIndex: number; @@ -20,20 +21,21 @@ export type URLCitation = { /** @internal */ export const URLCitation$inboundSchema: z.ZodType = z .object({ - type: z.literal("url_citation"), + type: z.literal('url_citation'), url: z.string(), title: z.string(), start_index: z.number(), end_index: z.number(), - }).transform((v) => { + }) + .transform((v) => { return remap$(v, { - "start_index": "startIndex", - "end_index": "endIndex", + start_index: 'startIndex', + end_index: 'endIndex', }); }); /** @internal */ export type URLCitation$Outbound = { - type: "url_citation"; + type: 'url_citation'; url: string; title: string; start_index: number; @@ -41,21 +43,20 @@ export type URLCitation$Outbound = { }; /** @internal */ -export const URLCitation$outboundSchema: z.ZodType< - URLCitation$Outbound, - URLCitation -> = z.object({ - type: z.literal("url_citation"), - url: z.string(), - title: z.string(), - startIndex: z.number(), - endIndex: z.number(), -}).transform((v) => { - return remap$(v, { - startIndex: "start_index", - endIndex: "end_index", +export const URLCitation$outboundSchema: z.ZodType = z + .object({ + type: z.literal('url_citation'), + url: z.string(), + title: z.string(), + startIndex: z.number(), + endIndex: z.number(), + }) + .transform((v) => { + return remap$(v, { + startIndex: 'start_index', + endIndex: 'end_index', + }); }); -}); export function urlCitationToJSON(urlCitation: URLCitation): string { return JSON.stringify(URLCitation$outboundSchema.parse(urlCitation)); diff --git a/src/models/usermessage.ts b/src/models/usermessage.ts index ec761e7f..ef9e55d0 100644 --- a/src/models/usermessage.ts +++ b/src/models/usermessage.ts @@ -3,53 +3,48 @@ * @generated-id: e34f73b285e1 */ -import * as z from "zod/v4"; -import { +import type { ChatMessageContentItem, ChatMessageContentItem$Outbound, - ChatMessageContentItem$outboundSchema, -} from "./chatmessagecontentitem.js"; +} from './chatmessagecontentitem.js'; + +import * as z from 'zod/v4'; +import { ChatMessageContentItem$outboundSchema } from './chatmessagecontentitem.js'; export type UserMessageContent = string | Array; export type UserMessage = { - role: "user"; + role: 'user'; content: string | Array; name?: string | undefined; }; /** @internal */ -export type UserMessageContent$Outbound = - | string - | Array; +export type UserMessageContent$Outbound = string | Array; /** @internal */ export const UserMessageContent$outboundSchema: z.ZodType< UserMessageContent$Outbound, UserMessageContent -> = z.union([z.string(), z.array(ChatMessageContentItem$outboundSchema)]); - -export function userMessageContentToJSON( - userMessageContent: UserMessageContent, -): string { - return JSON.stringify( - UserMessageContent$outboundSchema.parse(userMessageContent), - ); +> = z.union([ + z.string(), + z.array(ChatMessageContentItem$outboundSchema), +]); + +export function userMessageContentToJSON(userMessageContent: UserMessageContent): string { + return JSON.stringify(UserMessageContent$outboundSchema.parse(userMessageContent)); } /** @internal */ export type UserMessage$Outbound = { - role: "user"; + role: 'user'; content: string | Array; name?: string | undefined; }; /** @internal */ -export const UserMessage$outboundSchema: z.ZodType< - UserMessage$Outbound, - UserMessage -> = z.object({ - role: z.literal("user"), +export const UserMessage$outboundSchema: z.ZodType = z.object({ + role: z.literal('user'), content: z.union([ z.string(), z.array(ChatMessageContentItem$outboundSchema), diff --git a/src/models/websearchengine.ts b/src/models/websearchengine.ts index 5d8c6ef9..19dba5b1 100644 --- a/src/models/websearchengine.ts +++ b/src/models/websearchengine.ts @@ -3,16 +3,17 @@ * @generated-id: 49b0152fd59a */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; /** * The search engine to use for web search. */ export const WebSearchEngine = { - Native: "native", - Exa: "exa", + Native: 'native', + Exa: 'exa', } as const; /** * The search engine to use for web search. @@ -20,7 +21,5 @@ export const WebSearchEngine = { export type WebSearchEngine = OpenEnum; /** @internal */ -export const WebSearchEngine$outboundSchema: z.ZodType< - string, - WebSearchEngine -> = openEnums.outboundSchema(WebSearchEngine); +export const WebSearchEngine$outboundSchema: z.ZodType = + openEnums.outboundSchema(WebSearchEngine); diff --git a/src/models/websearchpreviewtooluserlocation.ts b/src/models/websearchpreviewtooluserlocation.ts index 38b0d83f..8081df4b 100644 --- a/src/models/websearchpreviewtooluserlocation.ts +++ b/src/models/websearchpreviewtooluserlocation.ts @@ -3,14 +3,15 @@ * @generated-id: cb1960e09942 */ -import * as z from "zod/v4"; -import { safeParse } from "../lib/schemas.js"; -import { ClosedEnum } from "../types/enums.js"; -import { Result as SafeParseResult } from "../types/fp.js"; -import { SDKValidationError } from "./errors/sdkvalidationerror.js"; +import type { ClosedEnum } from '../types/enums.js'; +import type { Result as SafeParseResult } from '../types/fp.js'; +import type { SDKValidationError } from './errors/sdkvalidationerror.js'; + +import * as z from 'zod/v4'; +import { safeParse } from '../lib/schemas.js'; export const WebSearchPreviewToolUserLocationType = { - Approximate: "approximate", + Approximate: 'approximate', } as const; export type WebSearchPreviewToolUserLocationType = ClosedEnum< typeof WebSearchPreviewToolUserLocationType @@ -69,9 +70,7 @@ export function webSearchPreviewToolUserLocationToJSON( webSearchPreviewToolUserLocation: WebSearchPreviewToolUserLocation, ): string { return JSON.stringify( - WebSearchPreviewToolUserLocation$outboundSchema.parse( - webSearchPreviewToolUserLocation, - ), + WebSearchPreviewToolUserLocation$outboundSchema.parse(webSearchPreviewToolUserLocation), ); } export function webSearchPreviewToolUserLocationFromJSON( diff --git a/src/models/websearchstatus.ts b/src/models/websearchstatus.ts index 3243a6ae..2c83d1d3 100644 --- a/src/models/websearchstatus.ts +++ b/src/models/websearchstatus.ts @@ -3,25 +3,22 @@ * @generated-id: 55795920a937 */ -import * as z from "zod/v4"; -import * as openEnums from "../types/enums.js"; -import { OpenEnum } from "../types/enums.js"; +import type * as z from 'zod/v4'; +import type { OpenEnum } from '../types/enums.js'; + +import * as openEnums from '../types/enums.js'; export const WebSearchStatus = { - Completed: "completed", - Searching: "searching", - InProgress: "in_progress", - Failed: "failed", + Completed: 'completed', + Searching: 'searching', + InProgress: 'in_progress', + Failed: 'failed', } as const; export type WebSearchStatus = OpenEnum; /** @internal */ -export const WebSearchStatus$inboundSchema: z.ZodType< - WebSearchStatus, - unknown -> = openEnums.inboundSchema(WebSearchStatus); +export const WebSearchStatus$inboundSchema: z.ZodType = + openEnums.inboundSchema(WebSearchStatus); /** @internal */ -export const WebSearchStatus$outboundSchema: z.ZodType< - string, - WebSearchStatus -> = openEnums.outboundSchema(WebSearchStatus); +export const WebSearchStatus$outboundSchema: z.ZodType = + openEnums.outboundSchema(WebSearchStatus); diff --git a/src/sdk/analytics.ts b/src/sdk/analytics.ts index 41f17bc8..fdf71017 100644 --- a/src/sdk/analytics.ts +++ b/src/sdk/analytics.ts @@ -3,10 +3,12 @@ * @generated-id: 411d91261be3 */ -import { analyticsGetUserActivity } from "../funcs/analyticsGetUserActivity.js"; -import { ClientSDK, RequestOptions } from "../lib/sdks.js"; -import * as operations from "../models/operations/index.js"; -import { unwrapAsync } from "../types/fp.js"; +import type { RequestOptions } from '../lib/sdks.js'; +import type * as operations from '../models/operations/index.js'; + +import { analyticsGetUserActivity } from '../funcs/analyticsGetUserActivity.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { unwrapAsync } from '../types/fp.js'; export class Analytics extends ClientSDK { /** @@ -19,10 +21,6 @@ export class Analytics extends ClientSDK { request?: operations.GetUserActivityRequest | undefined, options?: RequestOptions, ): Promise { - return unwrapAsync(analyticsGetUserActivity( - this, - request, - options, - )); + return unwrapAsync(analyticsGetUserActivity(this, request, options)); } } diff --git a/src/sdk/apikeys.ts b/src/sdk/apikeys.ts index 87017a4d..b765c68a 100644 --- a/src/sdk/apikeys.ts +++ b/src/sdk/apikeys.ts @@ -3,15 +3,17 @@ * @generated-id: 5dda931501e1 */ -import { apiKeysCreate } from "../funcs/apiKeysCreate.js"; -import { apiKeysDelete } from "../funcs/apiKeysDelete.js"; -import { apiKeysGet } from "../funcs/apiKeysGet.js"; -import { apiKeysGetCurrentKeyMetadata } from "../funcs/apiKeysGetCurrentKeyMetadata.js"; -import { apiKeysList } from "../funcs/apiKeysList.js"; -import { apiKeysUpdate } from "../funcs/apiKeysUpdate.js"; -import { ClientSDK, RequestOptions } from "../lib/sdks.js"; -import * as operations from "../models/operations/index.js"; -import { unwrapAsync } from "../types/fp.js"; +import type { RequestOptions } from '../lib/sdks.js'; +import type * as operations from '../models/operations/index.js'; + +import { apiKeysCreate } from '../funcs/apiKeysCreate.js'; +import { apiKeysDelete } from '../funcs/apiKeysDelete.js'; +import { apiKeysGet } from '../funcs/apiKeysGet.js'; +import { apiKeysGetCurrentKeyMetadata } from '../funcs/apiKeysGetCurrentKeyMetadata.js'; +import { apiKeysList } from '../funcs/apiKeysList.js'; +import { apiKeysUpdate } from '../funcs/apiKeysUpdate.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { unwrapAsync } from '../types/fp.js'; export class APIKeys extends ClientSDK { /** @@ -21,11 +23,7 @@ export class APIKeys extends ClientSDK { request?: operations.ListRequest | undefined, options?: RequestOptions, ): Promise { - return unwrapAsync(apiKeysList( - this, - request, - options, - )); + return unwrapAsync(apiKeysList(this, request, options)); } /** @@ -35,11 +33,7 @@ export class APIKeys extends ClientSDK { request: operations.CreateKeysRequest, options?: RequestOptions, ): Promise { - return unwrapAsync(apiKeysCreate( - this, - request, - options, - )); + return unwrapAsync(apiKeysCreate(this, request, options)); } /** @@ -49,11 +43,7 @@ export class APIKeys extends ClientSDK { request: operations.UpdateKeysRequest, options?: RequestOptions, ): Promise { - return unwrapAsync(apiKeysUpdate( - this, - request, - options, - )); + return unwrapAsync(apiKeysUpdate(this, request, options)); } /** @@ -63,11 +53,7 @@ export class APIKeys extends ClientSDK { request: operations.DeleteKeysRequest, options?: RequestOptions, ): Promise { - return unwrapAsync(apiKeysDelete( - this, - request, - options, - )); + return unwrapAsync(apiKeysDelete(this, request, options)); } /** @@ -77,11 +63,7 @@ export class APIKeys extends ClientSDK { request: operations.GetKeyRequest, options?: RequestOptions, ): Promise { - return unwrapAsync(apiKeysGet( - this, - request, - options, - )); + return unwrapAsync(apiKeysGet(this, request, options)); } /** @@ -90,12 +72,7 @@ export class APIKeys extends ClientSDK { * @remarks * Get information on the API key associated with the current authentication session */ - async getCurrentKeyMetadata( - options?: RequestOptions, - ): Promise { - return unwrapAsync(apiKeysGetCurrentKeyMetadata( - this, - options, - )); + async getCurrentKeyMetadata(options?: RequestOptions): Promise { + return unwrapAsync(apiKeysGetCurrentKeyMetadata(this, options)); } } diff --git a/src/sdk/beta.ts b/src/sdk/beta.ts index 0fe9a46a..d5a4a0ab 100644 --- a/src/sdk/beta.ts +++ b/src/sdk/beta.ts @@ -3,8 +3,8 @@ * @generated-id: afeac65e28f8 */ -import { ClientSDK } from "../lib/sdks.js"; -import { Responses } from "./responses.js"; +import { ClientSDK } from '../lib/sdks.js'; +import { Responses } from './responses.js'; export class Beta extends ClientSDK { private _responses?: Responses; diff --git a/src/sdk/chat.ts b/src/sdk/chat.ts index fe7bba6e..859f7c72 100644 --- a/src/sdk/chat.ts +++ b/src/sdk/chat.ts @@ -3,12 +3,14 @@ * @generated-id: c56babc22a20 */ -import { chatSend } from "../funcs/chatSend.js"; -import { EventStream } from "../lib/event-streams.js"; -import { ClientSDK, RequestOptions } from "../lib/sdks.js"; -import * as models from "../models/index.js"; -import * as operations from "../models/operations/index.js"; -import { unwrapAsync } from "../types/fp.js"; +import type { EventStream } from '../lib/event-streams.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type * as models from '../models/index.js'; +import type * as operations from '../models/operations/index.js'; + +import { chatSend } from '../funcs/chatSend.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { unwrapAsync } from '../types/fp.js'; export class Chat extends ClientSDK { /** @@ -18,11 +20,15 @@ export class Chat extends ClientSDK { * Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes. */ async send( - request: models.ChatGenerationParams & { stream?: false | undefined }, + request: models.ChatGenerationParams & { + stream?: false | undefined; + }, options?: RequestOptions, ): Promise; async send( - request: models.ChatGenerationParams & { stream: true }, + request: models.ChatGenerationParams & { + stream: true; + }, options?: RequestOptions, ): Promise>; async send( @@ -33,10 +39,6 @@ export class Chat extends ClientSDK { request: models.ChatGenerationParams, options?: RequestOptions, ): Promise { - return unwrapAsync(chatSend( - this, - request, - options, - )); + return unwrapAsync(chatSend(this, request, options)); } } diff --git a/src/sdk/completions.ts b/src/sdk/completions.ts index ac2caf3a..9e72f2dc 100644 --- a/src/sdk/completions.ts +++ b/src/sdk/completions.ts @@ -3,10 +3,12 @@ * @generated-id: b452d35d53b4 */ -import { completionsGenerate } from "../funcs/completionsGenerate.js"; -import { ClientSDK, RequestOptions } from "../lib/sdks.js"; -import * as models from "../models/index.js"; -import { unwrapAsync } from "../types/fp.js"; +import type { RequestOptions } from '../lib/sdks.js'; +import type * as models from '../models/index.js'; + +import { completionsGenerate } from '../funcs/completionsGenerate.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { unwrapAsync } from '../types/fp.js'; export class Completions extends ClientSDK { /** @@ -19,10 +21,6 @@ export class Completions extends ClientSDK { request: models.CompletionCreateParams, options?: RequestOptions, ): Promise { - return unwrapAsync(completionsGenerate( - this, - request, - options, - )); + return unwrapAsync(completionsGenerate(this, request, options)); } } diff --git a/src/sdk/credits.ts b/src/sdk/credits.ts index 9c43c6dd..7496c60e 100644 --- a/src/sdk/credits.ts +++ b/src/sdk/credits.ts @@ -3,12 +3,14 @@ * @generated-id: c72074b5f165 */ -import { creditsCreateCoinbaseCharge } from "../funcs/creditsCreateCoinbaseCharge.js"; -import { creditsGetCredits } from "../funcs/creditsGetCredits.js"; -import { ClientSDK, RequestOptions } from "../lib/sdks.js"; -import * as models from "../models/index.js"; -import * as operations from "../models/operations/index.js"; -import { unwrapAsync } from "../types/fp.js"; +import type { RequestOptions } from '../lib/sdks.js'; +import type * as models from '../models/index.js'; +import type * as operations from '../models/operations/index.js'; + +import { creditsCreateCoinbaseCharge } from '../funcs/creditsCreateCoinbaseCharge.js'; +import { creditsGetCredits } from '../funcs/creditsGetCredits.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { unwrapAsync } from '../types/fp.js'; export class Credits extends ClientSDK { /** @@ -17,13 +19,8 @@ export class Credits extends ClientSDK { * @remarks * Get total credits purchased and used for the authenticated user */ - async getCredits( - options?: RequestOptions, - ): Promise { - return unwrapAsync(creditsGetCredits( - this, - options, - )); + async getCredits(options?: RequestOptions): Promise { + return unwrapAsync(creditsGetCredits(this, options)); } /** @@ -37,11 +34,6 @@ export class Credits extends ClientSDK { request: models.CreateChargeRequest, options?: RequestOptions, ): Promise { - return unwrapAsync(creditsCreateCoinbaseCharge( - this, - security, - request, - options, - )); + return unwrapAsync(creditsCreateCoinbaseCharge(this, security, request, options)); } } diff --git a/src/sdk/embeddings.ts b/src/sdk/embeddings.ts index 1607646a..280495de 100644 --- a/src/sdk/embeddings.ts +++ b/src/sdk/embeddings.ts @@ -3,12 +3,14 @@ * @generated-id: 70cbb18bedaf */ -import { embeddingsGenerate } from "../funcs/embeddingsGenerate.js"; -import { embeddingsListModels } from "../funcs/embeddingsListModels.js"; -import { ClientSDK, RequestOptions } from "../lib/sdks.js"; -import * as models from "../models/index.js"; -import * as operations from "../models/operations/index.js"; -import { unwrapAsync } from "../types/fp.js"; +import type { RequestOptions } from '../lib/sdks.js'; +import type * as models from '../models/index.js'; +import type * as operations from '../models/operations/index.js'; + +import { embeddingsGenerate } from '../funcs/embeddingsGenerate.js'; +import { embeddingsListModels } from '../funcs/embeddingsListModels.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { unwrapAsync } from '../types/fp.js'; export class Embeddings extends ClientSDK { /** @@ -21,11 +23,7 @@ export class Embeddings extends ClientSDK { request: operations.CreateEmbeddingsRequest, options?: RequestOptions, ): Promise { - return unwrapAsync(embeddingsGenerate( - this, - request, - options, - )); + return unwrapAsync(embeddingsGenerate(this, request, options)); } /** @@ -34,12 +32,7 @@ export class Embeddings extends ClientSDK { * @remarks * Returns a list of all available embeddings models and their properties */ - async listModels( - options?: RequestOptions, - ): Promise { - return unwrapAsync(embeddingsListModels( - this, - options, - )); + async listModels(options?: RequestOptions): Promise { + return unwrapAsync(embeddingsListModels(this, options)); } } diff --git a/src/sdk/endpoints.ts b/src/sdk/endpoints.ts index 1951a884..ff61da75 100644 --- a/src/sdk/endpoints.ts +++ b/src/sdk/endpoints.ts @@ -3,11 +3,13 @@ * @generated-id: f159be23d878 */ -import { endpointsList } from "../funcs/endpointsList.js"; -import { endpointsListZdrEndpoints } from "../funcs/endpointsListZdrEndpoints.js"; -import { ClientSDK, RequestOptions } from "../lib/sdks.js"; -import * as operations from "../models/operations/index.js"; -import { unwrapAsync } from "../types/fp.js"; +import type { RequestOptions } from '../lib/sdks.js'; +import type * as operations from '../models/operations/index.js'; + +import { endpointsList } from '../funcs/endpointsList.js'; +import { endpointsListZdrEndpoints } from '../funcs/endpointsListZdrEndpoints.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { unwrapAsync } from '../types/fp.js'; export class Endpoints extends ClientSDK { /** @@ -17,22 +19,13 @@ export class Endpoints extends ClientSDK { request: operations.ListEndpointsRequest, options?: RequestOptions, ): Promise { - return unwrapAsync(endpointsList( - this, - request, - options, - )); + return unwrapAsync(endpointsList(this, request, options)); } /** * Preview the impact of ZDR on the available endpoints */ - async listZdrEndpoints( - options?: RequestOptions, - ): Promise { - return unwrapAsync(endpointsListZdrEndpoints( - this, - options, - )); + async listZdrEndpoints(options?: RequestOptions): Promise { + return unwrapAsync(endpointsListZdrEndpoints(this, options)); } } diff --git a/src/sdk/generations.ts b/src/sdk/generations.ts index ebd85c57..0f84db06 100644 --- a/src/sdk/generations.ts +++ b/src/sdk/generations.ts @@ -3,10 +3,12 @@ * @generated-id: e28b205da063 */ -import { generationsGetGeneration } from "../funcs/generationsGetGeneration.js"; -import { ClientSDK, RequestOptions } from "../lib/sdks.js"; -import * as operations from "../models/operations/index.js"; -import { unwrapAsync } from "../types/fp.js"; +import type { RequestOptions } from '../lib/sdks.js'; +import type * as operations from '../models/operations/index.js'; + +import { generationsGetGeneration } from '../funcs/generationsGetGeneration.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { unwrapAsync } from '../types/fp.js'; export class Generations extends ClientSDK { /** @@ -16,10 +18,6 @@ export class Generations extends ClientSDK { request: operations.GetGenerationRequest, options?: RequestOptions, ): Promise { - return unwrapAsync(generationsGetGeneration( - this, - request, - options, - )); + return unwrapAsync(generationsGetGeneration(this, request, options)); } } diff --git a/src/sdk/index.ts b/src/sdk/index.ts index 5c82fe38..9f4bfe26 100644 --- a/src/sdk/index.ts +++ b/src/sdk/index.ts @@ -3,4 +3,4 @@ * @generated-id: a857902a703f */ -export * from "./sdk.js"; +export * from './sdk.js'; diff --git a/src/sdk/models.ts b/src/sdk/models.ts index bb38b404..43961aeb 100644 --- a/src/sdk/models.ts +++ b/src/sdk/models.ts @@ -3,25 +3,22 @@ * @generated-id: 8c761ab180fd */ -import { modelsCount } from "../funcs/modelsCount.js"; -import { modelsList } from "../funcs/modelsList.js"; -import { modelsListForUser } from "../funcs/modelsListForUser.js"; -import { ClientSDK, RequestOptions } from "../lib/sdks.js"; -import * as models from "../models/index.js"; -import * as operations from "../models/operations/index.js"; -import { unwrapAsync } from "../types/fp.js"; +import type { RequestOptions } from '../lib/sdks.js'; +import type * as models from '../models/index.js'; +import type * as operations from '../models/operations/index.js'; + +import { modelsCount } from '../funcs/modelsCount.js'; +import { modelsList } from '../funcs/modelsList.js'; +import { modelsListForUser } from '../funcs/modelsListForUser.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { unwrapAsync } from '../types/fp.js'; export class Models extends ClientSDK { /** * Get total count of available models */ - async count( - options?: RequestOptions, - ): Promise { - return unwrapAsync(modelsCount( - this, - options, - )); + async count(options?: RequestOptions): Promise { + return unwrapAsync(modelsCount(this, options)); } /** @@ -31,11 +28,7 @@ export class Models extends ClientSDK { request?: operations.GetModelsRequest | undefined, options?: RequestOptions, ): Promise { - return unwrapAsync(modelsList( - this, - request, - options, - )); + return unwrapAsync(modelsList(this, request, options)); } /** @@ -45,10 +38,6 @@ export class Models extends ClientSDK { security: operations.ListModelsUserSecurity, options?: RequestOptions, ): Promise { - return unwrapAsync(modelsListForUser( - this, - security, - options, - )); + return unwrapAsync(modelsListForUser(this, security, options)); } } diff --git a/src/sdk/oauth.ts b/src/sdk/oauth.ts index 12f35868..d84884c7 100644 --- a/src/sdk/oauth.ts +++ b/src/sdk/oauth.ts @@ -3,16 +3,18 @@ * @generated-id: 37b7f9b2970b */ -import { oAuthCreateAuthCode } from "../funcs/oAuthCreateAuthCode.js"; -import { oAuthExchangeAuthCodeForAPIKey } from "../funcs/oAuthExchangeAuthCodeForAPIKey.js"; -import { ClientSDK, RequestOptions } from "../lib/sdks.js"; -import * as operations from "../models/operations/index.js"; -import { unwrapAsync } from "../types/fp.js"; // #region imports -import type { CreateAuthorizationUrlRequest } from "../funcs/oAuthCreateAuthorizationUrl.js"; -import { oAuthCreateAuthorizationUrl } from "../funcs/oAuthCreateAuthorizationUrl.js"; -import type { CreateSHA256CodeChallengeResponse } from "../funcs/oAuthCreateSHA256CodeChallenge.js"; -import { oAuthCreateSHA256CodeChallenge } from "../funcs/oAuthCreateSHA256CodeChallenge.js"; +import type { CreateAuthorizationUrlRequest } from '../funcs/oAuthCreateAuthorizationUrl.js'; +import type { CreateSHA256CodeChallengeResponse } from '../funcs/oAuthCreateSHA256CodeChallenge.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type * as operations from '../models/operations/index.js'; + +import { oAuthCreateAuthCode } from '../funcs/oAuthCreateAuthCode.js'; +import { oAuthCreateAuthorizationUrl } from '../funcs/oAuthCreateAuthorizationUrl.js'; +import { oAuthCreateSHA256CodeChallenge } from '../funcs/oAuthCreateSHA256CodeChallenge.js'; +import { oAuthExchangeAuthCodeForAPIKey } from '../funcs/oAuthExchangeAuthCodeForAPIKey.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { unwrapAsync } from '../types/fp.js'; // #endregion imports export class OAuth extends ClientSDK { @@ -27,9 +29,7 @@ export class OAuth extends ClientSDK { * * @see {@link https://openrouter.ai/docs/use-cases/oauth-pkce} */ - async createAuthorizationUrl( - request: CreateAuthorizationUrlRequest, - ): Promise { + async createAuthorizationUrl(request: CreateAuthorizationUrlRequest): Promise { const result = oAuthCreateAuthorizationUrl(this, request); if (!result.ok) { @@ -52,9 +52,7 @@ export class OAuth extends ClientSDK { * @see {@link https://openrouter.ai/docs/use-cases/oauth-pkce} * @see {@link https://datatracker.ietf.org/doc/html/rfc7636} */ - async createSHA256CodeChallenge(): Promise< - CreateSHA256CodeChallengeResponse - > { + async createSHA256CodeChallenge(): Promise { return unwrapAsync(oAuthCreateSHA256CodeChallenge()); } // #endregion sdk-class-body @@ -69,11 +67,7 @@ export class OAuth extends ClientSDK { request: operations.ExchangeAuthCodeForAPIKeyRequest, options?: RequestOptions, ): Promise { - return unwrapAsync(oAuthExchangeAuthCodeForAPIKey( - this, - request, - options, - )); + return unwrapAsync(oAuthExchangeAuthCodeForAPIKey(this, request, options)); } /** @@ -86,10 +80,6 @@ export class OAuth extends ClientSDK { request: operations.CreateAuthKeysCodeRequest, options?: RequestOptions, ): Promise { - return unwrapAsync(oAuthCreateAuthCode( - this, - request, - options, - )); + return unwrapAsync(oAuthCreateAuthCode(this, request, options)); } } diff --git a/src/sdk/parameters.ts b/src/sdk/parameters.ts index f6e0e933..fd3ef2eb 100644 --- a/src/sdk/parameters.ts +++ b/src/sdk/parameters.ts @@ -3,10 +3,12 @@ * @generated-id: 6e4ef00c29b7 */ -import { parametersGetParameters } from "../funcs/parametersGetParameters.js"; -import { ClientSDK, RequestOptions } from "../lib/sdks.js"; -import * as operations from "../models/operations/index.js"; -import { unwrapAsync } from "../types/fp.js"; +import type { RequestOptions } from '../lib/sdks.js'; +import type * as operations from '../models/operations/index.js'; + +import { parametersGetParameters } from '../funcs/parametersGetParameters.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { unwrapAsync } from '../types/fp.js'; export class ParametersT extends ClientSDK { /** @@ -17,11 +19,6 @@ export class ParametersT extends ClientSDK { request: operations.GetParametersRequest, options?: RequestOptions, ): Promise { - return unwrapAsync(parametersGetParameters( - this, - security, - request, - options, - )); + return unwrapAsync(parametersGetParameters(this, security, request, options)); } } diff --git a/src/sdk/providers.ts b/src/sdk/providers.ts index dc6908e0..c8400975 100644 --- a/src/sdk/providers.ts +++ b/src/sdk/providers.ts @@ -3,21 +3,18 @@ * @generated-id: fb8faa7013d0 */ -import { providersList } from "../funcs/providersList.js"; -import { ClientSDK, RequestOptions } from "../lib/sdks.js"; -import * as operations from "../models/operations/index.js"; -import { unwrapAsync } from "../types/fp.js"; +import type { RequestOptions } from '../lib/sdks.js'; +import type * as operations from '../models/operations/index.js'; + +import { providersList } from '../funcs/providersList.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { unwrapAsync } from '../types/fp.js'; export class Providers extends ClientSDK { /** * List all providers */ - async list( - options?: RequestOptions, - ): Promise { - return unwrapAsync(providersList( - this, - options, - )); + async list(options?: RequestOptions): Promise { + return unwrapAsync(providersList(this, options)); } } diff --git a/src/sdk/responses.ts b/src/sdk/responses.ts index fc8f29b9..e23a3162 100644 --- a/src/sdk/responses.ts +++ b/src/sdk/responses.ts @@ -3,12 +3,14 @@ * @generated-id: fc4b535757c5 */ -import { betaResponsesSend } from "../funcs/betaResponsesSend.js"; -import { EventStream } from "../lib/event-streams.js"; -import { ClientSDK, RequestOptions } from "../lib/sdks.js"; -import * as models from "../models/index.js"; -import * as operations from "../models/operations/index.js"; -import { unwrapAsync } from "../types/fp.js"; +import type { EventStream } from '../lib/event-streams.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type * as models from '../models/index.js'; +import type * as operations from '../models/operations/index.js'; + +import { betaResponsesSend } from '../funcs/betaResponsesSend.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { unwrapAsync } from '../types/fp.js'; export class Responses extends ClientSDK { /** @@ -18,11 +20,15 @@ export class Responses extends ClientSDK { * Creates a streaming or non-streaming response using OpenResponses API format */ async send( - request: models.OpenResponsesRequest & { stream?: false | undefined }, + request: models.OpenResponsesRequest & { + stream?: false | undefined; + }, options?: RequestOptions, ): Promise; async send( - request: models.OpenResponsesRequest & { stream: true }, + request: models.OpenResponsesRequest & { + stream: true; + }, options?: RequestOptions, ): Promise>; async send( @@ -33,10 +39,6 @@ export class Responses extends ClientSDK { request: models.OpenResponsesRequest, options?: RequestOptions, ): Promise { - return unwrapAsync(betaResponsesSend( - this, - request, - options, - )); + return unwrapAsync(betaResponsesSend(this, request, options)); } } diff --git a/src/sdk/sdk.ts b/src/sdk/sdk.ts index fa0219a8..90d6f87f 100644 --- a/src/sdk/sdk.ts +++ b/src/sdk/sdk.ts @@ -3,28 +3,27 @@ * @generated-id: 784571af2f69 */ -import { ClientSDK } from "../lib/sdks.js"; -import { Analytics } from "./analytics.js"; -import { APIKeys } from "./apikeys.js"; -import { Beta } from "./beta.js"; -import { Chat } from "./chat.js"; -import { Completions } from "./completions.js"; -import { Credits } from "./credits.js"; -import { Embeddings } from "./embeddings.js"; -import { Endpoints } from "./endpoints.js"; -import { Generations } from "./generations.js"; -import { Models } from "./models.js"; -import { OAuth } from "./oauth.js"; -import { ParametersT } from "./parameters.js"; -import { Providers } from "./providers.js"; -// #region imports -import { - callModel as callModelFunc, - type CallModelInput, -} from "../funcs/call-model.js"; -import type { ModelResult } from "../lib/model-result.js"; -import type { RequestOptions } from "../lib/sdks.js"; -import { type MaxToolRounds, ToolType } from "../lib/tool-types.js"; +import type { CallModelInput } from '../funcs/call-model.js'; +import type { ModelResult } from '../lib/model-result.js'; +import type { RequestOptions } from '../lib/sdks.js'; +import type { MaxToolRounds } from '../lib/tool-types.js'; + +import { callModel as callModelFunc } from '../funcs/call-model.js'; +import { ClientSDK } from '../lib/sdks.js'; +import { ToolType } from '../lib/tool-types.js'; +import { Analytics } from './analytics.js'; +import { APIKeys } from './apikeys.js'; +import { Beta } from './beta.js'; +import { Chat } from './chat.js'; +import { Completions } from './completions.js'; +import { Credits } from './credits.js'; +import { Embeddings } from './embeddings.js'; +import { Endpoints } from './endpoints.js'; +import { Generations } from './generations.js'; +import { Models } from './models.js'; +import { OAuth } from './oauth.js'; +import { ParametersT } from './parameters.js'; +import { Providers } from './providers.js'; export { ToolType }; export type { MaxToolRounds }; @@ -97,10 +96,7 @@ export class OpenRouter extends ClientSDK { } // #region sdk-class-body - callModel( - request: CallModelInput, - options?: RequestOptions, - ): ModelResult { + callModel(request: CallModelInput, options?: RequestOptions): ModelResult { return callModelFunc(this, request, options); } // #endregion sdk-class-body diff --git a/src/types/async.ts b/src/types/async.ts index 634e549a..1f56b8ce 100644 --- a/src/types/async.ts +++ b/src/types/async.ts @@ -5,56 +5,59 @@ export type APICall = | { - status: "complete"; + status: 'complete'; request: Request; response: Response; } | { - status: "request-error"; + status: 'request-error'; request: Request; response?: undefined; } | { - status: "invalid"; + status: 'invalid'; request?: undefined; response?: undefined; }; export class APIPromise implements Promise { - readonly #promise: Promise<[T, APICall]>; + readonly #promise: Promise< + [ + T, + APICall, + ] + >; readonly #unwrapped: Promise; - readonly [Symbol.toStringTag] = "APIPromise"; + readonly [Symbol.toStringTag] = 'APIPromise'; - constructor(p: [T, APICall] | Promise<[T, APICall]>) { + constructor( + p: + | [ + T, + APICall, + ] + | Promise< + [ + T, + APICall, + ] + >, + ) { this.#promise = p instanceof Promise ? p : Promise.resolve(p); this.#unwrapped = - p instanceof Promise - ? this.#promise.then(([value]) => value) - : Promise.resolve(p[0]); + p instanceof Promise ? this.#promise.then(([value]) => value) : Promise.resolve(p[0]); } then( - onfulfilled?: - | ((value: T) => TResult1 | PromiseLike) - | null - | undefined, - onrejected?: - | ((reason: any) => TResult2 | PromiseLike) - | null - | undefined, + onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null | undefined, + onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined, ): Promise { - return this.#promise.then( - onfulfilled ? ([value]) => onfulfilled(value) : void 0, - onrejected, - ); + return this.#promise.then(onfulfilled ? ([value]) => onfulfilled(value) : void 0, onrejected); } catch( - onrejected?: - | ((reason: any) => TResult | PromiseLike) - | null - | undefined, + onrejected?: ((reason: any) => TResult | PromiseLike) | null | undefined, ): Promise { return this.#unwrapped.catch(onrejected); } @@ -63,7 +66,12 @@ export class APIPromise implements Promise { return this.#unwrapped.finally(onfinally); } - $inspect(): Promise<[T, APICall]> { + $inspect(): Promise< + [ + T, + APICall, + ] + > { return this.#promise; } } diff --git a/src/types/blobs.ts b/src/types/blobs.ts index 6986071c..29af1e31 100644 --- a/src/types/blobs.ts +++ b/src/types/blobs.ts @@ -3,32 +3,29 @@ * @generated-id: f8ab9b326c86 */ -import * as z from "zod/v4"; +import * as z from 'zod/v4'; -export const blobLikeSchema: z.ZodType = z.custom( - isBlobLike, - { - message: "expected a Blob, File or Blob-like object", - abort: true, - }, -); +export const blobLikeSchema: z.ZodType = z.custom(isBlobLike, { + message: 'expected a Blob, File or Blob-like object', + abort: true, +}); export function isBlobLike(val: unknown): val is Blob { if (val instanceof Blob) { return true; } - if (typeof val !== "object" || val == null || !(Symbol.toStringTag in val)) { + if (typeof val !== 'object' || val == null || !(Symbol.toStringTag in val)) { return false; } const name = val[Symbol.toStringTag]; - if (typeof name !== "string") { + if (typeof name !== 'string') { return false; } - if (name !== "Blob" && name !== "File") { + if (name !== 'Blob' && name !== 'File') { return false; } - return "stream" in val && typeof val.stream === "function"; + return 'stream' in val && typeof val.stream === 'function'; } diff --git a/src/types/constdatetime.ts b/src/types/constdatetime.ts index 6e667b0e..6e3c69ea 100644 --- a/src/types/constdatetime.ts +++ b/src/types/constdatetime.ts @@ -3,14 +3,10 @@ * @generated-id: 0f7b6f513917 */ -import * as z from "zod/v4"; +import * as z from 'zod/v4'; -export function constDateTime( - val: string, -): z.ZodType { +export function constDateTime(val: string): z.ZodType { return z.custom((v) => { - return ( - typeof v === "string" && new Date(v).getTime() === new Date(val).getTime() - ); + return typeof v === 'string' && new Date(v).getTime() === new Date(val).getTime(); }, `Value must be equivalent to ${val}`); } diff --git a/src/types/discriminatedUnion.ts b/src/types/discriminatedUnion.ts index 3527dc38..8008fd79 100644 --- a/src/types/discriminatedUnion.ts +++ b/src/types/discriminatedUnion.ts @@ -3,24 +3,22 @@ * @generated-id: 44cf2d277540 */ -import * as z from "zod/v4"; -import { startCountingUnrecognized } from "./unrecognized.js"; +import * as z from 'zod/v4'; +import { startCountingUnrecognized } from './unrecognized.js'; -const UNKNOWN = Symbol("UNKNOWN"); +const UNKNOWN = Symbol('UNKNOWN'); -export type Unknown = - & { - [K in Discriminator]: UnknownValue; - } - & { - raw: unknown; - isUnknown: true; - }; +export type Unknown = { + [K in Discriminator]: UnknownValue; +} & { + raw: unknown; + isUnknown: true; +}; export function isUnknown( value: unknown, ): value is Unknown { - return typeof value === "object" && value !== null && UNKNOWN in value; + return typeof value === 'object' && value !== null && UNKNOWN in value; } /** @@ -38,7 +36,7 @@ export function isUnknown( export function discriminatedUnion< InputDiscriminator extends string, TOptions extends Readonly>, - UnknownValue extends string = "UNKNOWN", + UnknownValue extends string = 'UNKNOWN', OutputDiscriminator extends string = InputDiscriminator, >( inputPropertyName: InputDiscriminator, @@ -48,11 +46,10 @@ export function discriminatedUnion< outputPropertyName?: OutputDiscriminator; } = {}, ): z.ZodType< - | z.output - | Unknown, + z.output | Unknown, unknown > { - const { unknownValue = "UNKNOWN" as UnknownValue, outputPropertyName } = opts; + const { unknownValue = 'UNKNOWN' as UnknownValue, outputPropertyName } = opts; return z.unknown().transform((input) => { const fallback = Object.defineProperties( { @@ -60,14 +57,20 @@ export function discriminatedUnion< [outputPropertyName ?? inputPropertyName]: unknownValue, isUnknown: true as const, }, - { [UNKNOWN]: { value: true, enumerable: false, configurable: false } }, + { + [UNKNOWN]: { + value: true, + enumerable: false, + configurable: false, + }, + }, ); - const isObject = typeof input === "object" && input !== null; + const isObject = typeof input === 'object' && input !== null; if (!isObject) return fallback; const discriminator = input[inputPropertyName as keyof typeof input]; - if (typeof discriminator !== "string") return fallback; + if (typeof discriminator !== 'string') return fallback; if (!(discriminator in options)) return fallback; const schema = options[discriminator]; diff --git a/src/types/enums.ts b/src/types/enums.ts index f13dbd9e..75cefa40 100644 --- a/src/types/enums.ts +++ b/src/types/enums.ts @@ -3,11 +3,12 @@ * @generated-id: 4d03ddfe5100 */ -import * as z from "zod/v4"; -import { Unrecognized, unrecognized } from "./unrecognized.js"; +import type { Unrecognized } from './unrecognized.js'; -export type ClosedEnum>> = - T[keyof T]; +import * as z from 'zod/v4'; +import { unrecognized } from './unrecognized.js'; + +export type ClosedEnum>> = T[keyof T]; export type OpenEnum>> = | T[keyof T] | Unrecognized; @@ -17,8 +18,8 @@ export function inboundSchema>( ): z.ZodType, unknown> { const options = Object.values(enumObj); return z.union([ - ...options.map(x => z.literal(x)), - z.string().transform(x => unrecognized(x)), + ...options.map((x) => z.literal(x)), + z.string().transform((x) => unrecognized(x)), ] as any); } @@ -26,10 +27,10 @@ export function inboundSchemaInt>( enumObj: T, ): z.ZodType, unknown> { // For numeric enums, Object.values returns both numbers and string keys - const options = Object.values(enumObj).filter(v => typeof v === "number"); + const options = Object.values(enumObj).filter((v) => typeof v === 'number'); return z.union([ - ...options.map(x => z.literal(x)), - z.int().transform(x => unrecognized(x)), + ...options.map((x) => z.literal(x)), + z.int().transform((x) => unrecognized(x)), ] as any); } diff --git a/src/types/fp.ts b/src/types/fp.ts index 7d4f9f13..cc5ac16d 100644 --- a/src/types/fp.ts +++ b/src/types/fp.ts @@ -13,15 +13,29 @@ * inspect and more verbose work with due to try-catch blocks. */ export type Result = - | { ok: true; value: T; error?: never } - | { ok: false; value?: never; error: E }; + | { + ok: true; + value: T; + error?: never; + } + | { + ok: false; + value?: never; + error: E; + }; export function OK(value: V): Result { - return { ok: true, value }; + return { + ok: true, + value, + }; } export function ERR(error: E): Result { - return { ok: false, error }; + return { + ok: false, + error, + }; } /** @@ -39,9 +53,7 @@ export function unwrap(r: Result): T { * unwrapAsync is a convenience function for resolving a value from a Promise * of a result or rejecting if an error occurred. */ -export async function unwrapAsync( - pr: Promise>, -): Promise { +export async function unwrapAsync(pr: Promise>): Promise { const r = await pr; if (!r.ok) { throw r.error; diff --git a/src/types/index.ts b/src/types/index.ts index dfb23ead..634739e4 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -3,10 +3,11 @@ * @generated-id: cd7a0a5ed005 */ -export { blobLikeSchema, isBlobLike } from "./blobs.js"; -export type { ClosedEnum, OpenEnum } from "./enums.js"; -export type { Result } from "./fp.js"; -export type { PageIterator, Paginator } from "./operations.js"; -export { createPageIterator } from "./operations.js"; -export { RFCDate } from "./rfcdate.js"; -export * from "./unrecognized.js"; +export type { ClosedEnum, OpenEnum } from './enums.js'; +export type { Result } from './fp.js'; +export type { PageIterator, Paginator } from './operations.js'; + +export { blobLikeSchema, isBlobLike } from './blobs.js'; +export { createPageIterator } from './operations.js'; +export { RFCDate } from './rfcdate.js'; +export * from './unrecognized.js'; diff --git a/src/types/operations.ts b/src/types/operations.ts index a1c2b38e..6e9b07b6 100644 --- a/src/types/operations.ts +++ b/src/types/operations.ts @@ -3,18 +3,24 @@ * @generated-id: 314da01dca47 */ -import { Result } from "./fp.js"; +import type { Result } from './fp.js'; -export type Paginator = () => Promise }> | null; +export type Paginator = () => Promise< + V & { + next: Paginator; + } +> | null; export type PageIterator = V & { next: Paginator; [Symbol.asyncIterator]: () => AsyncIterableIterator; - "~next"?: PageState | undefined; + '~next'?: PageState | undefined; }; export function createPageIterator( - page: V & { next: Paginator }, + page: V & { + next: Paginator; + }, halt: (v: V) => boolean, ): { [Symbol.asyncIterator]: () => AsyncIterableIterator; @@ -42,9 +48,7 @@ export function createPageIterator( * terminates. It is useful in paginated SDK functions that have early return * paths when things go wrong. */ -export function haltIterator( - v: V, -): PageIterator { +export function haltIterator(v: V): PageIterator { return { ...v, next: () => null, @@ -70,7 +74,7 @@ export async function unwrapResultIterator( return { ...resultIter.value, next: unwrapPaginator(resultIter.next), - "~next": resultIter["~next"], + '~next': resultIter['~next'], [Symbol.asyncIterator]: async function* paginator() { for await (const page of resultIter) { if (!page.ok) { @@ -82,9 +86,7 @@ export async function unwrapResultIterator( }; } -function unwrapPaginator( - paginator: Paginator>, -): Paginator { +function unwrapPaginator(paginator: Paginator>): Paginator { return () => { const nextResult = paginator(); if (nextResult == null) { @@ -103,4 +105,4 @@ function unwrapPaginator( }; } -export const URL_OVERRIDE = Symbol("URL_OVERRIDE"); +export const URL_OVERRIDE = Symbol('URL_OVERRIDE'); diff --git a/src/types/rfcdate.ts b/src/types/rfcdate.ts index 05a12a9e..d1d4d1f4 100644 --- a/src/types/rfcdate.ts +++ b/src/types/rfcdate.ts @@ -26,18 +26,16 @@ export class RFCDate { * new RFCDate(new Date()) */ constructor(date: Date | string) { - if (typeof date === "string" && !dateRE.test(date)) { - throw new RangeError( - "RFCDate: date strings must be in the format YYYY-MM-DD: " + date, - ); + if (typeof date === 'string' && !dateRE.test(date)) { + throw new RangeError('RFCDate: date strings must be in the format YYYY-MM-DD: ' + date); } const value = new Date(date); if (isNaN(+value)) { - throw new RangeError("RFCDate: invalid date provided: " + date); + throw new RangeError('RFCDate: invalid date provided: ' + date); } - this.serialized = value.toISOString().slice(0, "YYYY-MM-DD".length); + this.serialized = value.toISOString().slice(0, 'YYYY-MM-DD'.length); if (!dateRE.test(this.serialized)) { throw new TypeError( `RFCDate: failed to build valid date with given value: ${date} serialized to ${this.serialized}`, diff --git a/src/types/streams.ts b/src/types/streams.ts index 88c11154..48202fc4 100644 --- a/src/types/streams.ts +++ b/src/types/streams.ts @@ -3,10 +3,8 @@ * @generated-id: f99be9c4bf14 */ -export function isReadableStream( - val: unknown, -): val is ReadableStream { - if (typeof val !== "object" || val === null) { +export function isReadableStream(val: unknown): val is ReadableStream { + if (typeof val !== 'object' || val === null) { return false; } @@ -15,8 +13,8 @@ export function isReadableStream( // ReadableStream has methods like getReader, cancel, and tee return ( - typeof stream.getReader === "function" && - typeof stream.cancel === "function" && - typeof stream.tee === "function" + typeof stream.getReader === 'function' && + typeof stream.cancel === 'function' && + typeof stream.tee === 'function' ); } diff --git a/src/types/unrecognized.ts b/src/types/unrecognized.ts index 4ccb9fff..b929cb83 100644 --- a/src/types/unrecognized.ts +++ b/src/types/unrecognized.ts @@ -4,7 +4,9 @@ */ declare const __brand: unique symbol; -export type Unrecognized = T & { [__brand]: "unrecognized" }; +export type Unrecognized = T & { + [__brand]: 'unrecognized'; +}; function unrecognized(value: T): Unrecognized { globalCount++; diff --git a/tests/e2e/call-model-tools.test.ts b/tests/e2e/call-model-tools.test.ts index 0fe1dcc2..4031fb91 100644 --- a/tests/e2e/call-model-tools.test.ts +++ b/tests/e2e/call-model-tools.test.ts @@ -622,21 +622,19 @@ describe('Enhanced Tool Support for callModel', () => { }, }; - const response = await client.callModel( - { - model: 'openai/gpt-4o', - input: [ - { - role: 'user', - content: 'What is 25 * 4?', - }, - ], - tools: [ - calculatorTool, - ], - maxToolRounds: 3, - }, - ); + const response = await client.callModel({ + model: 'openai/gpt-4o', + input: [ + { + role: 'user', + content: 'What is 25 * 4?', + }, + ], + tools: [ + calculatorTool, + ], + maxToolRounds: 3, + }); const fullResponse = await response.getResponse(); const finalMessage = toChatMessage(fullResponse); diff --git a/tests/e2e/call-model.test.ts b/tests/e2e/call-model.test.ts index aa726581..323916ad 100644 --- a/tests/e2e/call-model.test.ts +++ b/tests/e2e/call-model.test.ts @@ -1,15 +1,15 @@ import type { ChatStreamEvent, EnhancedResponseStreamEvent } from '../../src/lib/tool-types.js'; import type { ClaudeMessageParam } from '../../src/models/claude-message.js'; -import type { ResponsesOutputMessage } from '../../src/models/responsesoutputmessage.js'; import type { OpenResponsesFunctionCallOutput } from '../../src/models/openresponsesfunctioncalloutput.js'; +import type { OpenResponsesNonStreamingResponse } from '../../src/models/openresponsesnonstreamingresponse.js'; +import type { OpenResponsesStreamEvent } from '../../src/models/openresponsesstreamevent.js'; +import type { ResponsesOutputMessage } from '../../src/models/responsesoutputmessage.js'; import { beforeAll, describe, expect, it } from 'vitest'; import { z } from 'zod/v4'; -import { OpenRouter, ToolType } from '../../src/sdk/sdk.js'; -import { fromChatMessages, toChatMessage } from '../../src/lib/chat-compat.js'; import { fromClaudeMessages } from '../../src/lib/anthropic-compat.js'; -import { OpenResponsesNonStreamingResponse } from '../../src/models/openresponsesnonstreamingresponse.js'; -import { OpenResponsesStreamEvent } from '../../src/models/openresponsesstreamevent.js'; +import { fromChatMessages, toChatMessage } from '../../src/lib/chat-compat.js'; +import { OpenRouter, ToolType } from '../../src/sdk/sdk.js'; describe('callModel E2E Tests', () => { let client: OpenRouter; @@ -233,7 +233,7 @@ describe('callModel E2E Tests', () => { }, { role: 'assistant', - content: "Nice to meet you, Alice! How can I help you today?", + content: 'Nice to meet you, Alice! How can I help you today?', }, { role: 'user', @@ -281,6 +281,86 @@ describe('callModel E2E Tests', () => { }); }); + describe('getClaudeMessage - Claude output format', () => { + it('should return ClaudeMessage with correct structure', async () => { + const response = client.callModel({ + model: 'meta-llama/llama-3.2-1b-instruct', + input: "Say 'hello' and nothing else.", + }); + + const claudeMessage = await response.getClaudeMessage(); + + expect(claudeMessage.type).toBe('message'); + expect(claudeMessage.role).toBe('assistant'); + expect(claudeMessage.content).toBeInstanceOf(Array); + expect(claudeMessage.content.length).toBeGreaterThan(0); + expect(claudeMessage.content[0]?.type).toBe('text'); + expect(claudeMessage.stop_reason).toBeDefined(); + expect(claudeMessage.usage).toBeDefined(); + expect(claudeMessage.usage.input_tokens).toBeGreaterThan(0); + expect(claudeMessage.usage.output_tokens).toBeGreaterThan(0); + }, 30000); + + it('should include text content in ClaudeMessage', async () => { + const response = client.callModel({ + model: 'meta-llama/llama-3.2-1b-instruct', + input: "Say the word 'banana' and nothing else.", + }); + + const claudeMessage = await response.getClaudeMessage(); + const textBlock = claudeMessage.content.find((b) => b.type === 'text'); + + expect(textBlock).toBeDefined(); + if (textBlock && textBlock.type === 'text') { + expect(textBlock.text.toLowerCase()).toContain('banana'); + } + }, 30000); + + it('should include tool_use blocks when tools are called', async () => { + const response = client.callModel({ + model: 'openai/gpt-4o-mini', + input: "What's the weather in Paris?", + tools: [ + { + type: ToolType.Function, + function: { + name: 'get_weather', + description: 'Get weather for a location', + inputSchema: z.object({ + location: z.string(), + }), + }, + }, + ], + maxToolRounds: 0, // Don't execute tools, just get the tool call + }); + + const claudeMessage = await response.getClaudeMessage(); + + const toolUseBlock = claudeMessage.content.find((b) => b.type === 'tool_use'); + expect(toolUseBlock).toBeDefined(); + expect(claudeMessage.stop_reason).toBe('tool_use'); + + if (toolUseBlock && toolUseBlock.type === 'tool_use') { + expect(toolUseBlock.name).toBe('get_weather'); + expect(toolUseBlock.id).toBeDefined(); + expect(toolUseBlock.input).toBeDefined(); + } + }, 30000); + + it('should have correct model field in ClaudeMessage', async () => { + const response = client.callModel({ + model: 'meta-llama/llama-3.2-1b-instruct', + input: "Say 'test'", + }); + + const claudeMessage = await response.getClaudeMessage(); + + expect(claudeMessage.model).toBeDefined(); + expect(typeof claudeMessage.model).toBe('string'); + }, 30000); + }); + describe('response.text - Text extraction', () => { it('should successfully get text from a response', async () => { const response = client.callModel({ @@ -512,7 +592,14 @@ describe('callModel E2E Tests', () => { // Extract text from content array const getTextFromContent = (msg: ResponsesOutputMessage) => { return msg.content - .filter((c): c is { type: 'output_text'; text: string } => 'type' in c && c.type === 'output_text') + .filter( + ( + c, + ): c is { + type: 'output_text'; + text: string; + } => 'type' in c && c.type === 'output_text', + ) .map((c) => c.text) .join(''); }; @@ -555,12 +642,19 @@ describe('callModel E2E Tests', () => { expect(item).toHaveProperty('type'); expect(typeof item.type).toBe('string'); // Content items should be output_text or refusal - expect(['output_text', 'refusal']).toContain(item.type); + expect([ + 'output_text', + 'refusal', + ]).toContain(item.type); } // Validate optional status field if (outputMessage.status !== undefined) { - expect(['completed', 'incomplete', 'in_progress']).toContain(outputMessage.status); + expect([ + 'completed', + 'incomplete', + 'in_progress', + ]).toContain(outputMessage.status); } } } @@ -685,7 +779,10 @@ describe('callModel E2E Tests', () => { for await (const message of response.getNewMessagesStream()) { // type must be a string and one of the valid values expect(typeof message.type).toBe('string'); - expect(['message', 'function_call_output']).toContain(message.type); + expect([ + 'message', + 'function_call_output', + ]).toContain(message.type); if (message.type === 'message') { const outputMessage = message as ResponsesOutputMessage; @@ -853,7 +950,7 @@ describe('callModel E2E Tests', () => { // Verify delta events have the expected structure const firstDelta = textDeltaEvents[0]; - if(firstDelta.type === 'response.output_text.delta') { + if (firstDelta.type === 'response.output_text.delta') { expect(firstDelta.delta).toBeDefined(); expect(typeof firstDelta.delta).toBe('string'); } else { @@ -914,8 +1011,20 @@ describe('callModel E2E Tests', () => { case 'content.delta': hasContentDelta = true; // Must have delta property - expect((event as { delta: string }).delta).toBeDefined(); - expect(typeof (event as { delta: string }).delta).toBe('string'); + expect( + ( + event as { + delta: string; + } + ).delta, + ).toBeDefined(); + expect( + typeof ( + event as { + delta: string; + } + ).delta, + ).toBe('string'); // Delta can be empty string but must be string break; @@ -923,25 +1032,61 @@ describe('callModel E2E Tests', () => { _hasMessageComplete = true; // Must have response property expect(event).toHaveProperty('response'); - expect((event as { response: OpenResponsesNonStreamingResponse }).response).toBeDefined(); + expect( + ( + event as { + response: OpenResponsesNonStreamingResponse; + } + ).response, + ).toBeDefined(); // Response should be an object (the full response) - expect(typeof (event as { response: OpenResponsesNonStreamingResponse }).response).toBe('object'); - expect((event as { response: OpenResponsesNonStreamingResponse }).response).not.toBeNull(); + expect( + typeof ( + event as { + response: OpenResponsesNonStreamingResponse; + } + ).response, + ).toBe('object'); + expect( + ( + event as { + response: OpenResponsesNonStreamingResponse; + } + ).response, + ).not.toBeNull(); break; case 'tool.preliminary_result': // Must have toolCallId and result expect(event).toHaveProperty('toolCallId'); expect(event).toHaveProperty('result'); - expect(typeof (event as { toolCallId: string }).toolCallId).toBe('string'); - expect((event as { toolCallId: string }).toolCallId.length).toBeGreaterThan(0); + expect( + typeof ( + event as { + toolCallId: string; + } + ).toolCallId, + ).toBe('string'); + expect( + ( + event as { + toolCallId: string; + } + ).toolCallId.length, + ).toBeGreaterThan(0); // result can be any type break; default: // Pass-through events must have event property expect(event).toHaveProperty('event'); - expect((event as { event: OpenResponsesStreamEvent }).event).toBeDefined(); + expect( + ( + event as { + event: OpenResponsesStreamEvent; + } + ).event, + ).toBeDefined(); break; } } @@ -976,14 +1121,29 @@ describe('callModel E2E Tests', () => { expect(event.type).toBe('content.delta'); // delta must be a string - expect(typeof (event as { delta: string }).delta).toBe('string'); + expect( + typeof ( + event as { + delta: string; + } + ).delta, + ).toBe('string'); } } expect(contentDeltas.length).toBeGreaterThan(0); // Concatenated deltas should form readable text - const fullText = contentDeltas.map((e) => (e as { delta: string }).delta).join(''); + const fullText = contentDeltas + .map( + (e) => + ( + e as { + delta: string; + } + ).delta, + ) + .join(''); expect(fullText.length).toBeGreaterThan(0); }, 15000); @@ -1047,11 +1207,29 @@ describe('callModel E2E Tests', () => { expect(event).toHaveProperty('result'); // toolCallId must be non-empty string - expect(typeof (event as { toolCallId: string }).toolCallId).toBe('string'); - expect((event as { toolCallId: string }).toolCallId.length).toBeGreaterThan(0); + expect( + typeof ( + event as { + toolCallId: string; + } + ).toolCallId, + ).toBe('string'); + expect( + ( + event as { + toolCallId: string; + } + ).toolCallId.length, + ).toBeGreaterThan(0); // result is defined - expect((event as { result: unknown }).result).toBeDefined(); + expect( + ( + event as { + result: unknown; + } + ).result, + ).toBeDefined(); } } @@ -1152,7 +1330,14 @@ describe('callModel E2E Tests', () => { const lastMessage = messages[messages.length - 1] as ResponsesOutputMessage; // Extract text from ResponsesOutputMessage content array const textFromMessage = lastMessage.content - .filter((c): c is { type: 'output_text'; text: string } => 'type' in c && c.type === 'output_text') + .filter( + ( + c, + ): c is { + type: 'output_text'; + text: string; + } => 'type' in c && c.type === 'output_text', + ) .map((c) => c.text) .join(''); @@ -1277,7 +1462,13 @@ describe('callModel E2E Tests', () => { // Verify output items have correct shape for (const item of fullResponse.output) { expect(item).toHaveProperty('type'); - expect(typeof (item as { type: string }).type).toBe('string'); + expect( + typeof ( + item as { + type: string; + } + ).type, + ).toBe('string'); } // Verify temperature and topP are present (can be null) diff --git a/tests/e2e/embeddings.test.ts b/tests/e2e/embeddings.test.ts index 8fc8a103..62f5b143 100644 --- a/tests/e2e/embeddings.test.ts +++ b/tests/e2e/embeddings.test.ts @@ -47,7 +47,6 @@ describe('Embeddings E2E Tests', () => { if (response.usage) { expect(response.usage.totalTokens).toBeGreaterThan(0); } - }); it('should generate embeddings for multiple text inputs', async () => { @@ -81,7 +80,6 @@ describe('Embeddings E2E Tests', () => { expect(embedding?.index).toBe(index); }); - }); it('should generate consistent embedding dimensions', async () => { @@ -146,7 +144,6 @@ describe('Embeddings E2E Tests', () => { expect(typeof response.usage.totalTokens).toBe('number'); expect(response.usage.totalTokens).toBeGreaterThan(0); } - }); }); }); diff --git a/tests/e2e/responses.test.ts b/tests/e2e/responses.test.ts index 79881c0b..9ea00f4b 100644 --- a/tests/e2e/responses.test.ts +++ b/tests/e2e/responses.test.ts @@ -1,8 +1,8 @@ import type { OpenResponsesStreamEvent } from '../../src/models/openresponsesstreamevent.js'; +import type { ResponsesOutputMessage } from '../../src/models/responsesoutputmessage.js'; import { beforeAll, describe, expect, it } from 'vitest'; import { OpenRouter } from '../../src/sdk/sdk.js'; -import { ResponsesOutputMessage } from '../../src/models/responsesoutputmessage.js'; describe('Beta Responses E2E Tests', () => { let client: OpenRouter; diff --git a/tests/unit/claude-type-guards.test.ts b/tests/unit/claude-type-guards.test.ts new file mode 100644 index 00000000..0de98147 --- /dev/null +++ b/tests/unit/claude-type-guards.test.ts @@ -0,0 +1,209 @@ +import { describe, expect, it } from 'vitest'; +import { isClaudeStyleMessages } from '../../src/lib/claude-type-guards.js'; + +describe('claude-type-guards', () => { + describe('isClaudeStyleMessages', () => { + it('should return false for empty array', () => { + expect(isClaudeStyleMessages([])).toBe(false); + }); + + it('should return false for non-array input', () => { + expect(isClaudeStyleMessages('hello')).toBe(false); + expect(isClaudeStyleMessages(null)).toBe(false); + expect(isClaudeStyleMessages(undefined)).toBe(false); + expect(isClaudeStyleMessages(123)).toBe(false); + expect(isClaudeStyleMessages({})).toBe(false); + }); + + it('should return false when message has system role (OpenAI-specific)', () => { + const messages = [ + { + role: 'system', + content: 'You are helpful', + }, + ]; + expect(isClaudeStyleMessages(messages)).toBe(false); + }); + + it('should return false when message has developer role (OpenAI-specific)', () => { + const messages = [ + { + role: 'developer', + content: 'Instructions', + }, + ]; + expect(isClaudeStyleMessages(messages)).toBe(false); + }); + + it('should return false when message has tool role (OpenAI-specific)', () => { + const messages = [ + { + role: 'tool', + content: 'tool result', + tool_call_id: '123', + }, + ]; + expect(isClaudeStyleMessages(messages)).toBe(false); + }); + + it('should return true when message has tool_result block (Claude-specific)', () => { + const messages = [ + { + role: 'user', + content: [ + { + type: 'tool_result', + tool_use_id: 'tool_123', + content: 'Result text', + }, + ], + }, + ]; + expect(isClaudeStyleMessages(messages)).toBe(true); + }); + + it('should return true when message has image block with source (Claude-specific)', () => { + const messages = [ + { + role: 'user', + content: [ + { + type: 'image', + source: { + type: 'base64', + media_type: 'image/png', + data: 'base64data', + }, + }, + ], + }, + ]; + expect(isClaudeStyleMessages(messages)).toBe(true); + }); + + it('should return true when message has tool_use block with id (Claude-specific)', () => { + const messages = [ + { + role: 'assistant', + content: [ + { + type: 'tool_use', + id: 'tool_123', + name: 'get_weather', + input: { + location: 'NYC', + }, + }, + ], + }, + ]; + expect(isClaudeStyleMessages(messages)).toBe(true); + }); + + it('should return false for plain OpenAI chat messages without Claude features', () => { + const messages = [ + { + role: 'user', + content: 'Hello', + }, + { + role: 'assistant', + content: 'Hi there!', + }, + ]; + expect(isClaudeStyleMessages(messages)).toBe(false); + }); + + it('should return false for messages with text blocks only (ambiguous)', () => { + const messages = [ + { + role: 'user', + content: [ + { + type: 'text', + text: 'Hello', + }, + ], + }, + ]; + expect(isClaudeStyleMessages(messages)).toBe(false); + }); + + it('should return false for OpenAI image_url format', () => { + const messages = [ + { + role: 'user', + content: [ + { + type: 'text', + text: 'What is in this image?', + }, + { + type: 'image_url', + image_url: { + url: 'https://example.com/image.png', + }, + }, + ], + }, + ]; + expect(isClaudeStyleMessages(messages)).toBe(false); + }); + + it('should return false when message has top-level type field', () => { + const messages = [ + { + role: 'user', + content: 'Hello', + type: 'message', + }, + ]; + expect(isClaudeStyleMessages(messages)).toBe(false); + }); + + it('should handle mixed messages and detect Claude format from any message', () => { + const messages = [ + { + role: 'user', + content: 'Hello', + }, + { + role: 'assistant', + content: [ + { + type: 'text', + text: 'Let me check', + }, + { + type: 'tool_use', + id: 'tool_1', + name: 'search', + input: {}, + }, + ], + }, + ]; + expect(isClaudeStyleMessages(messages)).toBe(true); + }); + + it('should return false early when system role is found', () => { + const messages = [ + { + role: 'system', + content: 'You are helpful', + }, + { + role: 'user', + content: [ + { + type: 'tool_result', + tool_use_id: '123', + content: 'x', + }, + ], + }, + ]; + expect(isClaudeStyleMessages(messages)).toBe(false); + }); + }); +}); diff --git a/tests/unit/create-tool.test.ts b/tests/unit/create-tool.test.ts index bb26c0cd..321c521f 100644 --- a/tests/unit/create-tool.test.ts +++ b/tests/unit/create-tool.test.ts @@ -13,7 +13,9 @@ describe('tool', () => { input: z.string(), }), execute: async (params) => { - return { result: params.input }; + return { + result: params.input, + }; }, }); @@ -28,17 +30,28 @@ describe('tool', () => { name: 'weather', inputSchema: z.object({ location: z.string(), - units: z.enum(['celsius', 'fahrenheit']).optional(), + units: z + .enum([ + 'celsius', + 'fahrenheit', + ]) + .optional(), }), execute: async (params) => { // params should be typed as { location: string; units?: 'celsius' | 'fahrenheit' } const location: string = params.location; const units: 'celsius' | 'fahrenheit' | undefined = params.units; - return { location, units }; + return { + location, + units, + }; }, }); - const result = await weatherTool.function.execute({ location: 'NYC', units: 'fahrenheit' }); + const result = await weatherTool.function.execute({ + location: 'NYC', + units: 'fahrenheit', + }); expect(result.location).toBe('NYC'); expect(result.units).toBe('fahrenheit'); }); @@ -62,7 +75,9 @@ describe('tool', () => { }, }); - const result = await tempTool.function.execute({ location: 'NYC' }); + const result = await tempTool.function.execute({ + location: 'NYC', + }); expect(result.temperature).toBe(72); expect(result.description).toBe('Sunny'); }); @@ -75,12 +90,19 @@ describe('tool', () => { b: z.number(), }), execute: (params) => { - return { sum: params.a + params.b }; + return { + sum: params.a + params.b, + }; }, }); - const result = syncTool.function.execute({ a: 5, b: 3 }); - expect(result).toEqual({ sum: 8 }); + const result = syncTool.function.execute({ + a: 5, + b: 3, + }); + expect(result).toEqual({ + sum: 8, + }); }); it('should pass context to execute function', async () => { @@ -121,8 +143,12 @@ describe('tool', () => { result: z.string(), }), execute: async function* (_params) { - yield { progress: 50 }; - yield { result: 'done' }; + yield { + progress: 50, + }; + yield { + result: 'done', + }; }, }); @@ -147,22 +173,48 @@ describe('tool', () => { result: z.string(), }), execute: async function* (params) { - yield { status: 'started', progress: 0 }; - yield { status: 'processing', progress: 50 }; - yield { completed: true, result: `Processed: ${params.data}` }; + yield { + status: 'started', + progress: 0, + }; + yield { + status: 'processing', + progress: 50, + }; + yield { + completed: true, + result: `Processed: ${params.data}`, + }; }, }); const results: unknown[] = []; - const mockContext = { numberOfTurns: 1, messageHistory: [] }; - for await (const event of progressTool.function.execute({ data: 'test' }, mockContext)) { + const mockContext = { + numberOfTurns: 1, + messageHistory: [], + }; + for await (const event of progressTool.function.execute( + { + data: 'test', + }, + mockContext, + )) { results.push(event); } expect(results).toHaveLength(3); - expect(results[0]).toEqual({ status: 'started', progress: 0 }); - expect(results[1]).toEqual({ status: 'processing', progress: 50 }); - expect(results[2]).toEqual({ completed: true, result: 'Processed: test' }); + expect(results[0]).toEqual({ + status: 'started', + progress: 0, + }); + expect(results[1]).toEqual({ + status: 'processing', + progress: 50, + }); + expect(results[2]).toEqual({ + completed: true, + result: 'Processed: test', + }); }); }); diff --git a/tests/unit/tool-types.test.ts b/tests/unit/tool-types.test.ts new file mode 100644 index 00000000..6356c67b --- /dev/null +++ b/tests/unit/tool-types.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest'; +import { normalizeInputToArray } from '../../src/lib/tool-types.js'; + +describe('tool-types', () => { + describe('normalizeInputToArray', () => { + it('should return empty array for undefined input', () => { + const result = normalizeInputToArray(undefined); + expect(result).toEqual([]); + }); + + it('should wrap string input in a user message object', () => { + const result = normalizeInputToArray('Hello, world!'); + expect(result).toEqual([ + { + role: 'user', + content: 'Hello, world!', + }, + ]); + }); + + it('should return array input as-is', () => { + const input = [ + { + role: 'user' as const, + content: 'Hi', + }, + { + role: 'assistant' as const, + content: 'Hello!', + }, + ]; + const result = normalizeInputToArray(input); + expect(result).toBe(input); // Same reference + }); + + it('should handle empty string input', () => { + const result = normalizeInputToArray(''); + expect(result).toEqual([ + { + role: 'user', + content: '', + }, + ]); + }); + + it('should handle empty array input', () => { + const result = normalizeInputToArray([]); + expect(result).toEqual([]); + }); + }); +});