This commit is contained in:
dsyoon
2025-08-18 09:40:54 +09:00
commit d56d136522
26 changed files with 4593 additions and 0 deletions

View File

@@ -0,0 +1,72 @@
export async function fetchOpenAIChat(messages, model="gpt-3.5-turbo", options={}) {
const apiKey = import.meta.env.VITE_OPENAI_API_KEY || import.meta.env.OPENAI_API_KEY;
if (!apiKey) throw new Error('OPENAI API KEY not set');
const body = {
model,
messages,
};
const res = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify(body),
});
if (!res.ok) throw new Error(`OpenAI error ${res.status}`);
const data = await res.json();
return data.choices?.[0]?.message?.content || '';
}
// 샘플코드 방식: GPT-5로 이미지/텍스트 분류
export async function classifyRequest(userInput, model = 'gpt-5') {
const content = await fetchOpenAIChat(
[
{ role: 'system', content: '너는 요청 분류기다. 사용자가 이미지 생성을 원하면 image, 아니면 text라고만 답해라.' },
{ role: 'user', content: `사용자가 다음과 같은 요청을 했습니다:\n"${userInput}"\n이 요청이 '이미지 생성'에 해당하면 'image'라고만 답하고, 그렇지 않으면 'text'라고만 답하세요.` },
],
model,
{ temperature: 0 }
);
const answer = (content || '').trim().toLowerCase();
return answer.includes('image') ? 'image' : 'text';
}
// 이미지 생성 API 호출 (gpt-image-1 또는 호환 모델)
export async function fetchOpenAIImage(prompt, model = "gpt-image-1", options = {}) {
const apiKey = import.meta.env.VITE_OPENAI_API_KEY || import.meta.env.OPENAI_API_KEY;
if (!apiKey) throw new Error('OPENAI API KEY not set');
const runOnce = async (mdl) => {
const body = {
model: mdl,
prompt,
size: options.size || '1024x1024',
response_format: 'b64_json',
};
const res = await fetch('https://api.openai.com/v1/images/generations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify(body),
});
if (!res.ok) throw new Error(`OpenAI image error ${res.status}`);
const data = await res.json();
const item = data?.data?.[0] || {};
if (item.b64_json) return `data:image/png;base64,${item.b64_json}`;
if (item.url) return item.url; // some models may return URL
throw new Error('No image returned');
};
// 우선 gpt-image-1 시도 → 실패 시 dall-e-3 폴백
try {
return await runOnce(model || 'gpt-image-1');
} catch (_) {
return await runOnce('dall-e-3');
}
}