터미널 AI 에이전트 구축 (v2)
개발자들이 직접 제어하고 최적화할 수 있는 터미널 기반 AI 에이전트를 구축하는 실전 가이드입니다. 이 가이드는 로컬 LLM을 활용한 실시간 코드 지원 터미널 에이전트를 구축하는 데 필요한 모든 요소를 제공합니다.
1. CLI AI 에이전트 생태계
현재 터미널 AI 에이전트는 다음과 같은 주요 플랫폼으로 분류됩니다:
Aider
가장 유명한 오픈소스 터미널 에이전트입니다. VSCode, Neovim, Emacs 등과 통합 가능하며, Python으로 구현되어 있습니다.
# Aider 설치
pip install aider
# 기존 프로젝트에 적용
aider --help
# 실시간 코딩 모드
aider --chat-mode
Continue.dev
IDE 기반의 AI 에이전트로, 터미널에서도 작동 가능합니다. 빠른 코드 생성 기능을 제공합니다.
OpenCode
커뮤니티 중심의 오픈소스 에이전트로, 커스터마이징이 용이합니다.
2. 로컬 LLM API 엔드포인트 설정
로컬 LLM을 활용하기 위해 Ollama를 사용하여 API 엔드포인트를 구축합니다.
# Ollama 설치 (Ubuntu/Debian)
curl -fsSL https://ollama.com/install.sh | sh
# Ollama 시작
ollama serve
# 모델 다운로드
ollama pull llama3
# API 서버 확인
curl http://localhost:11434/api/tags
3. 간단한 Python CLI 에이전트 구축
다음은 함수 호출 기능을 포함한 간단한 CLI 에이전트입니다:
#!/usr/bin/env python3
# terminal_agent.py
import os
import json
import subprocess
from openai import OpenAI
import argparse
class TerminalAgent:
def __init__(self, model="llama3"):
# 로컬 API 엔드포인트 설정
self.client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="ollama"
)
self.model = model
def call_function(self, function_name, arguments):
"""함수 호출"""
if function_name == "execute_shell":
return self.execute_shell(arguments["command"])
elif function_name == "read_file":
return self.read_file(arguments["path"])
elif function_name == "write_file":
return self.write_file(arguments["path"], arguments["content"])
elif function_name == "git_status":
return self.git_status()
else:
return f"Unknown function: {function_name}"
def execute_shell(self, command):
"""쉘 명령어 실행"""
try:
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True
)
return result.stdout + result.stderr
except Exception as e:
return f"Error: {str(e)}"
def read_file(self, path):
"""파일 읽기"""
try:
with open(path, 'r') as f:
return f.read()
except Exception as e:
return f"Error reading {path}: {str(e)}"
def write_file(self, path, content):
"""파일 쓰기"""
try:
with open(path, 'w') as f:
f.write(content)
return f"File written: {path}"
except Exception as e:
return f"Error writing {path}: {str(e)}"
def git_status(self):
"""Git 상태 확인"""
return self.execute_shell("git status --porcelain")
def chat(self, prompt):
"""채팅 함수"""
response = self.client.chat.completions.create(
model=self.model,
messages=[
{
"role": "system",
"content": """
당신은 터미널 기반 AI 에이전트입니다. 다음 함수들을 호출하여 작업을 수행할 수 있습니다:
- execute_shell(command): 쉘 명령어 실행
- read_file(path): 파일 내용 읽기
- write_file(path, content): 파일 쓰기
- git_status(): Git 상태 확인
"""
},
{
"role": "user",
"content": prompt
}
],
functions=[
{
"name": "execute_shell",
"description": "쉘 명령어 실행",
"parameters": {
"type": "object",
"properties": {
"command": {"type": "string"}
},
"required": ["command"]
}
},
{
"name": "read_file",
"description": "파일 내용 읽기",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string"}
},
"required": ["path"]
}
},
{
"name": "write_file",
"description": "파일 쓰기",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string"},
"content": {"type": "string"}
},
"required": ["path", "content"]
}
},
{
"name": "git_status",
"description": "Git 상태 확인",
"parameters": {
"type": "object"
}
}
],
function_call="auto"
)
return response.choices[0].message
# 메인 실행 함수
def main():
parser = argparse.ArgumentParser(description="터미널 AI 에이전트")
parser.add_argument("prompt", help="AI에게 질문할 내용")
parser.add_argument("--model", default="llama3", help="사용할 모델")
args = parser.parse_args()
agent = TerminalAgent(args.model)
response = agent.chat(args.prompt)
if response.function_call:
# 함수 호출 실행
function_name = response.function_call.name
arguments = json.loads(response.function_call.arguments)
result = agent.call_function(function_name, arguments)
print(result)
else:
# 텍스트 응답 출력
print(response.content)
if __name__ == "__main__":
main()
실행 방법:
python terminal_agent.py "프로젝트 디렉토리의 모든 .py 파일을 찾아주세요"
python terminal_agent.py "README.md 파일을 읽어주세요"
python terminal_agent.py "git status를 확인해주세요"
4. tmux와 통합
터미널 에이전트를 tmux 세션과 통합하여 편리하게 사용:
# tmux 세션 생성
tmux new-session -s ai-agent -d
# 세션 내에서 에이전트 실행
tmux send-keys -t ai-agent "python3 terminal_agent.py" Enter
# 세션 연결
tmux attach -t ai-agent
5. 커스텀 도구 개발
코드 검색 도구
# code_search.py
import os
import re
def search_code(pattern, directory=".", file_extensions=None):
"""코드 검색 도구"""
if file_extensions is None:
file_extensions = [".py", ".js", ".ts", ".java", ".cpp", ".h"]
results = []
for root, dirs, files in os.walk(directory):
for file in files:
if any(file.endswith(ext) for ext in file_extensions):
file_path = os.path.join(root, file)
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
if re.search(pattern, content):
results.append({
"file": file_path,
"line_count": len(content.split('\n'))
})
except Exception as e:
continue
return results
Git 도구
# git_tools.py
import subprocess
def git_branch_diff(branch_name="main"):
"""브랜치 차이 비교"""
try:
result = subprocess.run([
"git", "diff", f"origin/{branch_name}", "HEAD"
], capture_output=True, text=True)
return result.stdout
except Exception as e:
return f"Error: {str(e)}"
def git_recent_commits(count=5):
"""최근 커밋 목록"""
try:
result = subprocess.run([
"git", "log", f"--oneline", f"-{count}"
], capture_output=True, text=True)
return result.stdout
except Exception as e:
return f"Error: {str(e)}"
6. 컨텍스트 윈도우 관리
대규모 코드베이스를 처리하기 위해 컨텍스트 윈도우 크기를 조절:
python
# context_manager.py
class ContextManager:
def __init__(self, max_tokens=4096):
self.max_tokens = max_tokens
self.context =
---
📥 **Get the full guide on Gumroad**: https://gumroad.com/l/auto ($5)
Top comments (0)