DEV Community

matias yoon
matias yoon

Posted on

터미널 AI 에이전트 구축 (v20)

터미널 AI 에이전트 구축 (v20)

1. CLI AI 에이전트 생태계

터미널에서 작동하는 AI 에이전트는 최근 두드러진 트렌드입니다. 주요 플랫폼들:

Aider

# 설치
pip install aider
# 사용 예시
aider --model gpt-4 --yes
Enter fullscreen mode Exit fullscreen mode

Continue.dev

# VSCode 확장 설치
# 또는 CLI 모드로 사용
continue serve
Enter fullscreen mode Exit fullscreen mode

오픈소스 도구

# OpenCode (기본 기능)
opencode --help

# 커스텀 스크립트
./my-ai-agent.py --prompt "Write a Python function to sort an array"
Enter fullscreen mode Exit fullscreen mode

2. 로컬 LLM API 엔드포인트 설정

로컬 모델을 터미널에서 사용하기 위해 API 서버를 설정합니다:

# Ollama 설치 (가장 간단한 방법)
curl -fsSL https://ollama.com/install.sh | sh

# 모델 다운로드
ollama pull llama3

# API 서버 실행
ollama serve &
Enter fullscreen mode Exit fullscreen mode
# local-llm-api.py - 로컬 API 서버
from flask import Flask, request, jsonify
import ollama

app = Flask(__name__)

@app.route('/generate', methods=['POST'])
def generate():
    data = request.json
    prompt = data.get('prompt', '')

    response = ollama.generate(model='llama3', prompt=prompt)
    return jsonify({
        'response': response['response']
    })

if __name__ == '__main__':
    app.run(host='localhost', port=11434)
Enter fullscreen mode Exit fullscreen mode

3. 간단한 Python CLI 에이전트 구축

# ai-agent.py
import openai
import argparse
import os
import json

class TerminalAI:
    def __init__(self):
        self.client = openai.OpenAI(
            base_url="http://localhost:11434/v1",
            api_key="ollama"
        )

    def generate(self, prompt, max_tokens=1000):
        response = self.client.chat.completions.create(
            model="llama3",
            messages=[{"role": "user", "content": prompt}],
            max_tokens=max_tokens
        )
        return response.choices[0].message.content

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--prompt", "-p", required=True)
    parser.add_argument("--file", "-f", help="파일 경로")

    args = parser.parse_args()

    agent = TerminalAI()

    if args.file:
        with open(args.file, 'r') as f:
            content = f.read()
        prompt = f"{args.prompt}\n\nCode:\n{content}"
    else:
        prompt = args.prompt

    result = agent.generate(prompt)
    print(result)

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

사용법:

# 기본 사용
python ai-agent.py --prompt "Write a Python class for user authentication"

# 파일 기반
python ai-agent.py --prompt "Explain this code" --file main.py
Enter fullscreen mode Exit fullscreen mode

4. tmux와 통합

터미널 분할에서 AI 도움을 받기 위해 tmux와 통합:

# tmux 세션 생성
tmux new-session -s ai-agent -d
# 새로운 윈도우 생성
tmux new-window -t ai-agent
# 윈도우 1에 AI 에이전트 실행
tmux send-keys -t ai-agent:1 "python ai-agent.py" Enter
Enter fullscreen mode Exit fullscreen mode
# tmux 스크립트 (tmux-ai.sh)
#!/bin/bash
tmux new-session -s coding-session -d
tmux new-window -t coding-session
tmux new-window -t coding-session
tmux send-keys -t coding-session:0 "vim" Enter
tmux send-keys -t coding-session:1 "python ai-agent.py" Enter
tmux attach -t coding-session
Enter fullscreen mode Exit fullscreen mode

5. 사용자 정의 도구 개발

코드 검색 도구

# code-search.py
import os
import re

