본문 바로가기

AI

[ 개발 환경 구축 가이드]CodeLlama 기반 독립형 AI 코딩 어시스턴스 어플라이언스

반응형

개발 환경 구축 가이드

 

Windows 11 환경에서 AI 기반 코드 생성 어시스턴트를 로컬 PC (RTX4080)에 구축하고, 이후 별도의 Windows PC로 이전하여 운영할 수 있는 독립형 어플라이언스

 

Windows 11 + RTX4080 기반  
AI 코딩 어시스턴트 개발 환경 구축 가이드

프로젝트 명
CodeLlama 기반 독립형 AI 코딩 어시스턴스 어플라이언스


주요 요구사항
| 항목 | 내용 |
|------|------|
| OS | Windows 11 Pro 이상 |
| GPU | NVIDIA RTX 30xx / 40xx 시리즈 |
| AI 모델 | Meta Code Llama (70B GGUF 형식 추천) |
| 언어 지원 | React, TypeScript, Java, Python, MariaDB SQL |
| 배포 방식 | Docker 없이 독립 실행형 패키지 가능 (Electron + Python API 서버) |
| 보안 | 인증/권한 관리 포함, 클라우드 의존 없음 |
| 사용 목적 | 기업 내부 정책 반영 및 업무 지침 적용 가능 |

---

## 📁 최종 디렉토리 구조 예시

```text
/code-assistant-appliance/
├── backend/                  # FastAPI 기반 API 서버
│   ├── main.py               # 메인 서버 파일
│   └── requirements.txt      # Python 패키지 목록
├── models/                   # AI 모델 (예: codellama-70b-instruct.Q4_K_M.gguf)
├── frontend/                 # React UI (빌드된 정적 파일 포함)
│   └── build/
├── venv/                     # Python 가상 환경 (패키징 시 포함)
├── db/                       # MariaDB 설치 스크립트 또는 SQLite 활용
├── electron-main.js          # Electron 앱 메인 파일
├── package.json              # Electron 설정
└── README.md
```

---

## 🛠️ 단계별 개발 환경 구축 가이드

---

## 1. 📦 기본 도구 설치

### 1.1 Python 설치

