From f62e84b94da140ba97d5b1021d1bba34c58f57bc Mon Sep 17 00:00:00 2001 From: Tom Aylott Date: Tue, 11 Nov 2025 17:32:52 -0500 Subject: [PATCH 1/3] Add basic fetch example extracted from wrapper repo --- typescript/fetch/src/basic/example.ts | 111 ++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 typescript/fetch/src/basic/example.ts diff --git a/typescript/fetch/src/basic/example.ts b/typescript/fetch/src/basic/example.ts new file mode 100644 index 0000000..992096a --- /dev/null +++ b/typescript/fetch/src/basic/example.ts @@ -0,0 +1,111 @@ +/** + * Example: Using OpenRouter with raw fetch API + * + * This example demonstrates how to make direct HTTP requests to OpenRouter's API + * using the native fetch API without any additional libraries. + * + * To run: bun examples/basic/example-basic-fetch.ts + */ + +// Make this a module +export {}; + +// OpenRouter API endpoint +const OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions"; + +// Type definitions for the API response +interface ChatCompletionResponse { + id: string; + model: string; + choices: Array<{ + index: number; + message: { + role: string; + content: string; + }; + finish_reason: string; + }>; + usage: { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; + }; +} + +// Request payload following OpenAI-compatible chat completions format +const requestBody = { + model: "openai/gpt-4o-mini", + messages: [ + { + role: "user", + content: "Write a haiku about TypeScript", + }, + ], +}; + +console.log("=== OpenRouter Raw Fetch Example ===\n"); +console.log("Request:"); +console.log(`URL: ${OPENROUTER_API_URL}`); +console.log("Model:", requestBody.model); +console.log("Message:", requestBody.messages[0]?.content); +console.log(); + +try { + // Ensure API key is available + if (!process.env.OPENROUTER_API_KEY) { + throw new Error("OPENROUTER_API_KEY environment variable is not set"); + } + + // Make the HTTP POST request to OpenRouter + const response = await fetch(OPENROUTER_API_URL, { + method: "POST", + headers: { + // Required: Authorization header with your API key + "Authorization": `Bearer ${process.env.OPENROUTER_API_KEY}`, + // Required: Content type for JSON payload + "Content-Type": "application/json", + // Optional but recommended: Identify your app + "HTTP-Referer": "https://github.com/openrouter/examples", + "X-Title": "OpenRouter Fetch Example", + }, + body: JSON.stringify(requestBody), + }); + + // Check if the request was successful + if (!response.ok) { + const errorText = await response.text(); + throw new Error( + `HTTP error! status: ${response.status}, body: ${errorText}` + ); + } + + // Parse the JSON response + const data = await response.json() as ChatCompletionResponse; + + // Display the response + console.log("Response:"); + console.log("Status:", response.status, response.statusText); + console.log("Model used:", data.model); + console.log("\nGenerated content:"); + console.log(data.choices[0]?.message?.content); + console.log("\nUsage stats:"); + console.log("- Prompt tokens:", data.usage.prompt_tokens); + console.log("- Completion tokens:", data.usage.completion_tokens); + console.log("- Total tokens:", data.usage.total_tokens); + + // Optional: Show raw response structure + if (process.env.DEBUG) { + console.log("\nFull response object:"); + console.log(JSON.stringify(data, null, 2)); + } +} catch (error) { + console.error("Error making request to OpenRouter:"); + + if (error instanceof Error) { + console.error("Error message:", error.message); + } else { + console.error("Unknown error:", error); + } + + process.exit(1); +} From 1330c7556e82c35aa7b75eb8dbef5ab3f3e91356 Mon Sep 17 00:00:00 2001 From: Tom Aylott Date: Tue, 11 Nov 2025 18:16:17 -0500 Subject: [PATCH 2/3] Run biome format --- typescript/fetch/src/basic/example.ts | 66 +++++++++++++-------------- 1 file changed, 32 insertions(+), 34 deletions(-) diff --git a/typescript/fetch/src/basic/example.ts b/typescript/fetch/src/basic/example.ts index 992096a..9490a62 100644 --- a/typescript/fetch/src/basic/example.ts +++ b/typescript/fetch/src/basic/example.ts @@ -1,9 +1,9 @@ /** * Example: Using OpenRouter with raw fetch API - * + * * This example demonstrates how to make direct HTTP requests to OpenRouter's API * using the native fetch API without any additional libraries. - * + * * To run: bun examples/basic/example-basic-fetch.ts */ @@ -11,7 +11,7 @@ export {}; // OpenRouter API endpoint -const OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions"; +const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions'; // Type definitions for the API response interface ChatCompletionResponse { @@ -34,39 +34,39 @@ interface ChatCompletionResponse { // Request payload following OpenAI-compatible chat completions format const requestBody = { - model: "openai/gpt-4o-mini", + model: 'openai/gpt-4o-mini', messages: [ { - role: "user", - content: "Write a haiku about TypeScript", + role: 'user', + content: 'Write a haiku about TypeScript', }, ], }; -console.log("=== OpenRouter Raw Fetch Example ===\n"); -console.log("Request:"); +console.log('=== OpenRouter Raw Fetch Example ===\n'); +console.log('Request:'); console.log(`URL: ${OPENROUTER_API_URL}`); -console.log("Model:", requestBody.model); -console.log("Message:", requestBody.messages[0]?.content); +console.log('Model:', requestBody.model); +console.log('Message:', requestBody.messages[0]?.content); console.log(); try { // Ensure API key is available if (!process.env.OPENROUTER_API_KEY) { - throw new Error("OPENROUTER_API_KEY environment variable is not set"); + throw new Error('OPENROUTER_API_KEY environment variable is not set'); } // Make the HTTP POST request to OpenRouter const response = await fetch(OPENROUTER_API_URL, { - method: "POST", + method: 'POST', headers: { // Required: Authorization header with your API key - "Authorization": `Bearer ${process.env.OPENROUTER_API_KEY}`, + Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`, // Required: Content type for JSON payload - "Content-Type": "application/json", + 'Content-Type': 'application/json', // Optional but recommended: Identify your app - "HTTP-Referer": "https://github.com/openrouter/examples", - "X-Title": "OpenRouter Fetch Example", + 'HTTP-Referer': 'https://github.com/openrouter/examples', + 'X-Title': 'OpenRouter Fetch Example', }, body: JSON.stringify(requestBody), }); @@ -74,38 +74,36 @@ try { // Check if the request was successful if (!response.ok) { const errorText = await response.text(); - throw new Error( - `HTTP error! status: ${response.status}, body: ${errorText}` - ); + throw new Error(`HTTP error! status: ${response.status}, body: ${errorText}`); } // Parse the JSON response - const data = await response.json() as ChatCompletionResponse; + const data = (await response.json()) as ChatCompletionResponse; // Display the response - console.log("Response:"); - console.log("Status:", response.status, response.statusText); - console.log("Model used:", data.model); - console.log("\nGenerated content:"); + console.log('Response:'); + console.log('Status:', response.status, response.statusText); + console.log('Model used:', data.model); + console.log('\nGenerated content:'); console.log(data.choices[0]?.message?.content); - console.log("\nUsage stats:"); - console.log("- Prompt tokens:", data.usage.prompt_tokens); - console.log("- Completion tokens:", data.usage.completion_tokens); - console.log("- Total tokens:", data.usage.total_tokens); + console.log('\nUsage stats:'); + console.log('- Prompt tokens:', data.usage.prompt_tokens); + console.log('- Completion tokens:', data.usage.completion_tokens); + console.log('- Total tokens:', data.usage.total_tokens); // Optional: Show raw response structure if (process.env.DEBUG) { - console.log("\nFull response object:"); + console.log('\nFull response object:'); console.log(JSON.stringify(data, null, 2)); } } catch (error) { - console.error("Error making request to OpenRouter:"); - + console.error('Error making request to OpenRouter:'); + if (error instanceof Error) { - console.error("Error message:", error.message); + console.error('Error message:', error.message); } else { - console.error("Unknown error:", error); + console.error('Unknown error:', error); } - + process.exit(1); } From afadffc018a43084e990ff00cc90a8916961e9c8 Mon Sep 17 00:00:00 2001 From: Tom Aylott Date: Wed, 12 Nov 2025 18:06:33 -0500 Subject: [PATCH 3/3] Remove run command and use shared type instead of duplicate --- typescript/fetch/src/basic/example.ts | 24 +----------------------- 1 file changed, 1 insertion(+), 23 deletions(-) diff --git a/typescript/fetch/src/basic/example.ts b/typescript/fetch/src/basic/example.ts index 9490a62..8af258b 100644 --- a/typescript/fetch/src/basic/example.ts +++ b/typescript/fetch/src/basic/example.ts @@ -3,35 +3,13 @@ * * This example demonstrates how to make direct HTTP requests to OpenRouter's API * using the native fetch API without any additional libraries. - * - * To run: bun examples/basic/example-basic-fetch.ts */ -// Make this a module -export {}; +import type { ChatCompletionResponse } from '@openrouter-examples/shared/types'; // OpenRouter API endpoint const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions'; -// Type definitions for the API response -interface ChatCompletionResponse { - id: string; - model: string; - choices: Array<{ - index: number; - message: { - role: string; - content: string; - }; - finish_reason: string; - }>; - usage: { - prompt_tokens: number; - completion_tokens: number; - total_tokens: number; - }; -} - // Request payload following OpenAI-compatible chat completions format const requestBody = { model: 'openai/gpt-4o-mini',