|
| 1 | +/** |
| 2 | + * Example: Using OpenRouter with raw fetch API |
| 3 | + * |
| 4 | + * This example demonstrates how to make direct HTTP requests to OpenRouter's API |
| 5 | + * using the native fetch API without any additional libraries. |
| 6 | + */ |
| 7 | + |
| 8 | +import type { ChatCompletionResponse } from '@openrouter-examples/shared/types'; |
| 9 | + |
| 10 | +// OpenRouter API endpoint |
| 11 | +const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions'; |
| 12 | + |
| 13 | +// Request payload following OpenAI-compatible chat completions format |
| 14 | +const requestBody = { |
| 15 | + model: 'openai/gpt-4o-mini', |
| 16 | + messages: [ |
| 17 | + { |
| 18 | + role: 'user', |
| 19 | + content: 'Write a haiku about TypeScript', |
| 20 | + }, |
| 21 | + ], |
| 22 | +}; |
| 23 | + |
| 24 | +console.log('=== OpenRouter Raw Fetch Example ===\n'); |
| 25 | +console.log('Request:'); |
| 26 | +console.log(`URL: ${OPENROUTER_API_URL}`); |
| 27 | +console.log('Model:', requestBody.model); |
| 28 | +console.log('Message:', requestBody.messages[0]?.content); |
| 29 | +console.log(); |
| 30 | + |
| 31 | +try { |
| 32 | + // Ensure API key is available |
| 33 | + if (!process.env.OPENROUTER_API_KEY) { |
| 34 | + throw new Error('OPENROUTER_API_KEY environment variable is not set'); |
| 35 | + } |
| 36 | + |
| 37 | + // Make the HTTP POST request to OpenRouter |
| 38 | + const response = await fetch(OPENROUTER_API_URL, { |
| 39 | + method: 'POST', |
| 40 | + headers: { |
| 41 | + // Required: Authorization header with your API key |
| 42 | + Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`, |
| 43 | + // Required: Content type for JSON payload |
| 44 | + 'Content-Type': 'application/json', |
| 45 | + // Optional but recommended: Identify your app |
| 46 | + 'HTTP-Referer': 'https://github.com/openrouter/examples', |
| 47 | + 'X-Title': 'OpenRouter Fetch Example', |
| 48 | + }, |
| 49 | + body: JSON.stringify(requestBody), |
| 50 | + }); |
| 51 | + |
| 52 | + // Check if the request was successful |
| 53 | + if (!response.ok) { |
| 54 | + const errorText = await response.text(); |
| 55 | + throw new Error(`HTTP error! status: ${response.status}, body: ${errorText}`); |
| 56 | + } |
| 57 | + |
| 58 | + // Parse the JSON response |
| 59 | + const data = (await response.json()) as ChatCompletionResponse; |
| 60 | + |
| 61 | + // Display the response |
| 62 | + console.log('Response:'); |
| 63 | + console.log('Status:', response.status, response.statusText); |
| 64 | + console.log('Model used:', data.model); |
| 65 | + console.log('\nGenerated content:'); |
| 66 | + console.log(data.choices[0]?.message?.content); |
| 67 | + console.log('\nUsage stats:'); |
| 68 | + console.log('- Prompt tokens:', data.usage.prompt_tokens); |
| 69 | + console.log('- Completion tokens:', data.usage.completion_tokens); |
| 70 | + console.log('- Total tokens:', data.usage.total_tokens); |
| 71 | + |
| 72 | + // Optional: Show raw response structure |
| 73 | + if (process.env.DEBUG) { |
| 74 | + console.log('\nFull response object:'); |
| 75 | + console.log(JSON.stringify(data, null, 2)); |
| 76 | + } |
| 77 | +} catch (error) { |
| 78 | + console.error('Error making request to OpenRouter:'); |
| 79 | + |
| 80 | + if (error instanceof Error) { |
| 81 | + console.error('Error message:', error.message); |
| 82 | + } else { |
| 83 | + console.error('Unknown error:', error); |
| 84 | + } |
| 85 | + |
| 86 | + process.exit(1); |
| 87 | +} |
0 commit comments