🔗 다운로드: [https://www.python.org/downloads/windows/](https://www.python.org/downloads/windows/) 
(최신 버전 권장, "Add to PATH" 체크 필수)

```powershell
python --version
pip --version
```

---

### 1.2 Node.js 설치

🔗 다운로드: [https://nodejs.org/ko/download/](https://nodejs.org/ko/download/) 
(LTS 버전 권장)

```powershell
node -v
npm -v
```

---

## 2. 🤖 AI 모델 준비 (Code Llama GGUF)

### 2.1 GGUF 형식 모델 다운로드

- 추천 모델:
  - `codellama-70b-instruct.Q4_K_M.gguf` (VRAM 24GB 필요)
  - `openchat-3.5-13b.Q4_K_M.gguf` (가벼움)

🔗 HuggingFace CLI 설치:

```powershell
pip install huggingface-cli
```

🔗 GGUF 모델 다운로드 예시:

```powershell
huggingface-cli download TheBloke/CodeLlama-70B-Instruct-GGUF --filename "codellama-70b-instruct.Q4_K_M.gguf"
```

> 다운로드 경로: `/code-assistant-appliance/models/codellama-70b-instruct.Q4_K_M.gguf`

---

### 2.2 llama.cpp 설치 및 실행

#### 방법 1: 이미 빌드된 바이너리 사용

🔗 공식 GitHub Releases:  
[https://github.com/ggerganov/llama.cpp/releases](https://github.com/ggerganov/llama.cpp/releases)

- `llama-cpp-server.exe` 다운로드 후 적절한 폴더에 저장

#### 방법 2: 직접 빌드 (선택적)

```powershell
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp
mkdir build && cd build
cmake .. -DLLAMA_CUBLAS=on
cmake --build . --config Release
```

#### 서버 실행 (GPU 사용)

```powershell
llama-cpp-server.exe -m ../models/codellama-70b-instruct.Q4_K_M.gguf -ngl 9999
```

> `-ngl 9999`: 전체 모델을 GPU에 로드 (VRAM 여유 있을 경우)

---

## 3. 🌐 FastAPI 기반 백엔드 서버 구성

### 3.1 디렉토리 구조

```text
/code-assistant-appliance/backend/
├── main.py
└── requirements.txt
```

### 3.2 `requirements.txt`

```
fastapi>=0.95.0
uvicorn>=0.21.1
httpx>=0.24.0
```

### 3.3 `main.py` 예시

```python
from fastapi import FastAPI
import httpx

app = FastAPI()

LLM_SERVER_URL = "http://localhost:8080/completion"

@app.post("/generate")
async def generate_code(prompt: str):
    async with httpx.AsyncClient() as client:
        response = await client.post(LLM_SERVER_URL, json={
            "prompt": prompt,
            "temperature": 0.2,
            "max_tokens": 200
        })
        return response.json()
```

---

## 4. 🖼️ React 기반 프론트엔드 구성

### 4.1 Create React App 생성

```powershell
npx create-react-app code-assistant-ui
cd code-assistant-ui
npm install axios monaco-editor
```

### 4.2 간단한 코드 에디터 UI 예시 (`App.js`)

```jsx
import React, { useState } from 'react';
import axios from 'axios';
import Editor from '@monaco-editor/react';

function App() {
  const [prompt, setPrompt] = useState('');
  const [code, setCode] = useState('');

  const handleGenerate = async () => {
    const res = await axios.post('http://localhost:8000/generate', { prompt });
    setCode(res.data.content);
  };

  return (
    <div style={{ padding: 20 }}>
      <h2>AI Code Generator</h2>
      <textarea value={prompt} onChange={(e) => setPrompt(e.target.value)} />
      <button onClick={handleGenerate}>Generate Code</button>
      <Editor height="500px" defaultLanguage="python" value={code} />
    </div>
  );
}

export default App;
```

### 4.3 빌드 실행

```powershell
npm run build
```

> 결과물: `/code-assistant-ui/build/`

---

## 5. 🚀 Electron 기반 앱으로 통합

### 5.1 `package.json` 작성

```json
{
  "name": "code-assistant-electron",
  "version": "1.0.0",
  "main": "electron-main.js",
  "scripts": {
    "start": "electron .",
    "build": "electron-packager . --platform=win32 --arch=x64 --out dist"
  },
  "dependencies": {
    "electron-is-dev": "^2.0.0"
  },
  "devDependencies": {
    "electron": "^25.0.0",
    "electron-packager": "^17.1.1"
  }
}
```

### 5.2 `electron-main.js` 작성

```javascript
const { app, BrowserWindow } = require('electron');
const path = require('path');
const express = require('child_process').exec;
let apiProcess;

function createWindow() {
  const win = new BrowserWindow({
    width: 1000,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

  if (require('electron-is-dev')) {
    win.loadURL('http://localhost:3000'); // 개발 서버
  } else {
    win.loadFile(path.join(__dirname, 'frontend', 'build', 'index.html'));
  }
}

function startAPIServer() {
  const pythonPath = path.join(__dirname, 'venv', 'Scripts', 'python.exe');
  const apiScript = path.join(__dirname, 'backend', 'main.py');

  apiProcess = express(`"${pythonPath}" "${apiScript}"`, (error, stdout, stderr) => {
    if (error) console.error(`실행 오류: ${error.message}`);
    if (stderr) console.error(`stderr: ${stderr}`);
    if (stdout) console.log(`stdout: ${stdout}`);
  });

  apiProcess.on('close', (code) => {
    console.log(`서버 종료됨: ${code}`);
  });
}

app.whenReady().then(() => {
  startAPIServer();
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
    if (apiProcess) apiProcess.kill();
  }
});
```

---

## 6. 🧪 개발 환경 테스트

### 6.1 AI 서버 실행

```powershell
cd models
llama-cpp-server.exe -m codellama-70b-instruct.Q4_K_M.gguf -ngl 9999
```

### 6.2 FastAPI 서버 실행

```powershell
cd backend
..\venv\Scripts\python.exe -m uvicorn main:app --host 0.0.0.0 --port 8000
```

### 6.3 Electron 앱 실행

```powershell
npm start
```

---

## 7. 📦 독립형 어플라이언스 패키징

### 7.1 Python venv 생성 및 포함

```powershell
python -m venv venv
.\venv\Scripts\pip install -r backend\requirements.txt
```

### 7.2 Electron 앱 빌드

```powershell
npm run build
```

> 결과물: `dist/code-assistant-electron-win32-x64/`

---

## 8. 🔄 별도 Windows PC로 이전

1. `dist/code-assistant-electron-win32-x64/` 폴더 전체를 다른 PC에 복사
2. `.exe` 파일 더블클릭 실행
3. 자동으로 Python 서버와 AI 모델이 시작됨

---

## 9. 🗃️ MariaDB 연동 옵션

- MariaDB 설치: [https://mariadb.org/download/](https://mariadb.org/download/)
- Python DB 연결: SQLAlchemy 사용
- 샘플 코드 추가 가능 (원하신다면 제공)

---

## 📎 첨부: 다음 단계 제안

📌 원하신다면 아래 문서나 샘플을 함께 제공해 드릴 수 있습니다:

- [ ] PDF 형태의 개발자용 설치 및 사용자 가이드
- [ ] Inno Setup 기반 설치 프로그램 샘플
- [ ] MariaDB 연동 샘플 코드
- [ ] 전체 GitHub 샘플 리포지토리 구조
- [ ] PowerShell 기반 설치 스크립트

요약

| 항목 | 내용 |
|------|------|
| 개발 환경 | Windows 11 + RTX4080 |
| AI 모델 | Code Llama (GGUF 형식) |
| 기술 스택 | Python + FastAPI + React + Electron |
| 배포 방식 | Docker 없이 독립 실행형 .exe 패키지 |
| 데이터베이스 | MariaDB 연동 가능 |
| 보안 | JWT, RBAC 등 확장 가능성 있음 |





감사합니다 😊

반응형