터미널 AI 에이전트 구축 (v31)
터미널에서 작동하는 AI 에이전트를 구축하면 코드 작성 속도가 2배 이상 향상됩니다. 이 가이드에서는 실제 개발자가 사용할 수 있는 터미널 AI 에이전트를 구축하는 방법을 단계별로 설명합니다.
1. CLI AI 에이전트 생태계
현재 터미널 AI 에이전트는 다음과 같은 솔루션으로 구성되어 있습니다:
Aider
pip install aider
aider --help
Continue.dev
# 설치
npm install -g continue
OpenCode
# 커스텀 스크립트 예시
python opencode.py --prompt "함수를 생성해주세요"
커스텀 스크립트
# aider-like 커맨드 라인 도구
#!/usr/bin/env python3
import sys
import subprocess
def main():
prompt = " ".join(sys.argv[1:])
# 커스텀 AI API 호출
response = call_ai_api(prompt)
print(response)
if __name__ == "__main__":
main()
2. 로컬 LLM API 엔드포인트 설정
로컬에서 LLM을 실행하여 속도와 보안을 향상시키세요:
LM Studio 설치
# macOS
brew install lm-studio
# 또는 Windows
winget install LMStudio
# Linux
wget https://github.com/LM-SStudio/Local-LLM/releases/latest/download/Local-LLM-linux-x64.tar.gz
tar -xzf Local-LLM-linux-x64.tar.gz
API 서버 시작
# LM Studio에서 API 서버 시작
# 또는 직접 Ollama 사용
ollama serve
# API 엔드포인트 확인
curl http://localhost:11434/api/tags
3. 간단한 Python CLI 에이전트 만들기
#!/usr/bin/env python3
# agent.py
import os
import sys
import json
import requests
from typing import Dict, List, Any
class TerminalAgent:
def __init__(self, api_url="http://localhost:11434/api/generate"):
self.api_url = api_url
self.context = []
def call_api(self, prompt: str, functions: List[Dict] = None) -> str:
payload = {
"model": "llama3",
"prompt": prompt,
"stream": False
}
if functions:
payload["functions"] = functions
try:
response = requests.post(self.api_url, json=payload)
return response.json()["response"]
except Exception as e:
return f"API 오류: {str(e)}"
def create_function_call(self, name: str, description: str, parameters: Dict) -> Dict:
return {
"name": name,
"description": description,
"parameters": parameters
}
def run(self, prompt: str):
result = self.call_api(prompt)
print(result)
return result
# 사용법
if __name__ == "__main__":
agent = TerminalAgent()
prompt = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else "도움말을 제공해주세요"
agent.run(prompt)
4. tmux와 통합
터미널 멀티플렉서를 통한 효율적인 작업 흐름:
# tmux 세션 생성
tmux new-session -d -s ai-agent
# 세션 내에서 에이전트 실행
tmux send-keys -t ai-agent "python agent.py" Enter
# 세션에 연결
tmux attach -t ai-agent
tmux 스크립트
#!/bin/bash
# ai-session.sh
SESSION="ai-dev"
if tmux has-session -t $SESSION 2>/dev/null; then
tmux attach -t $SESSION
else
tmux new-session -d -s $SESSION
tmux send-keys -t $SESSION "cd /path/to/project" Enter
tmux send-keys -t $SESSION "python agent.py" Enter
tmux attach -t $SESSION
fi
5. 사용자 정의 도구 개발
코드 검색 도구
# tools/code_search.py
import os
import subprocess
from typing import List
class CodeSearchTool:
def __init__(self, project_root: str):
self.project_root = project_root
def search_code(self, query: str, file_types: List[str] = None) -> List[str]:
"""코드 검색 도구"""
cmd = ["find", self.project_root, "-type", "f"]
if file_types:
extensions = " -o ".join([f"-name '*.{ext}'" for ext in file_types])
cmd.extend(["-exec", "grep", "-l", query, "{}", ";"])
try:
result = subprocess.run(cmd, capture_output=True, text=True)
return result.stdout.strip().split('\n') if result.stdout.strip() else []
except Exception as e:
return [f"오류: {str(e)}"]
def find_function(self, function_name: str) -> List[str]:
"""함수 정의 찾기"""
cmd = ["grep", "-r", f"def {function_name}", self.project_root]
result = subprocess.run(cmd, capture_output=True, text=True)
return result.stdout.strip().split('\n') if result.stdout.strip() else []
# 사용 예시
search_tool = CodeSearchTool("/home/user/myproject")
results = search_tool.search_code("logger.error")
print(results)
Git 통합 도구
# tools/git_tool.py
import subprocess
import json
class GitTool:
def __init__(self, repo_path: str = "."):
self.repo_path = repo_path
def get_changed_files(self) -> List[str]:
"""변경된 파일 목록 가져오기"""
try:
result = subprocess.run(
["git", "diff", "--name-only", "HEAD~1", "HEAD"],
capture_output=True, text=True, cwd=self.repo_path
)
return result.stdout.strip().split('\n') if result.stdout.strip() else []
except Exception as e:
return [f"오류: {str(e)}"]
def get_staged_files(self) -> List[str]:
"""스테이징된 파일"""
try:
result = subprocess.run(
["git", "diff", "--cached", "--name-only"],
capture_output=True, text=True, cwd=self.repo_path
)
return result.stdout.strip().split('\n') if result.stdout.strip() else []
except Exception as e:
return [f"오류: {str(e)}"]
def commit_message_suggestion(self) -> str:
"""커밋 메시지 제안"""
try:
result = subprocess.run(
["git", "diff", "--cached", "--stat"],
capture_output=True, text=True, cwd=self.repo_path
)
return f"커밋 변경사항: {result.stdout.strip()}"
except Exception as e:
return f"오류: {str(e)}"
파일 작업 도구
# tools/file_operations.py
import os
import shutil
from pathlib import Path
class FileOperations:
@staticmethod
def create_file(path: str, content: str = ""):
"""파일 생성"""
try:
Path(path).parent.mkdir(parents=True, exist_ok=True)
with open(path, 'w') as f:
f.write(content)
return f"파일 생성 완료: {path}"
except Exception as e:
return f"파일 생성 실패: {str(e)}"
@staticmethod
def copy_file(src: str, dst: str):
"""파일 복사"""
try:
shutil.copy2(src, dst)
return f"파일 복사 완료: {src} -> {dst}"
except Exception as e:
return f"파일 복사 실패: {str(e)}"
@staticmethod
def find_files_by_pattern(pattern: str, root: str = ".") -> List[str]:
"""패턴에 맞는 파일 찾기"""
results = []
for path in Path(root).rglob(pattern):
if path.is_file():
results.append(str(path))
return results
6. 컨텍스트 윈도우 관리
대형 코드베이스를 효율적으로 처리하기 위한 컨텍스트 관리:
python
# context_manager.py
import os
import json
from typing import List, Dict
class ContextManager:
def __init__(self, max_tokens: int = 4096):
self.max_tokens = max_tokens
self.context = []
def add_file_context(self, file_path: str, lines: int = 50) -> bool:
"""파일 컨텍스트 추가"""
try:
with open
---
📥 **Get the full guide on Gumroad**: https://gumroad.com/l/auto ($5)
Top comments (0)