본문 바로가기
프로그래밍/프로그래밍 기타

ChatGPT API 사용법

by freeelifee 2025. 4. 11.
728x90

✅ ChatGPT API 키 발급 방법 (OpenAI)

🔹 1. OpenAI 사이트 접속

👉 https://platform.openai.com
→ OpenAI의 공식 API 플랫폼 페이지입니다.


🔹 2. 로그인 또는 회원가입

  • 기존 계정이 있다면 로그인
  • 없다면 구글 계정, 깃허브 계정, 이메일 등으로 가입

🔹 3. 대시보드로 이동

로그인 후 아래 주소로 자동 이동하거나, 직접 접속하세요:
👉 https://platform.openai.com/account/api-keys


🔹 4. API 키 발급

  1. 상단 메뉴에서 "API Keys" 선택
  2. "Create new secret key" 버튼 클릭
  3. 원하는 이름 입력 (예: "my-first-key")
  4. 발급된 키를 복사해서 저장합니다

⚠️ 키는 한 번만 표시되며, 다시 확인할 수 없으니 안전한 곳에 복사해두세요!


🔹 5. API 키 사용 예시

openai.api_key = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

이 키를 코드에 넣으면 OpenAI API와 연결됩니다.


🔐 보안 팁

  • 절대 깃허브, 블로그 등에 키를 올리지 마세요!
  • 유출된 경우, API Keys 페이지에서 "Revoke" (폐기) 하고 다시 만들 수 있어요.

 

✅ ChatGPT API 사용법

🔹 1단계: 라이브러리 설치

pip install openai  # OpenAI의 Python 라이브러리를 설치

🔹 2단계: API 키 설정 및 불러오기

import openai  # OpenAI API를 사용하기 위한 라이브러리 import

openai.api_key = "your-api-key"  # 발급받은 OpenAI API 키를 여기에 넣기

🔐 your-api-key에는 직접 발급받은 비밀 키를 넣어야 해요. 유출되지 않게 주의!


🔹 3단계: ChatGPT 모델 호출 (기본 예제)

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",  # 사용할 모델 이름 (gpt-4 도 가능)
    messages=[  # 대화 형식으로 메시지를 구성
        {"role": "system", "content": "You are a helpful assistant."},  # 시스템 메시지: AI의 역할 설정
        {"role": "user", "content": "What's the capital of France?"}   # 유저가 보낸 메시지
    ]
)

🔹 4단계: 응답 출력

print(response.choices[0].message["content"])  # AI의 응답 내용 출력

🔹 전체 코드 한 번에 보기 (설명 포함)

import openai

# 발급받은 API 키 입력
openai.api_key = "your-api-key"

# 대화 구성 및 GPT 모델 호출
response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",  # 또는 "gpt-4"
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},  # 시스템 프롬프트
        {"role": "user", "content": "What's the capital of France?"}    # 유저 질문
    ]
)

# 응답 내용 출력
print(response.choices[0].message["content"])

💡 추가 옵션도 있어요 (선택사항)

옵션 설명

temperature 창의성 조절 (0 = 일관됨, 1 = 자연스러움, 2 = 매우 창의적)
max_tokens 응답 길이 제한
top_p nucleus sampling 설정 (일반적으로 temperature랑 같이 안 씀)
stop 특정 토큰이 나오면 응답 멈춤

예시:

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[...],
    temperature=0.7,
    max_tokens=100
)

 


✅ Node.js에서 ChatGPT API 사용하기 (OpenAI API)

🔹 1단계: 프로젝트 폴더 만들기

mkdir chatgpt-node
cd chatgpt-node
npm init -y

🔹 2단계: 필요한 라이브러리 설치

npm install openai dotenv

openai는 OpenAI 공식 라이브러리,
dotenv는 API 키 같은 민감한 정보를 .env 파일에 안전하게 저장하기 위해 사용해요.


🔹 3단계: .env 파일 만들기 (API 키 저장)

// .env 파일 (프로젝트 루트에 생성)
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

🔹 4단계: ChatGPT 호출 코드 작성 (index.js)

// index.js
const { OpenAI } = require("openai");
require("dotenv").config();  // .env 파일에서 환경변수 불러오기

// OpenAI 클라이언트 초기화
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,  // API 키 가져오기
});

// 비동기 함수로 GPT 호출
async function askChatGPT() {
  const response = await openai.chat.completions.create({
    model: "gpt-3.5-turbo",  // 또는 "gpt-4"
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: "What is the capital of South Korea?" },
    ],
  });

  console.log("💬 ChatGPT 응답:", response.choices[0].message.content);
}

// 실행
askChatGPT();

🔹 5단계: 실행하기

node index.js

✅ 결과:

💬 ChatGPT 응답: The capital of South Korea is Seoul.

✅ 메시지 구조 정리

role 의미

system AI에게 역할을 지정 (도우미 등)
user 사용자의 질문
assistant (선택) 이전에 AI가 응답한 내용 기록

**웹(Web)**에서 ChatGPT API를 사용하는 방법
프론트엔드(HTML + JS)와 백엔드(Node.js + Express)를 연결해서 브라우저에서 질문 → ChatGPT 응답 출력 구조로 만들 수 있어요.


✅ 목표: 웹에서 ChatGPT에 질문하고 응답 받기

구성:

  • 프론트엔드: 사용자 입력창 + 결과 표시
  • 백엔드 (Node.js): OpenAI API에 요청 전송
  • API 키는 백엔드에만 저장 (보안 중요!)

🔧 1. 프로젝트 구조 예시

chatgpt-web/
├── server.js         ← Node.js 백엔드
├── .env              ← OpenAI API 키 저장
├── public/
│   └── index.html    ← 브라우저용 HTML

✅ 2. 백엔드 코드 (server.js)

const express = require("express");
const path = require("path");
const { OpenAI } = require("openai");
require("dotenv").config();

const app = express();
const PORT = 3000;

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

app.use(express.json());
app.use(express.static("public")); // static HTML, JS 제공

// ChatGPT API 요청 처리
app.post("/chat", async (req, res) => {
  const userMessage = req.body.message;

  try {
    const response = await openai.chat.completions.create({
      model: "gpt-3.5-turbo",
      messages: [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: userMessage },
      ],
    });

    const reply = response.choices[0].message.content;
    res.json({ reply });
  } catch (error) {
    console.error("OpenAI API 오류:", error);
    res.status(500).json({ error: "문제가 발생했습니다." });
  }
});

app.listen(PORT, () => {
  console.log(`✅ 서버 실행 중: http://localhost:${PORT}`);
});

✅ 3. .env 파일

OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

dotenv를 사용해서 API 키는 절대 코드에 직접 쓰지 않도록 해요!


✅ 4. 프론트엔드 (public/index.html)

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>ChatGPT 웹 데모</title>
</head>
<body>
  <h1>💬 ChatGPT에게 물어보세요</h1>
  <input id="userInput" type="text" placeholder="질문을 입력하세요" />
  <button onclick="sendMessage()">보내기</button>
  <pre id="responseArea"></pre>

  <script>
    async function sendMessage() {
      const input = document.getElementById("userInput").value;
      const res = await fetch("/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: input })
      });

      const data = await res.json();
      document.getElementById("responseArea").textContent = data.reply;
    }
  </script>
</body>
</html>

✅ 실행 방법

  1. 의존성 설치:
  2. npm install express openai dotenv
  3. 서버 실행:
  4. node server.js
  5. 브라우저에서 접속: http://localhost:3000

🛡️ 보안 주의

API 키는 절대 프론트엔드에 넣으면 안 됩니다! 백엔드에서만 요청해야 안전해요.

 

728x90