# ChatGPT 플러그인 개발 입문

안녕하세요! 오늘은 **ChatGPT 플러그인**을 개발해서 ChatGPT를 확장하는 방법을 알아봅니다! 🔌
## ChatGPT 플러그인이란?
플러그인은 ChatGPT가 외부 API와 상호작용할 수 있게 해주는 확장 기능입니다.
**예시:**
– 웹 검색
– 이메일 전송
– 데이터베이스 쿼리
– 캘린더 일정 관리
—
## 1. 플러그인 구조
“`
┌─────────────────┐
│ ChatGPT UI │
└────────┬────────┘
│
[API 요청]
↓
┌─────────────────┐
│ 플러그인 API │ ← FastAPI/Express
└────────┬────────┘
│
[데이터 접근]
↓
┌─────────────────┐
│ 외부 서비스 │ ← 데이터베이스/API
└─────────────────┘
“`
—
## 2. 프로젝트 시작
“`bash
mkdir chatgpt-plugin
cd chatgpt-plugin
npm init -y
npm install express cors dotenv
“`
—
## 3. manifest.json 생성
“`json
{
“schema_version”: “v1”,
“name_for_human”: “내 플러그인”,
“name_for_model”: “my_plugin”,
“description_for_human”: “ChatGPT 확장용 플러그인”,
“description_for_model”: “이 플러그인을 사용해서 외부 데이터에 접근합니다.”,
“auth”: {
“type”: “none”
},
“api”: {
“type”: “openapi”,
“url”: “http://localhost:3000/openapi.yaml”
},
“contact_email”: “contact@example.com”,
“legal_info_url”: “https://example.com/legal”
}
“`
—
## 4. OpenAPI 스펙
“`yaml
openapi: 3.0.0
info:
title: My Plugin API
version: 1.0.0
servers:
– url: http://localhost:3000
paths:
/api/products:
get:
operationId: getProducts
summary: 제품 목록 조회
parameters:
– name: category
in: query
description: 카테고리
schema:
type: string
responses:
‘200’:
description: 성공
content:
application/json:
schema:
type: array
items:
$ref: ‘#/components/schemas/Product’
components:
schemas:
Product:
type: object
properties:
id:
type: string
name:
type: string
price:
type: number
category:
type: string
“`
—
## 5. 백엔드 구현
### Express 서버
“`javascript
const express = require(‘express’);
const cors = require(‘cors’);
require(‘dotenv’).config();
const app = express();
app.use(cors());
app.use(express.json());
// 제품 데이터
const products = [
{ id: ‘1’, name: ‘노트북’, price: 1000000, category: ‘전자제품’ },
{ id: ‘2’, name: ‘의자’, price: 150000, category: ‘가구’ },
{ id: ‘3’, name: ‘책상’, price: 200000, category: ‘가구’ },
];
// GET /api/products
app.get(‘/api/products’, (req, res) => {
const { category } = req.query;
let result = products;
if (category) {
result = products.filter(p => p.category === category);
}
res.json(result);
});
// GET /api/products/:id
app.get(‘/api/products/:id’, (req, res) => {
const product = products.find(p => p.id === req.params.id);
if (!product) {
return res.status(404).json({ error: ‘제품을 찾을 수 없습니다’ });
}
res.json(product);
});
// OpenAPI 스펙
app.get(‘/openapi.yaml’, (req, res) => {
res.sendFile(__dirname + ‘/openapi.yaml’);
});
// manifest.json
app.get(‘/.well-known/ai-plugin.json’, (req, res) => {
res.sendFile(__dirname + ‘/manifest.json’);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
“`
—
## 6. 데이터베이스 연결
### MongoDB 사용
“`javascript
const mongoose = require(‘mongoose’);
mongoose.connect(process.env.MONGODB_URI);
const productSchema = new mongoose.Schema({
name: String,
price: Number,
category: String,
});
const Product = mongoose.model(‘Product’, productSchema);
app.get(‘/api/products’, async (req, res) => {
const { category } = req.query;
const query = category ? { category } : {};
const products = await Product.find(query);
res.json(products);
});
“`
—
## 7. 인증 구현
### API Key 인증
“`javascript
const auth = (req, res, next) => {
const apiKey = req.headers[‘x-api-key’];
if (apiKey !== process.env.PLUGIN_API_KEY) {
return res.status(401).json({ error: ‘인증 실패’ });
}
next();
};
app.get(‘/api/protected’, auth, (req, res) => {
res.json({ message: ‘인증 성공’ });
});
“`
—
## 8. 플러그인 등록
1. ChatGPT 열기
2. Settings → Beta features
3. Plugins 활성화
4. Plugin Store → Develop your own plugin
5. 로컬 플러그인 URL 입력
– `http://localhost:3000`
—
## 9. 테스트
### ChatGPT에서 테스트
“`
User: 가구 카테고리의 제품을 보여줘
ChatGPT: 가구 카테고리 제품 목록을 찾아보겠습니다.
[플러그인 호출]
GET /api/products?category=가구
ChatGPT: 가구 카테고리에는 다음 제품들이 있습니다:
– 의자: 150,000원
– 책상: 200,000원
“`
—
## 10. 고급 기능
### 스트리밍 응답
“`javascript
app.get(‘/api/stream’, (req, res) => {
res.setHeader(‘Content-Type’, ‘text/event-stream’);
const data = [‘데이터1’, ‘데이터2’, ‘데이터3’];
data.forEach((item, index) => {
setTimeout(() => {
res.write(`data: ${item}\n\n`);
}, index * 1000);
});
setTimeout(() => {
res.end();
}, data.length * 1000);
});
“`
### 파일 업로드
“`javascript
const multer = require(‘multer’);
const upload = multer({ dest: ‘uploads/’ });
app.post(‘/api/upload’, upload.single(‘file’), (req, res) => {
const file = req.file;
// 파일 처리
const result = processFile(file);
res.json({
filename: file.originalname,
url: `/uploads/${file.filename}`,
…result
});
});
“`
—
## 11. 배포
### Vercel 배포
“`bash
# vercel.json
{
“version”: 2,
“builds”: [
{
“src”: “index.js”,
“use”: “@vercel/node”
}
]
}
# 배포
vercel
“`
### Railway 배포
“`bash
railway up
“`
—
## 12. 모니터링
### 로깅
“`javascript
const morgan = require(‘morgan’);
app.use(morgan(‘combined’));
“`
### 에러 처리
“`javascript
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: ‘서버 오류’ });
});
“`
—
## 결론
ChatGPT 플러그인은 AI를 실제 세계와 연결하는 강력한 방법입니다!
**핵심 포인트:**
– ✅ 명확한 OpenAPI 스펙
– ✅ 안전한 인증
– ✅ 오류 처리
– ✅ 효율적인 API 설계
—
## 다음 단계
– 🌐 실제 배포
– 🔐 강력한 인증
– 📊 사용량 분석
## 참고 자료
– [OpenAI Plugin Docs](https://platform.openai.com/docs/plugins/introduction)
– [OpenAPI Spec](https://swagger.io/specification/)
– [ChatGPT Plugin Examples](https://github.com/openai/plugins-quickstart)
—
질문이 있나요? 댓글로 남겨주세요! 😊
**다음 포스팅:** 최신 LLM 이슈: Multimodal 모델 소개