터미널 AI 에이전트 구축 (v47)
CLI AI 에이전트 생태계
터미널에서 작동하는 AI 에이전트는 이미 다양한 형태로 존재합니다. 현재 주요 도구는 다음과 같습니다:
Aider: GitHub Copilot과 유사한 기능을 제공하며, 파일 단위로 코드를 생성하고 수정합니다. 주요 특징은 소스 코드가 있는 파일과 현재 작업 디렉토리 기반의 콘텍스트를 사용하는 것입니다.
# Aider 설치
pip install aider
# Aider 실행
aider --help
Continue.dev: VS Code 확장 기반의 AI 에이전트로, 터미널에서도 사용 가능한 커스텀 에이전트를 지원합니다. GitHub Copilot 기반으로 작동하며, 확장 기능을 사용합니다.
OpenCode: OpenAI API와 연동되는 터미널 기반 툴로, 코드 생성 및 리뷰 기능을 제공합니다. 터미널에서 직접 사용할 수 있는 기능을 중심으로 설계되었습니다.
커스텀 스크립트: 직접 구축한 스크립트는 최대한의 사용자 맞춤형 기능을 제공합니다. 예를 들어, 특정 프로젝트 구조에 맞는 코드 생성기를 만들 수 있습니다.
로컬 LLM API 엔드포인트 설정
터미널에서 AI 에이전트를 구축하기 위해 로컬 LLM (Large Language Model) API 서버를 설정하는 것이 중요합니다.
# llama.cpp를 사용한 로컬 LLM 서버 설정
git clone https://github.com/ggerganov/llama.cpp.git
cd llama.cpp
make
# 모델 다운로드 및 변환
wget https://huggingface.co/TheBloke/Mistral-7B-v0.1-GGUF/resolve/main/mistral-7b-v0.1.Q4_K_M.gguf
# 로컬 서버 실행
./server -m mistral-7b-v0.1.Q4_K_M.gguf -c 2048 --host 127.0.0.1 --port 11434
위 명령어는 llama.cpp를 사용하여 로컬에서 LLM 서버를 실행하는 방법입니다. 이 서버는 localhost:11434 포트에서 API를 제공합니다.
간단한 Python CLI 에이전트 구축
다음은 기능 호출(Functions calling)을 포함하는 간단한 Python CLI 에이전트입니다.
#!/usr/bin/env python3
# ai_agent.py
import openai
import json
import subprocess
import sys
from typing import Dict, List, Any
# 로컬 LLM API 설정
openai.api_base = "http://localhost:11434/v1"
openai.api_key = "dummy"
class TerminalAgent:
def __init__(self):
self.tools = {
"run_command": self.run_command,
"read_file": self.read_file,
"write_file": self.write_file,
"search_code": self.search_code
}
def run_command(self, command: str) -> str:
"""명령어 실행"""
try:
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=30
)
return result.stdout + result.stderr
except Exception as e:
return f"Error: {str(e)}"
def read_file(self, filename: str) -> str:
"""파일 읽기"""
try:
with open(filename, 'r') as f:
return f.read()
except Exception as e:
return f"Error reading {filename}: {str(e)}"
def write_file(self, filename: str, content: str) -> str:
"""파일 쓰기"""
try:
with open(filename, 'w') as f:
f.write(content)
return f"Successfully wrote to {filename}"
except Exception as e:
return f"Error writing to {filename}: {str(e)}"
def search_code(self, pattern: str, directory: str = ".") -> str:
"""코드 검색"""
try:
cmd = f"grep -r '{pattern}' {directory}"
result = subprocess.run(
cmd,
shell=True,
capture_output=True,
text=True
)
return result.stdout
except Exception as e:
return f"Error searching code: {str(e)}"
def call_tool(self, tool_name: str, arguments: Dict[str, Any]) -> str:
"""툴 실행"""
if tool_name in self.tools:
return self.tools[tool_name](**arguments)
return f"Unknown tool: {tool_name}"
def chat(self, messages: List[Dict[str, str]], tools: List[Dict[str, Any]] = None) -> str:
"""채팅 메시지 처리"""
if tools:
# 기능 호출을 위한 메시지 생성
response = openai.ChatCompletion.create(
model="mistral",
messages=messages,
functions=tools,
function_call="auto"
)
return response.choices[0].message
else:
# 일반적인 채팅
response = openai.ChatCompletion.create(
model="mistral",
messages=messages
)
return response.choices[0].message.content
def main():
agent = TerminalAgent()
# 예제 메시지
messages = [
{
"role": "system",
"content": "You are a helpful assistant that can execute terminal commands and manipulate files."
},
{
"role": "user",
"content": "Create a new Python file called 'hello.py' that prints 'Hello, World!'"
}
]
# 함수 정의
tools = [
{
"name": "write_file",
"description": "Write content to a file",
"parameters": {
"type": "object",
"properties": {
"filename": {"type": "string"},
"content": {"type": "string"}
},
"required": ["filename", "content"]
}
}
]
result = agent.chat(messages, tools)
print(result)
if __name__ == "__main__":
main()
tmux와의 통합
터미널 멀티플렉서인 tmux와 통합하여 작업 환경을 향상시킬 수 있습니다.
# tmux 세션 생성
tmux new-session -d -s ai_agent
# 세션 내에서 명령 실행
tmux send-keys -t ai_agent "python ai_agent.py" Enter
# 세션에 연결
tmux attach -t ai_agent
다음은 tmux와 통합된 에이전트입니다:
# tmux_integration.py
import subprocess
import json
class TmuxAgent:
def __init__(self, session_name="ai_agent"):
self.session_name = session_name
def create_session(self):
"""tmux 세션 생성"""
subprocess.run(["tmux", "new-session", "-d", "-s", self.session_name])
def send_command(self, command: str):
"""명령어 전송"""
subprocess.run([
"tmux", "send-keys", "-t", self.session_name, command, "Enter"
])
def get_session_info(self):
"""세션 정보 확인"""
result = subprocess.run(
["tmux", "list-sessions", "-F", "#{session_name}: #{session_attached}"],
capture_output=True,
text=True
)
return result.stdout
def run_agent_command(self, command: str, output_file: str = None):
"""에이전트 명령 실행"""
# 명령어를 터미널에서 실행
result = subprocess.run(
["python", "ai_agent.py", command],
capture_output=True,
text=True
)
if output_file:
with open(output_file, 'w') as f:
f.write(result.stdout)
return result.stdout
# 사용 예시
agent = TmuxAgent("my_ai_session")
agent.create_session()
agent.send_command("ls -la")
커스텀 툴 개발
다음은 코드 검색, git 연동, 파일 작업 기능을 포함한 커스텀 툴입니다:
python
# custom_tools.py
import os
import subprocess
import re
class CodeTools:
@staticmethod
def search_git_files(pattern: str, repo_path: str = ".") -> list:
"""Git 저장소 내 파일 검색"""
try:
cmd = ["git", "ls-files"]
result = subprocess.run(cmd, cwd=repo_path, capture_output=True, text=True)
files = result.stdout.strip().split('\n')
matched_files = []
for file in files:
if pattern in file:
matched_files.append(file)
return matched_files
except Exception as e:
return []
@staticmethod
def get_git_diff():
"""Git 변경 사항 확인"""
try:
cmd =
---
📥 **Get the full guide on Gumroad**: https://gumroad.com/l/auto ($5)
Top comments (0)