class CodeSearcher:
    def __init__(self, project_root):
        self.project_root = project_root

    def find_function(self, func_name):
        results = []
        for root, dirs, files in os.walk(self.project_root):
            for file in files:
                if file.endswith(('.py', '.js', '.ts')):
                    filepath = os.path.join(root, file)
                    with open(filepath, 'r') as f:
                        content = f.read()
                        if func_name in content:
                            # 함수 정의 찾기
                            pattern = rf'def {func_name}\s*\([^)]*\):'
                            matches = re.finditer(pattern, content)
                            for match in matches:
                                line_num = content[:match.start()].count('\n') + 1
                                results.append({
                                    'file': filepath,
                                    'line': line_num,
                                    'context': self._get_context(content, match.start())
                                })
        return results

    def _get_context(self, content, start_pos, context_lines=3):
        lines = content[:start_pos].split('\n')
        start_line = max(0, len(lines) - context_lines)
        end_line = min(len(lines), len(lines) + context_lines)
        return '\n'.join(lines[start_line:end_line])

# 사용 예시
searcher = CodeSearcher('.')
results = searcher.find_function('calculate_sum')
for result in results:
    print(f"Found in {result['file']} line {result['line']}")
Enter fullscreen mode Exit fullscreen mode

Git 통합 도구

# git-helper.py
import subprocess
import json

class GitHelper:
    @staticmethod
    def get_last_commits(n=5):
        cmd = ['git', 'log', '--oneline', f'-{n}']
        result = subprocess.run(cmd, capture_output=True, text=True)
        return result.stdout.strip().split('\n')

    @staticmethod
    def get_diff():
        cmd = ['git', 'diff']
        result = subprocess.run(cmd, capture_output=True, text=True)
        return result.stdout

    @staticmethod
    def get_status():
        cmd = ['git', 'status', '--porcelain']
        result = subprocess.run(cmd, capture_output=True, text=True)
        return result.stdout.strip().split('\n')

# 통합 예시
git_helper = GitHelper()
commits = git_helper.get_last_commits(3)
for commit in commits:
    print(f"Commit: {commit}")
Enter fullscreen mode Exit fullscreen mode

6. 컨텍스트 창 관리

대규모 코드베이스에서 성능 문제를 해결하기 위한 컨텍스트 관리:

# context-manager.py
import os
import hashlib

class ContextManager:
    def __init__(self, max_context_size=20000):
        self.max_context_size = max_context_size
        self.context_cache = {}

    def add_file_context(self, filepath, content):
        # 파일 해시 생성
        file_hash = hashlib.md5(content.encode()).hexdigest()
        self.context_cache[filepath] = {
            'hash': file_hash,
            'content': content,
            'size': len(content)
        }

    def get_context_window(self, files_list):
        total_size = 0
        context_files = []

        for file_path in files_list:
            if file_path in self.context_cache:
                file_info = self.context_cache[file_path]
                if total_size + file_info['size'] <= self.max_context_size:
                    context_files.append({
                        'path': file_path,
                        'content': file_info['content']
                    })
                    total_size += file_info['size']
                else:
                    break
        return context_files

# 사용 예시
context_manager = ContextManager(15000)
files = ['main.py', 'utils.py', 'models.py']
context = context_manager.get_context_window(files)
Enter fullscreen mode Exit fullscreen mode

7. 로컬 vs API 모델 최적화

성능 비교 스크립트

# performance-test.py
import time
import subprocess

def test_local_model():
    start_time = time.time()
    result = subprocess.run([
        'ollama', 'run', 'llama3', 
        'Explain the Fibonacci sequence in simple terms'
    ], capture_output=True, text=True)
    end_time = time.time()
    return end_time - start_time, result.stdout

def test_api_model():
    start_time = time.time()
    # 실제 API 호출 구현
    end_time = time.time()
    return end_time - start_time, "API result"

# 성능 비교
local_time, local_result = test_local_model()
print(f"Local: {local_time:.2f}s")
Enter fullscreen mode Exit fullscreen mode

메모리 최적화


python
# memory-optimized.py
import gc
import psutil

def monitor_memory():
    process = psutil.Process()
    memory_info = process.memory_info()
    return memory_info.rss / 1024 / 1024  # MB

class MemoryEfficientAI:
    def __init__(self):
        self.cache = {}

    def process_with_cleanup(self, prompt):
        #

---

📥 **Get the full guide on Gumroad**: https://gumroad.com/l/auto ($5)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)