AI Agents · 강의

대화형 REPL 스타일 에이전트

터미널 에이전트의 입력 반복, 기록, 여러 차례의 대화를 다룹니다.

레슨 2/413개 단계

대화형 REPL 스타일 에이전트은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.

REPL 스타일 에이전트란 무엇인가요?

REPL(읽기-평가-출력 반복문)은 입력을 입력하고 출력을 받은 뒤 계속 진행하는 대화형 터미널 세션입니다. 터미널의 대화형 에이전트는 정확히 이런 방식으로 작동합니다. 사용자가 메시지를 입력하면 에이전트가 응답하고, 사용자가 종료할 때까지 대화가 계속됩니다.

기본 REPL 반복문

가장 단순한 REPL은 while True 반복문으로, input()을 사용해 사용자 입력을 읽고 처리한 다음 결과를 출력합니다. 사용자가 종료 신호를 보낼 때까지 반복문은 계속 실행됩니다.

def run_agent_repl(inputs):
    print('Agent started. Type /exit to quit.')
    conversation_history = []
    for user_input in inputs:
        user_input = user_input.strip()
        if not user_input:
            continue
        if user_input == '/exit':
            print('Goodbye!')
            break
        conversation_history.append({'role': 'user', 'content': user_input})
        agent_reply = f'[Agent reply to: {user_input}]'
        conversation_history.append({'role': 'assistant', 'content': agent_reply})
        print(f'Agent: {agent_reply}')

run_agent_repl(['Hello agent', 'What can you do?', '/exit'])

KeyboardInterrupt를 안전하게 처리하기

사용자가 Ctrl+C를 누르면 Python은 KeyboardInterrupt를 발생시킵니다. 최상위 수준에서 이를 포착하여 스택 추적 대신 친절한 작별 메시지를 출력하십시오.

def run_agent_repl():
    print('Agent ready. Press Ctrl+C to exit.')
    conversation_history = []

    try:
        while True:
            user_input = input('You: ').strip()
            if not user_input:
                continue

            conversation_history.append({'role': 'user', 'content': user_input})
            reply = '[mocked agent response]'
            conversation_history.append({'role': 'assistant', 'content': reply})
            print(f'Agent: {reply}')

    except KeyboardInterrupt:
        print('\nSession ended. Goodbye!')
    except EOFError:
        # Triggered when stdin is closed (piped input ends)
        print('\nEnd of input. Exiting.')

if __name__ == '__main__':
    import builtins
    _demo_inputs = iter(['What agents can you build?', EOFError])
    def _fake_input(prompt=''):
        val = next(_demo_inputs)
        if val is EOFError:
            raise EOFError
        print(prompt + val)
        return val
    builtins.input = _fake_input
    run_agent_repl()

여러 차례 대화 기록 유지하기

에이전트가 대화를 기억하도록 하려면 메시지 목록을 유지하고 각 대화 차례마다 전체 기록을 LLM에 전달하십시오. 에이전트의 페르소나를 설정하는 시스템 메시지로 시작하십시오.

import openai

client = openai.OpenAI(api_key='YOUR_API_KEY')

def run_chat_repl():
    history = [
        {'role': 'system', 'content': 'You are a helpful AI assistant.'}
    ]

    print('Chat started. Type /exit to quit.')

    try:
        while True:
            user_input = input('You: ').strip()
            if not user_input or user_input == '/exit':
                break

            history.append({'role': 'user', 'content': user_input})

            response = client.chat.completions.create(
                model='gpt-4o-mini',
                messages=history
            )

            reply = response.choices[0].message.content
            history.append({'role': 'assistant', 'content': reply})
            print(f'Agent: {reply}')

    except KeyboardInterrupt:
        print('\nGoodbye!')

readline: 입력 기록 및 편집

readline 모듈(Unix/Mac)을 사용하면 실제 셸처럼 화살표 키로 이전 입력 사이를 이동할 수 있습니다. 사용자는 위쪽 화살표를 눌러 이전 메시지를 불러올 수 있습니다.

try:
    import readline  # available on Unix/Mac, not Windows
    # Enable persistent history between sessions
    import os
    HISTORY_FILE = os.path.expanduser('~/.agent_history')
    try:
        readline.read_history_file(HISTORY_FILE)
    except FileNotFoundError:
        pass

    import atexit
    atexit.register(readline.write_history_file, HISTORY_FILE)
    readline.set_history_length(500)
    print('History enabled (use up/down arrows)')
except ImportError:
    pass  # readline not available on Windows

# After this, input() automatically has history support

기본 제공 슬래시 명령

자주 사용하는 작업을 위한 기본 제공 슬래시 명령을 REPL 에이전트에 추가하십시오: /help, /exit, 대화를 초기화하는 /clear, 이전 메시지를 확인하는 /history가 있습니다.

def handle_command(cmd: str, history: list) -> bool:
    'Returns True if the command was handled, False if it is a regular message'
    if cmd == '/exit' or cmd == '/quit':
        print('Goodbye!')
        raise SystemExit(0)

    elif cmd == '/help':
        print('Commands: /exit, /clear, /history, /help')
        return True

    elif cmd == '/clear':
        # Keep only the system message
        system = history[0] if history and history[0]['role'] == 'system' else None
        history.clear()
        if system:
            history.append(system)
        print('[Conversation cleared]')
        return True

    elif cmd == '/history':
        for i, msg in enumerate(history):
            if msg['role'] != 'system':
                print(f'  [{msg["role"]}] {msg["content"][:80]}')
        return True

    return False  # not a command, treat as regular message

if __name__ == '__main__':
    demo_history = [
        {'role': 'system', 'content': 'You are a helpful agent.'},
        {'role': 'user', 'content': 'Hi there'},
        {'role': 'assistant', 'content': 'Hello! How can I help?'},
    ]
    handle_command('/help', demo_history)
    handle_command('/history', demo_history)

대화 기록 길이 제한하기

각 대화 차례마다 전체 대화 기록을 LLM에 전달하면 토큰 수가 선형적으로 증가합니다. 비용을 관리하려면 시스템 메시지는 유지하면서 기록을 최근 N개 메시지로 줄이십시오.

def trim_history(history: list, max_turns: int = 10) -> list:
    system_messages = [m for m in history if m['role'] == 'system']
    non_system = [m for m in history if m['role'] != 'system']

    # Keep the last max_turns messages (each turn = 1 user + 1 assistant)
    max_messages = max_turns * 2
    trimmed = non_system[-max_messages:]

    return system_messages + trimmed

# Usage in the REPL loop:
# history.append({'role': 'user', 'content': user_input})
# trimmed = trim_history(history, max_turns=10)
# response = client.chat.completions.create(model='gpt-4o-mini', messages=trimmed)
print('Trimming history prevents token count from growing unboundedly')

환영 배너 표시하기

환영 배너를 표시하면 REPL이 더욱 완성도 있게 느껴집니다. 시작할 때 에이전트 이름, 버전, 사용 가능한 명령을 한 번 출력하십시오. 간단한 ASCII 아트나 색상을 지원하는 rich 라이브러리를 사용하십시오.

def print_banner():
    banner = '''
====================================
  AI Research Agent v1.0
====================================
  Type your question to begin.
  Commands: /help  /clear  /exit
====================================
    '''
    print(banner)

# Or with rich colors:
# from rich.console import Console
# from rich.panel import Panel
# console = Console()
# console.print(Panel('[bold cyan]AI Research Agent[/] v1.0', subtitle='Type /help for commands'))

print_banner()

입력 중 표시기 보여 주기

LLM 호출에는 몇 초가 걸릴 수 있습니다. 기다리는 동안 '생각 중...' 메시지를 표시하여 사용자가 에이전트가 처리 중임을 알 수 있도록 하십시오. 응답이 도착하면 메시지를 지우십시오.

import sys
import threading
import time

def thinking_spinner(stop_event: threading.Event):
    frames = ['|', '/', '-', '\\']
    i = 0
    while not stop_event.is_set():
        sys.stdout.write(f'\rAgent is thinking... {frames[i % 4]}')
        sys.stdout.flush()
        time.sleep(0.1)
        i += 1
    sys.stdout.write('\r' + ' ' * 30 + '\r')  # clear the line
    sys.stdout.flush()

def call_agent_with_spinner(query: str) -> str:
    stop = threading.Event()
    spinner = threading.Thread(target=thinking_spinner, args=(stop,))
    spinner.start()

    # result = agent.run(query)  # the actual slow call
    time.sleep(1)  # simulating work
    result = 'The answer is 42.'

    stop.set()
    spinner.join()
    return result

if __name__ == '__main__':
    answer = call_agent_with_spinner('What is 6 * 7?')
    print(f'\nFinal answer: {answer}')

세션을 파일에 저장하기

세션이 끝날 때 사용자가 대화를 파일에 저장할 수 있도록 하십시오. 에이전트가 무엇을 찾아냈는지 기록으로 남기고 싶은 연구 세션에 유용합니다.

import json
import datetime
import os

def save_session(history: list, directory: str = 'sessions'):
    os.makedirs(directory, exist_ok=True)
    timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
    filename = os.path.join(directory, f'session_{timestamp}.json')

    with open(filename, 'w') as f:
        json.dump({
            'saved_at': timestamp,
            'messages': history
        }, f, indent=2)

    print(f'Session saved to {filename}')

# Usage in REPL on /save command:
# save_session(conversation_history)

if __name__ == '__main__':
    import tempfile
    demo_dir = tempfile.mkdtemp()
    demo_history = [
        {'role': 'user', 'content': 'Hello'},
        {'role': 'assistant', 'content': 'Hi! How can I help?'},
    ]
    save_session(demo_history, directory=demo_dir)

완성형 REPL 에이전트 템플릿

지금까지 배운 내용을 모두 결합한 실무용 REPL 템플릿입니다. 기록 관리, 슬래시 명령, 키보드 인터럽트 처리, 세션 저장 기능을 포함합니다.

def run_repl(agent):
    history = [{'role': 'system', 'content': 'You are a helpful AI assistant.'}]
    print('Agent ready. Type /help for commands.')
    try:
        while True:
            user_input = input('You: ').strip()
            if not user_input:
                continue
            if user_input.startswith('/'):
                handle_command(user_input, history)
                continue
            history.append({'role': 'user', 'content': user_input})
            trimmed = trim_history(history, max_turns=10)
            reply = agent.run(trimmed)
            history.append({'role': 'assistant', 'content': reply})
            print(f'Agent: {reply}')
    except KeyboardInterrupt:
        print('\nSession ended.')
        save_session(history)

학습 확인: REPL 스타일 에이전트

대화형 REPL 에이전트에 대한 이해도를 확인해 보십시오.

복습: 대화형 REPL 스타일 에이전트

이제 터미널을 위한 모든 기능을 갖춘 대화형 에이전트를 구축할 수 있습니다:

  • 핵심 입력 반복문으로 while True: input()을 사용하십시오
  • 깔끔한 Ctrl+C 종료를 위해 KeyboardInterrupt를 포착하십시오
  • 여러 차례 대화를 기억하도록 conversation_history 목록을 유지하십시오
  • 화살표 키 입력 기록에는 readline을 사용하십시오
  • /help, /clear, /exit 슬래시 명령을 구현하십시오
  • 토큰 수가 제한 없이 증가하지 않도록 기록을 줄이십시오
  • LLM 호출 중 스피너나 진행률 표시기를 보여 주십시오
무료로 시작

AI 튜터와 함께 AI Agents을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
60
레슨
239

자주 묻는 질문

“대화형 REPL 스타일 에이전트” 강의는 무료인가요?

네 — “대화형 REPL 스타일 에이전트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.

“대화형 REPL 스타일 에이전트”에서 뭘 배우나요?

터미널 에이전트의 입력 반복, 기록, 여러 차례의 대화를 다룹니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Agents을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“대화형 REPL 스타일 에이전트” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 명령줄 에이전트 인터페이스 만들기
  2. 대화형 REPL 스타일 에이전트
  3. 인수 파싱 및 도움말 텍스트
  4. CLI 에이전트의 스트리밍 출력
← AI Agents(으)로 돌아가기