터미널 AI 에이전트 구축 (v4)
개발자를 위한 경량 로컬 AI 코딩 어시스턴트 구축 가이드
1. CLI AI 에이전트 생태계 개요
터미널 기반 AI 에이전트는 개발자들이 코드를 작성하고 디버깅할 때 실시간으로 도움을 받을 수 있도록 해주는 도구입니다. 현재 주류로는 다음과 같은 솔루션들이 있습니다:
Aider
# 설치
pip install aider
# 사용 예시
aider --model gpt-4 --yes
Continue.dev
# VSCode 확장 설치
# 설치 후 터미널에서 실행
continue
OpenCode
# GitHub에서 클론
git clone https://github.com/opencode/opencode.git
cd opencode
npm install
커스텀 스크립트
가장 유연한 접근 방식으로, 직접 만들 수 있는 도구는 다음처럼 구성할 수 있습니다:
# aider-like 기능을 가진 간단한 에이전트
import subprocess
import json
class TerminalAgent:
def __init__(self):
self.model = "llama3:8b"
def query(self, prompt):
# 로컬 LLM 호출
result = subprocess.run([
"ollama", "run", self.model, prompt
], capture_output=True, text=True)
return result.stdout
2. 로컬 LLM API 엔드포인트 설정
로컬 모델을 터미널에서 사용하기 위해 Ollama를 사용해 API 엔드포인트를 설정합니다:
# Ollama 설치
curl -fsSL https://ollama.com/install.sh | sh
# 모델 다운로드
ollama pull llama3:8b
# API 엔드포인트 시작 (기본 포트 11434)
ollama serve &
API 엔드포인트를 통해 다음과 같은 방식으로 호출할 수 있습니다:
import requests
import json
def call_local_llm(prompt):
response = requests.post(
'http://localhost:11434/api/generate',
json={
'model': 'llama3:8b',
'prompt': prompt,
'stream': False
}
)
return response.json()['response']
# 사용 예시
result = call_local_llm("Python에서 파일을 읽는 코드를 작성해주세요")
print(result)
3. 함수 호출 기능을 가진 간단한 Python CLI 에이전트
다음은 간단한 Python 기반 CLI 에이전트입니다. 이 에이전트는 코드를 생성하고 실행하며, 함수 호출 기능을 포함합니다:
#!/usr/bin/env python3
import subprocess
import sys
import requests
import json
import os
class LocalAIAgent:
def __init__(self, model="llama3:8b"):
self.model = model
self.base_url = "http://localhost:11434"
def execute_command(self, command):
"""터미널 명령 실행"""
try:
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=30
)
return result.stdout, result.stderr
except subprocess.TimeoutExpired:
return "", "Command timed out"
def generate_code(self, instruction, context=""):
"""LLM을 통한 코드 생성"""
prompt = f"""
You are a senior Python developer.
Context: {context}
Instruction: {instruction}
Provide only the code, no explanations.
"""
response = requests.post(
f'{self.base_url}/api/generate',
json={
'model': self.model,
'prompt': prompt,
'stream': False
}
)
if response.status_code == 200:
return response.json()['response']
return ""
def save_and_run(self, code, filename):
"""코드 저장 및 실행"""
with open(filename, 'w') as f:
f.write(code)
# 실행
stdout, stderr = self.execute_command(f'python {filename}')
return stdout, stderr
# 사용 예시
if __name__ == "__main__":
agent = LocalAIAgent()
# 코드 생성
code = agent.generate_code(
"Create a Python function that calculates Fibonacci numbers with memoization"
)
print("Generated code:")
print(code)
# 저장 및 실행
stdout, stderr = agent.save_and_run(code, "fibonacci.py")
print("Output:", stdout)
4. tmux/터미널 멀티플렉서 통합
tmux를 활용하여 에이전트를 터미널 세션에 통합할 수 있습니다:
# tmux 설치
sudo apt install tmux # Ubuntu/Debian
brew install tmux # macOS
# 새로운 세션 생성
tmux new-session -s ai-agent -d
# 세션에 명령 실행
tmux send-keys -t ai-agent "python3 agent.py" Enter
# 세션 접속
tmux attach -t ai-agent
다음은 tmux 통합을 위한 Python 스크립트입니다:
import subprocess
import os
class TmuxIntegrator:
def __init__(self, session_name="ai-agent"):
self.session_name = session_name
def create_session(self):
"""tmux 세션 생성"""
subprocess.run([
"tmux", "new-session", "-s", self.session_name, "-d"
])
def run_command_in_session(self, command):
"""세션 내에서 명령 실행"""
subprocess.run([
"tmux", "send-keys", "-t", self.session_name, command, "Enter"
])
def attach_session(self):
"""세션 접속"""
subprocess.run(["tmux", "attach", "-t", self.session_name])
# 사용 예시
integrator = TmuxIntegrator()
integrator.create_session()
integrator.run_command_in_session("python3 agent.py")
5. 커스텀 도구 개발
다음은 코드 검색, Git 통합, 파일 조작을 위한 커스텀 도구들입니다:
코드 검색 도구
import subprocess
import os
class CodeSearchTool:
def __init__(self, project_root="."):
self.project_root = project_root
def search_in_files(self, pattern, file_extensions=None):
"""파일 내에서 패턴 검색"""
if file_extensions:
extensions = " ".join([f"-name '*.{ext}'" for ext in file_extensions])
cmd = f"find {self.project_root} -type f {extensions} -exec grep -l '{pattern}' {{}} \\;"
else:
cmd = f"find {self.project_root} -type f -exec grep -l '{pattern}' {{}} \\;"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return result.stdout.strip().split('\n') if result.stdout else []
# 사용 예시
searcher = CodeSearchTool()
results = searcher.search_in_files("def main", ["py", "js"])
print("Found files:", results)
Git 통합 도구
class GitTool:
def __init__(self):
self.repo_path = "."
def get_git_status(self):
"""Git 상태 확인"""
result = subprocess.run(
["git", "status", "--porcelain"],
capture_output=True, text=True
)
return result.stdout.strip().split('\n') if result.stdout else []
def create_branch(self, branch_name):
"""브랜치 생성"""
subprocess.run(["git", "checkout", "-b", branch_name])
def commit_changes(self, message):
"""변경사항 커밋"""
subprocess.run(["git", "add", "."])
subprocess.run(["git", "commit", "-m", message])
# 사용 예시
git_tool = GitTool()
status = git_tool.get_git_status()
print("Git status:", status)
파일 조작 도구
python
import os
import shutil
from pathlib import Path
class FileTool:
def create_directory(self, path):
"""디렉토리 생성"""
os.makedirs(path, exist_ok=True)
def copy_file(self, src, dst):
"""파일 복사"""
shutil.copy2(src, dst)
def delete_file(self, path):
"""파일 삭제"""
if os.path.exists(path):
os.remove(path)
def read_file(self, path):
"""파일 읽기"""
with open(path, 'r') as f:
return f.read()
def write_file(self, path, content):
"""파일 쓰기"""
with open(path, 'w') as f:
f.write(content)
# 사용 예시
file_tool = FileTool()
file_tool.write_file("test.txt", "Hello, World!")
content = file_tool.read_file("test.txt")
print("
---
📥 **Get the full guide on Gumroad**: https://gumroad.com/l/auto ($5)
Top comments (0)