-
Notifications
You must be signed in to change notification settings - Fork 43
Add basic fetch example extracted from wrapper repo #47
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
subtleGradient
wants to merge
3
commits into
pdf-example-effect
Choose a base branch
from
basic-01-fetch
base: pdf-example-effect
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+87
−0
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| /** | ||
| * 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. | ||
| */ | ||
|
|
||
| import type { ChatCompletionResponse } from '@openrouter-examples/shared/types'; | ||
|
|
||
| // OpenRouter API endpoint | ||
| const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions'; | ||
|
|
||
| // 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); | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
top-level fetch?