AI API를 처음 사용하다 보면, 요청을 보냈는데 응답의 content가 비어 있는 경우가 있습니다. "왜 아무것도 안 오는 거지?"라고 당황할 수 있습니다. 이 글에서는 그 원인과 해결 방법을 초보자도 쉽게 이해할 수 있도록 설명합니다.

finish_reason이란?

API가 응답을 끝낸 이유를 알려주는 표시입니다. 마치 친구가 말을 끝내는 방식과 같습니다.

content_filter가 뜨는 이유

AI 모델은 유해하거나 부적절한 내용을 걸러냅니다. 이때 content_filter 상태가 표시되면서 실제 답변 대신 빈 값이 돌아옵니다. 마치 검열기에 걸린 편지처럼 아무 내용도 보이지 않는 것입니다.

단계별 실습: 빈 응답 확인하고 대처하기

1단계: 응답 구조 확인하기

가장 먼저 해야 할 일은 API가 돌려주는 전체 응답을 보는 것입니다. 다음 코드를 따라 해보세요.

const axios = require('axios');

async function checkResponse() {
    try {
        const response = await axios.post(
            'https://api.holysheep.ai/v1/chat/completions',
            {
                model: 'gpt-4o-mini',
                messages: [
                    { 
                        role: 'user', 
                        content: '인공지능에 대해 설명해줘' 
                    }
                ],
                max_tokens: 100
            },
            {
                headers: {
                    'Authorization': 'Bearer YOUR_HOLYSHEEP_API_KEY',
                    'Content-Type': 'application/json'
                }
            }
        );

        // 응답 전체 확인
        console.log('=== 전체 응답 ===');
        console.log(JSON.stringify(response.data, null, 2));

        // 핵심 정보 추출
        const choice = response.data.choices[0];
        console.log('\n=== 핵심 정보 ===');
        console.log('finish_reason:', choice.finish_reason);
        console.log('content:', choice.message.content);

    } catch (error) {
        console.error('오류 발생:', error.response?.data || error.message);
    }
}

checkResponse();

2단계: 빈 응답 자동 감지하기

이제 빈 응답이 돌아올 때 자동으로 알려주는 코드를 만들어보겠습니다.

const axios = require('axios');

async function safeChat(message) {
    try {
        const response = await axios.post(
            'https://api.holysheep.ai/v1/chat/completions',
            {
                model: 'gpt-4o-mini',
                messages: [
                    { role: 'user', content: message }
                ],
                max_tokens: 500
            },
            {
                headers: {
                    'Authorization': 'Bearer YOUR_HOLYSHEEP_API_KEY',
                    'Content-Type': 'application/json'
                }
            }
        );

        const choice = response.data.choices[0];
        const content = choice.message.content;
        const reason = choice.finish_reason;

        // 빈 응답 감지
        if (!content || content.trim() === '') {
            console.log('⚠️ 빈 응답이 돌아왔습니다');
            console.log('이유:', reason);
            
            // 이유별 대처법
            if (reason === 'content_filter') {
                console.log('→ 안전 필터가 작동했습니다. 질문을 다르게 해보세요.');
            } else if (reason === 'length') {
                console.log('→ 최대 길이에 도달했습니다. max_tokens를 늘려보세요.');
            }
            return null;
        }

        return content;

    } catch (error) {
        console.error('API 오류:', error.response?.data || error.message);
        return null;
    }
}

// 테스트
safeChat('안녕하세요!');

3단계: HolySheep AI에서 여러 모델 비교하기

같은 질문을 서로 다른 모델에 보내서 어떤 모델이 더 잘 응답하는지 비교할 수 있습니다. HolySheep AI를 사용하면 하나의 API 키로 여러 모델을 쉽게 테스트할 수 있습니다.

const axios = require('axios');

const HOLYSHEEP_API_KEY = 'YOUR_HOLYSHEEP_API_KEY';
const BASE_URL = 'https://api.holysheep.ai/v1';

const models = [
    'gpt-4o-mini',
    'gpt-4.1-nano',
    'claude-sonnet-4-20250514',
    'deepseek-chat-v3-0324'
];

async function compareModels(question) {
    console.log(질문: ${question}\n);
    console.log('=' .repeat(50));

    for (const model of models) {
        try {
            const response = await axios.post(
                ${BASE_URL}/chat/completions,
                {
                    model: model,
                    messages: [{ role: 'user', content: question }],
                    max_tokens: 200
                },
                {
                    headers: {
                        'Authorization': Bearer ${HOLYSHEEP_API_KEY},
                        'Content-Type': 'application/json'
                    }
                }
            );

            const content = response.data.choices[0].message.content;
            const reason = response.data.choices[0].finish_reason;

            console.log(\n[${model}]);
            console.log(finish_reason: ${reason});
            console.log(content: ${content ? content.substring(0, 50) + '...' : '(비어있음)'});

        } catch (error) {
            console.log(\n[${model}]);
            console.log(오류: ${error.response?.data?.error?.message || error.message});
        }
    }
}

compareModels('파이썬으로 "안녕" 출력하는 방법을 알려줘');

자주 발생하는 오류 해결

1. content_filter가 뜨면서 빈 응답이 돌아올 때

원인: 질문 내용이 안전 필터에 걸린 경우입니다.

해결 방법:

2. finish_reason이 length인데 응답이 비어있을 때

원인: max_tokens 값이 너무 작아서 아무 내용도 출력하기 전에 최대치에 도달한 경우입니다.

해결 방법:

3. finish_reason이 null이고 content도 없을 때

원인: 아직 응답이 완료되지 않았거나 서버 연결 문제일 수 있습니다.

해결 방법:

4. choices 배열이 비어있을 때

원인: 시스템 프롬프트나 설정에 문제가 있어 응답이 생성되지 않은 경우입니다.

해결 방법:

5. API 키 오류로 빈 응답이 올 때

원인: API 키가 없거나 잘못된 경우 서버가 빈 응답을 반환할 수 있습니다.

해결 방법:

정리

API 응답이 비어있는 건 여러 이유가 있을 수 있습니다. 가장 중요한 것은 finish_reason을 반드시 확인하는 것입니다. 이 값이 'stop'이면 정상이고, 'content_filter'이면 질문 내용을 바꿔보시고, 'length'이면 max_tokens를 늘리시면 됩니다.

HolySheep AI는 하나의 API 키로 여러 모델을 쉽게試해볼 수 있어서, 어떤 모델이 내 질문에 가장 잘 답하는지 비교하기에도 좋습니다.

개발할 때 이 체크리스트를 항상 기억하세요:

이 기본을掌握하면 API 문제를 해결하는 데 큰 도움이 됩니다. Happy coding!

👉 HolySheep AI 가입하고 무료 크레딧 받기