Skip to content

[WIP] Fix AI chatbot response length for better user experience#6

Merged
redsunjin merged 1 commit intomainfrom
copilot/fix-ai-chatbot-responses
Mar 9, 2026
Merged

[WIP] Fix AI chatbot response length for better user experience#6
redsunjin merged 1 commit intomainfrom
copilot/fix-ai-chatbot-responses

Conversation

Copy link
Contributor

Copilot AI commented Mar 9, 2026

Thanks for asking me to work on this. I will get started on it and keep this PR's description up to date as I form a plan and make progress.

Original prompt

목표

AI 챗봇의 답변이 너무 길고 대화가 많아 사용자 경험이 저하되는 문제를 해결합니다.
답변을 짧고 컴팩트하게 유지하면서 2~3번 대화 안에 담당자 연결까지 완료되도록 흐름을 개선합니다.


변경 1: api/chat.js — 시스템 프롬프트 교체 + 코드 단순화

변경 내용

  • 기존의 복잡한 callGeminiWithRetry 함수 제거, 단순 try/catch로 교체
  • 시스템 프롬프트를 완전히 새로 작성:
    • 답변 3문장 이내 강제
    • 글머리 기호/번호 목록 금지
    • 한 번에 질문 하나만
    • 2번째 대화부터 [INQUIRY_COMPLETE] 태그 포함 가능, 최대 3번 후 무조건 포함
    • 전문 용어 나열 금지

완성 코드

// api/chat.js - Vercel Serverless Function
//
// ⚠️ Vercel 환경변수 설정 필요:
// GEMINI_API_KEY: Google AI Studio (https://aistudio.google.com/app/apikey)

const GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent';

const SYSTEM_INSTRUCTION = `당신은 라이트닝(Lightning) Gov-Tech AI 에이전시의 AI 상담 어시스턴트입니다.

[핵심 규칙]
- 답변은 반드시 3문장 이내로 짧고 핵심만 말하세요.
- 글머리 기호나 번호 목록은 절대 사용하지 마세요.
- 한 번에 하나의 질문만 하세요.
- 전문 용어보다 쉬운 말을 사용하세요.

[대화 목표]
사용자의 프로젝트 요구사항을 2~3번의 짧은 대화로 파악하고 담당자 연결을 유도합니다.

[대화 흐름]
1. 첫 메시지: 사용자 요청에 한 문장으로 공감 + 한 가지 핵심 질문
2. 두 번째: 답변 수용 + 라이트닝이 도울 수 있음을 한 문장으로 + [INQUIRY_COMPLETE] 태그 포함
3. 세 번째 이상: 추가 질문이 있으면 한 번만 더 묻고, 그 다음 답변에는 반드시 [INQUIRY_COMPLETE] 태그 포함

[INQUIRY_COMPLETE 태그]
- 요구사항이 어느 정도 파악되면 응답 마지막에 정확히 "[INQUIRY_COMPLETE]" 를 붙이세요.
- 최대 3번 대화 후에는 무조건 포함하세요.

[금지 사항]
- 긴 설명, 여러 옵션 나열, 기술 스펙 상세 설명 금지
- "전자정부프레임워크", "보안 규정" 등 전문 용어 나열 금지`;

module.exports = async function handler(req, res) {
  res.setHeader('Access-Control-Allow-Origin', 'https://flashgta-github-io.vercel.app');
  res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

  if (req.method === 'OPTIONS') return res.status(200).end();
  if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' });

  const apiKey = process.env.GEMINI_API_KEY;
  if (!apiKey) return res.status(500).json({ error: 'GEMINI_API_KEY not configured' });

  const { contents } = req.body;
  if (!contents || !Array.isArray(contents)) return res.status(400).json({ error: 'Invalid request body' });

  try {
    const response = await fetch(`${GEMINI_API_URL}?key=${apiKey}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        contents,
        systemInstruction: { parts: [{ text: SYSTEM_INSTRUCTION }] }
      })
    });

    if (response.status === 429) {
      return res.status(429).json({ error: 'Too many requests. Please wait a moment.' });
    }

    if (!response.ok) {
      const errBody = await response.text();
      throw new Error(`HTTP ${response.status}: ${errBody}`);
    }

    const data = await response.json();
    return res.status(200).json({ text: data.candidates[0].content.parts[0].text });
  } catch (error) {
    console.error('Gemini API error:', error);
    return res.status(500).json({ error: 'Failed to get AI response' });
  }
};

변경 2: index.html — 메시지 및 대화 흐름 간소화

현재 index.html의 BlobSha: e916096c50d1c850c97c3f93f552a8808a36f943

변경 포인트

  1. 웰컴 메시지 (line 98~103) 4줄 → 2줄로 단축:
<div class="message ai">
    안녕하세요! ⚡ 라이트닝 AI입니다.<br>
    어떤 프로젝트가 필요하신가요? 간단히 말씀해 주세요.
</div>
  1. handleInquiryStep 함수while 루프 제거, try/catch 단순화:
async function handleInquiryStep(text) {
    conversationHistory.push({ role: 'user', parts: [{ text }] });
    showTyping();

    try {
        const response = await fetch('/api/chat', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ contents: conversationHistory })
        });

        if (response.status === 429) {
            hideTyping();
            appendMessage('요청이 많습니다. 잠시 후 다시 시도해 주세요. 🙏', 'ai');
            conversationHistory.pop();
            return;
        }

        if (!response.ok) throw new Error(`HTTP ${response.status}`);

        const data = await response.json();
        const aiText = data.text;

        hideTyping();

        const cleanText = aiText.replace(/\[INQUIRY_COMPLETE\]/g, '').trim();
        appendMessage(cleanText, 'ai');
        displayHistory.push({ role: 'ai', text: cleanText });
        conversationHistory.push({ role: 'model', parts: [{ text: aiText }] });

        if (inquirySummary === '') {
            inquirySummary = conversationHistory[0].parts[0].text;
        }

        if (aiText.includes('[INQUIRY_COMPLETE]')) {
            step = 'privacy';
            setTimeout(() => {
                appendMessage('담당자 연결을 위해 연락처를 남겨주세요.\n개인정보는 상담 목적으로만 사용됩니다. 동의하시나요? (예 / 아니오)', 'ai');
            }, 400);
        }

    } catch (err) {
        hideTyping();
        appendMessage('응답이 지연되고 있습니다. 잠시 후 다시 시도해주세요.', 'ai');
        conversationHistory.pop();
    }
}
  1. 개인정보 거절 시 메시지: '알겠습니다. 언제든지 다시 방문해 주세요. 😊'

  2. 연락처 요청 메시지: `${collectedName}님, 이메일 또는 전화번호를 알려주세요.`

  3. 발송 성공 메시지: '접수 완료! 담당자가 확인 후 연락드리겠습니다. ⚡'


기대 효과

  • 대화 턴 수: 기존 34회 → **23회**로 단축
  • 답변 길이: 기존 긴 설명 → 3문장 이내
  • 담당자 연결 속도: 더...

This pull request was created from Copilot chat.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

@vercel
Copy link

vercel bot commented Mar 9, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
flashgta-github-io Ready Ready Preview, Comment Mar 9, 2026 3:06pm

@redsunjin redsunjin marked this pull request as ready for review March 9, 2026 15:06
@redsunjin redsunjin merged commit a5f3f29 into main Mar 9, 2026
2 of 3 checks passed
Copilot stopped work on behalf of redsunjin due to an error March 9, 2026 15:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants