惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
量子位
阮一峰的网络日志
阮一峰的网络日志
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
美团技术团队
J
Java Code Geeks
Apple Machine Learning Research
Apple Machine Learning Research
腾讯CDC
V
Visual Studio Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 三生石上(FineUI控件)
IT之家
IT之家
博客园 - 【当耐特】
L
LangChain Blog
A
About on SuperTechFans
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
N
Netflix TechBlog - Medium
博客园_首页
WordPress大学
WordPress大学
博客园 - Franky
Engineering at Meta
Engineering at Meta
C
Check Point Blog
aimingoo的专栏
aimingoo的专栏
M
MIT News - Artificial intelligence

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
터미널 AI 에이전트 구축 (v20)
matias yoon · 2026-05-25 · via DEV Community

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

1. CLI AI 에이전트 생태계

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

Aider

# 설치
pip install aider
# 사용 예시
aider --model gpt-4 --yes

Continue.dev

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

오픈소스 도구

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

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

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

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

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

# 모델 다운로드
ollama pull llama3

# API 서버 실행
ollama serve &

# 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)

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()

사용법:

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

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

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

# 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

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']}")

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}")

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)

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")

메모리 최적화


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)