
Nano Banana 2 API는 PoYo에서 제공하는 저비용 Nano Banana 경로로, Nano Banana Pro와는 별도로 운영됩니다. 이 가이드에서는 nano-banana-2 및 nano-banana-2-edit를 사용하는 방법을 단계별로 안내하며, 생성 1회당 5 크레딧부터, 1K 출력 기준 약 $0.025의 비용으로 이용할 수 있습니다.
Nano Banana 2 API 시작하기
1단계: PoYo 계정 설정
먼저 PoYo 계정을 생성하고 API 인증 정보를 발급받으세요.
2단계: 필요한 의존성 설치
# For Node.js/JavaScript
npm install axios
# For Python
pip install requests
# For cURL (no installation needed)
기본 텍스트-이미지 생성
JavaScript/Node.js 구현
const axios = require('axios');
const generateImage = async (prompt, size = '1:1') => {
try {
const response = await axios.post(
'https://api.poyo.ai/api/generate/submit',
{
model: 'nano-banana-2',
callback_url: 'https://your-domain.com/callback', // Optional webhook
input: {
prompt: prompt,
size: size // Options: '1:1', '16:9', '9:16', '2:3', '3:2', '3:4', '4:3'
}
},
{
headers: {
'Authorization': `Bearer YOUR_API_KEY`,
'Content-Type': 'application/json'
}
}
);
console.log('Task ID:', response.data.task_id);
console.log('Status:', response.data.status);
console.log('Created:', response.data.created_time);
return response.data;
} catch (error) {
console.error('Error generating image:', error.response?.data || error.message);
}
};
// Example usage
generateImage('A futuristic city skyline at sunset with flying cars', '16:9');
Python 구현
import requests
import json
def generate_image(prompt, api_key, size='1:1'):
url = "https://api.poyo.ai/api/generate/submit"
payload = {
"model": "nano-banana-2",
"callback_url": "https://your-domain.com/callback", # Optional webhook
"input": {
"prompt": prompt,
"size": size # Options: '1:1', '16:9', '9:16', '2:3', '3:2', '3:4', '4:3'
}
}
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
result = response.json()
print(f"Task ID: {result['task_id']}")
print(f"Status: {result['status']}")
print(f"Created: {result['created_time']}")
return result
except requests.exceptions.RequestException as e:
print(f"Error generating image: {e}")
return None
# Example usage
api_key = "YOUR_API_KEY"
result = generate_image("A serene mountain landscape with crystal clear lake", api_key, '16:9')
cURL 구현
curl -X POST "https://api.poyo.ai/api/generate/submit" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "nano-banana-2",
"callback_url": "https://your-domain.com/callback",
"input": {
"prompt": "A professional headshot of a confident business woman in modern office setting",
"size": "1:1"
}
}'
Nano Banana 2의 고급 기능
1. 문화적 맥락 이해
Nano Banana 2의 문화 이해 기능을 활용하면 지역 특성에 맞는 자연스러운 콘텐츠를 생성할 수 있습니다.
const culturalPrompts = [
"Tokyo springtime cherry blossom picnic with families in traditional dress",
"Berlin winter street fashion with authentic German architecture",
"Mumbai monsoon street food vendor with vibrant local atmosphere"
];
// Generate culturally accurate images
culturalPrompts.forEach(async (prompt) => {
const result = await generateImage(prompt);
console.log(`Generated culturally aware image for: ${prompt}`);
});
2. 완벽한 텍스트 렌더링
수학 공식과 복잡한 텍스트가 포함된 이미지를 생성할 수 있습니다.
def generate_educational_content(equation, api_key):
prompt = f"A clean whiteboard with the mathematical equation '{equation}' written in clear handwriting, classroom setting"
payload = {
"model": "nano-banana-2",
"prompt": prompt,
"width": 1024,
"height": 768,
"guidance_scale": 8.0,
"num_inference_steps": 60
}
return generate_image_with_payload(payload, api_key)
# Generate educational content with perfect text
result = generate_educational_content("E = mc虏", "YOUR_API_KEY")
3. 다양한 화면 비율 지원
Nano Banana 2는 다양한 활용 사례에 맞는 여러 화면 비율을 지원합니다.
const aspectRatios = {
square: { width: 1024, height: 1024 }, // 1:1 - Social media
portrait: { width: 768, height: 1024 }, // 3:4 - Mobile screens
landscape: { width: 1024, height: 768 }, // 4:3 - Desktop
widescreen: { width: 1792, height: 1024 }, // 16:9 - Video thumbnails
ultrawide: { width: 2048, height: 896 } // 21:9 - Banners
};
const generateWithAspectRatio = async (prompt, ratio) => {
const dimensions = aspectRatios[ratio];
const response = await axios.post(
'https://api.poyo.ai/v1/image/generations',
{
model: 'nano-banana-2',
prompt: prompt,
...dimensions,
guidance_scale: 7.5
},
{
headers: {
'Authorization': `Bearer YOUR_API_KEY`,
'Content-Type': 'application/json'
}
}
);
return response.data;
};
Nano Banana 2를 활용한 이미지 편집
이미지 간 변환
const editImage = async (imageUrls, editPrompt, size = '1:1') => {
try {
const response = await axios.post(
'https://api.poyo.ai/api/generate/submit',
{
model: 'nano-banana-2-edit',
callback_url: 'https://your-domain.com/callback', // Optional
input: {
prompt: editPrompt,
image_urls: imageUrls, // Array of reference image URLs
size: size
}
},
{
headers: {
'Authorization': `Bearer YOUR_API_KEY`,
'Content-Type': 'application/json'
}
}
);
return response.data;
} catch (error) {
console.error('Error editing image:', error.response?.data || error.message);
}
};
// Example: Transform day scene to night
const result = await editImage(
['https://example.com/day-scene.jpg'],
'Transform this scene to a beautiful night setting with stars and moon',
'16:9'
);
웹훅을 사용한 결과 처리
Nano Banana 2 API는 결과 전달을 위해 웹훅을 사용합니다. 결과를 수신하려면 웹훅 엔드포인트를 설정하세요.
웹훅 엔드포인트 설정
// Express.js webhook handler
const express = require('express');
const app = express();
app.use(express.json());
// Webhook endpoint to receive results
app.post('/webhook/callback', (req, res) => {
const { task_id, status, files } = req.body;
console.log(`Task ${task_id} status: ${status}`);
if (status === 'finished' && files && files.length > 0) {
console.log('Generated image URL:', files[0].file_url);
// Process the completed image
processGeneratedImage(task_id, files[0].file_url);
} else if (status === 'failed') {
console.error('Generation failed for task:', task_id);
handleGenerationError(task_id);
}
res.status(200).send('OK');
});
const processGeneratedImage = (taskId, imageUrl) => {
// Your logic to handle the completed image
console.log(`Processing image from task ${taskId}: ${imageUrl}`);
};
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});
대안: 수동 상태 확인
웹훅을 사용하지 않으려면 작업 상태를 직접 확인할 수 있습니다.
const checkTaskStatus = async (taskId) => {
try {
const response = await axios.get(
`https://api.poyo.ai/api/generate/status/${taskId}`,
{
headers: {
'Authorization': `Bearer YOUR_API_KEY`
}
}
);
return response.data.data; // Returns the task data
} catch (error) {
console.error('Error checking status:', error.message);
return null;
}
};
const pollForResult = async (taskId, maxAttempts = 30) => {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const taskData = await checkTaskStatus(taskId);
if (!taskData) break;
console.log(`Status: ${taskData.status}, Progress: ${taskData.progress}%`);
if (taskData.status === 'finished') {
console.log('Image generated successfully!');
if (taskData.files && taskData.files.length > 0) {
console.log('Image URL:', taskData.files[0].file_url);
}
return taskData;
} else if (taskData.status === 'failed') {
console.error('Generation failed:', taskData.error_message);
return null;
}
// Status is 'not_started' or 'running'
await new Promise(resolve => setTimeout(resolve, 3000)); // Wait 3 seconds
}
console.error('Maximum polling attempts reached');
return null;
};
// Complete workflow example
const completeGeneration = async (prompt) => {
// Step 1: Submit generation request
const generation = await generateImage(prompt);
if (!generation) return null;
// Step 2: Poll for results
const result = await pollForResult(generation.task_id);
return result;
};
Python 상태 확인
import time
def check_task_status(task_id, api_key):
url = f"https://api.poyo.ai/api/generate/status/{task_id}"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.json()['data']
except requests.exceptions.RequestException as e:
print(f"Error checking status: {e}")
return None
def wait_for_completion(task_id, api_key, max_attempts=30):
for attempt in range(max_attempts):
task_data = check_task_status(task_id, api_key)
if not task_data:
break
print(f"Status: {task_data['status']}, Progress: {task_data.get('progress', 0)}%")
if task_data['status'] == 'finished':
print("Image generated successfully!")
if task_data.get('files') and len(task_data['files']) > 0:
print(f"Image URL: {task_data['files'][0]['file_url']}")
return task_data
elif task_data['status'] == 'failed':
print(f"Generation failed: {task_data.get('error_message', 'Unknown error')}")
return None
time.sleep(3) # Wait 3 seconds
print("Maximum attempts reached")
return None
# Complete workflow
def complete_image_generation(prompt, api_key, size='1:1'):
# Step 1: Submit request
task_result = generate_image(prompt, api_key, size)
if not task_result:
return None
# Step 2: Wait for completion
final_result = wait_for_completion(task_result['task_id'], api_key)
return final_result
오류 처리 및 모범 사례
종합적인 오류 처리
const robustImageGeneration = async (prompt, size = '1:1', retries = 3) => {
for (let attempt = 0; attempt < retries; attempt++) {
try {
const response = await axios.post(
'https://api.poyo.ai/api/generate/submit',
{
model: 'nano-banana-2',
input: {
prompt: prompt,
size: size
}
},
{
headers: {
'Authorization': `Bearer YOUR_API_KEY`,
'Content-Type': 'application/json'
},
timeout: 30000 // 30 second timeout
}
);
return response.data;
} catch (error) {
if (error.response) {
// Server responded with error status
const status = error.response.status;
const message = error.response.data?.error || 'Unknown error';
console.error(`API Error (${status}): ${message}`);
// Don't retry for certain errors
if (status === 401 || status === 403) {
throw new Error('Authentication failed. Check your API key.');
}
if (status === 400) {
throw new Error(`Bad request: ${message}`);
}
} else if (error.request) {
console.error('Network error:', error.message);
} else {
console.error('Request setup error:', error.message);
}
// If this was the last attempt, throw the error
if (attempt === retries - 1) {
throw error;
}
// Wait before retrying (exponential backoff)
const delay = Math.pow(2, attempt) * 1000;
console.log(`Retrying in ${delay}ms... (Attempt ${attempt + 1}/${retries})`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
};
프로덕션 환경을 위한 모범 사례
- 속도 제한 관리: API 제한 초과를 방지하기 위해 적절한 속도 제한을 구현하세요.
- 캐싱: 성공적으로 생성된 결과를 캐싱하여 API 호출을 줄이세요.
- 사용자 경험 개선: 오래 걸리는 생성 작업에는 진행 상태 표시기를 제공하세요.
- 오류 복구: 생성 실패 시 안정적인 대체 처리를 구현하세요.
class NanoBanana2Client {
constructor(apiKey, options = {}) {
this.apiKey = apiKey;
this.baseURL = 'https://api.poyo.ai/v1';
this.requestsPerMinute = options.requestsPerMinute || 60;
this.queue = [];
}
async generateImage(prompt, options = {}) {
const payload = {
model: 'nano-banana-2',
prompt,
width: options.width || 1024,
height: options.height || 1024,
guidance_scale: options.guidanceScale || 7.5,
num_inference_steps: options.steps || 50
};
return this.makeRequest('/image/generations', payload);
}
async editImage(imageUrl, editPrompt, options = {}) {
const payload = {
model: 'nano-banana-2-edit',
image: imageUrl,
prompt: editPrompt,
strength: options.strength || 0.8,
guidance_scale: options.guidanceScale || 7.5
};
return this.makeRequest('/image/edits', payload);
}
async makeRequest(endpoint, payload) {
// Implement rate limiting, error handling, and retries
// This is a simplified version
try {
const response = await axios.post(
`${this.baseURL}${endpoint}`,
payload,
{
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
}
}
);
return response.data;
} catch (error) {
throw this.handleError(error);
}
}
handleError(error) {
// Implement comprehensive error handling
return new Error(`Nano Banana 2 API Error: ${error.message}`);
}
}
성능 최적화 팁
1. 프롬프트 엔지니어링
- 구체적으로 작성하기: 상세한 프롬프트일수록 더 좋은 결과를 얻을 수 있습니다.
- 스타일 지시어 포함하기: "photorealistic", "4K resolution", "professional" 같은 표현을 활용하세요.
- 문화적 맥락 활용하기: Nano Banana 2의 문화 이해 기능을 활용하세요.
2. 매개변수 조정
- guidance_scale: 대부분의 사용 사례에서 7.0-8.5 권장
- num_inference_steps: 30-60 (더 높은 값은 더 나은 품질 제공)
- strength: 이미지 편집 시 0.6-0.9 (낮을수록 원본 보존 비율 증가)
3. 일괄 처리
const generateBatch = async (prompts) => {
const generations = await Promise.all(
prompts.map(prompt => generateImage(prompt))
);
const results = await Promise.all(
generations.map(gen => pollForResult(gen.id))
);
return results.filter(result => result !== null);
};
결론
PoYo의 Nano Banana 2 API는 혁신적인 5단계 워크플로, 문화적 맥락 이해, 완벽한 텍스트 렌더링 기능을 통해 AI 이미지 생성 분야에서 새로운 수준의 기능을 제공합니다. 이 가이드를 따라 강력한 기능을 애플리케이션에 통합하고 전문가 수준의 시각 콘텐츠를 제작할 수 있습니다.
더 고급 기능과 전체 API 문서는 공식 Nano Banana 2 API 문서를 방문하세요.
지금 바로 개발을 시작할 준비가 되셨나요? API 키 발급을 받고 오늘부터 Nano Banana 2로 제작을 시작하세요.
구현 과정에서 도움이 필요하신가요? 개발자 커뮤니티에 참여하거나 더 많은 API 튜토리얼을 확인해 고급 기술을 배워보세요.