-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-direct-api.js
More file actions
executable file
·155 lines (133 loc) · 4.76 KB
/
test-direct-api.js
File metadata and controls
executable file
·155 lines (133 loc) · 4.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#!/usr/bin/env node
const fs = require('fs').promises;
const path = require('path');
async function testImageGeneration() {
const apiKey = process.env.OPENROUTER_API_KEY;
if (!apiKey) {
console.error('❌ OPENROUTER_API_KEY not set');
return;
}
console.log('🔑 API Key loaded:', apiKey.substring(0, 10) + '...');
// Test with Gemini image generation
const requestBody = {
model: 'google/gemini-2.0-flash-exp:free',
messages: [
{
role: 'user',
content: 'Generate an ultra-realistic 4K photo: A cute cat sitting on a windowsill during sunset'
}
],
temperature: 0.7,
max_tokens: 4096
};
console.log('\n📤 Sending request to OpenRouter...');
console.log('Model:', requestBody.model);
console.log('Prompt:', requestBody.messages[0].content);
try {
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'HTTP-Referer': 'https://github.com/openrouter-image-gen-mcp',
'X-Title': 'OpenRouter Image Test'
},
body: JSON.stringify(requestBody)
});
console.log('\n📥 Response Status:', response.status, response.statusText);
if (!response.ok) {
const errorText = await response.text();
console.error('❌ Error Response:', errorText);
return;
}
const data = await response.json();
console.log('\n✅ Response received!');
// Log the full response structure
console.log('\n📊 Response structure:');
console.log(JSON.stringify(data, null, 2));
if (data.choices && data.choices[0]) {
const content = data.choices[0].message.content;
console.log('\n📝 Content type:', typeof content);
console.log('Content length:', content.length);
// Check if it's a URL
if (content.startsWith('http')) {
console.log('\n🔗 Got URL:', content);
await saveImageFromUrl(content);
}
// Check if it's a data URL
else if (content.startsWith('data:image')) {
console.log('\n🖼️ Got data URL');
await saveImageFromDataUrl(content);
}
// Check if it contains a URL in the text
else if (content.includes('http')) {
const urlMatch = content.match(/https?:\/\/[^\s]+/);
if (urlMatch) {
console.log('\n🔗 Found URL in content:', urlMatch[0]);
await saveImageFromUrl(urlMatch[0]);
}
}
// Otherwise it might be base64 or text
else {
console.log('\n📄 Content preview (first 200 chars):');
console.log(content.substring(0, 200));
// Try to decode as base64
if (content.length > 1000 && !content.includes(' ')) {
console.log('\n🔍 Attempting to decode as base64...');
await saveImageFromBase64(content);
} else {
console.log('\n⚠️ Content appears to be text, not an image');
}
}
}
} catch (error) {
console.error('\n❌ Error:', error.message);
console.error(error.stack);
}
}
async function saveImageFromUrl(url) {
console.log('\n💾 Downloading image from URL...');
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch image: ${response.status}`);
}
const buffer = await response.arrayBuffer();
const filename = `test_image_${Date.now()}.png`;
await fs.writeFile(filename, Buffer.from(buffer));
console.log('✅ Image saved as:', filename);
} catch (error) {
console.error('❌ Failed to save image from URL:', error.message);
}
}
async function saveImageFromDataUrl(dataUrl) {
console.log('\n💾 Saving image from data URL...');
try {
const matches = dataUrl.match(/^data:([^;]+);base64,(.+)$/);
if (!matches) {
throw new Error('Invalid data URL format');
}
const mimeType = matches[1];
const base64Data = matches[2];
const ext = mimeType.split('/')[1] || 'png';
const buffer = Buffer.from(base64Data, 'base64');
const filename = `test_image_${Date.now()}.${ext}`;
await fs.writeFile(filename, buffer);
console.log('✅ Image saved as:', filename);
} catch (error) {
console.error('❌ Failed to save image from data URL:', error.message);
}
}
async function saveImageFromBase64(base64) {
console.log('\n💾 Saving image from base64...');
try {
const buffer = Buffer.from(base64, 'base64');
const filename = `test_image_${Date.now()}.png`;
await fs.writeFile(filename, buffer);
console.log('✅ Image saved as:', filename);
} catch (error) {
console.error('❌ Failed to save image from base64:', error.message);
}
}
// Run the test
testImageGeneration();