0Pricing
AI Agents · บทเรียน

ตัวแทนรูปแบบ REPL แบบโต้ตอบ

ลูปข้อมูลนำเข้า ประวัติ และการสนทนาหลายรอบในตัวแทนเทอร์มินัล

ตัวแทนรูปแบบ REPL แบบโต้ตอบ เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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() เป็นวงจรอ่านหลัก
  • ดักจับ KeyboardInterrupt เพื่อออกจากโปรแกรมด้วย Ctrl+C อย่างเรียบร้อย
  • รักษารายการ conversation_history เพื่อจดจำการสนทนาหลายรอบ
  • ใช้ readline สำหรับประวัติอินพุตที่เรียกดูด้วยปุ่มลูกศร
  • ใช้คำสั่งเครื่องหมายทับ /help, /clear และ /exit
  • ตัดประวัติเพื่อป้องกันจำนวนโทเค็นเพิ่มขึ้นอย่างไม่มีขอบเขต
  • แสดงวงล้อหมุนหรือตัวบ่งชี้ความคืบหน้าระหว่างการเรียกใช้ LLM

คำถามที่พบบ่อย

บทเรียน “ตัวแทนรูปแบบ REPL แบบโต้ตอบ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ตัวแทนรูปแบบ REPL แบบโต้ตอบ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ตัวแทนรูปแบบ REPL แบบโต้ตอบ”

ลูปข้อมูลนำเข้า ประวัติ และการสนทนาหลายรอบในตัวแทนเทอร์มินัล คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “ตัวแทนรูปแบบ REPL แบบโต้ตอบ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม

ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การสร้างส่วนติดต่อบรรทัดคำสั่งสำหรับตัวแทน
  2. ตัวแทนรูปแบบ REPL แบบโต้ตอบ
  3. การแยกวิเคราะห์อาร์กิวเมนต์และข้อความช่วยเหลือ
  4. การส่งข้อมูลออกแบบสตรีมในตัวแทน CLI
← กลับไปที่ AI Agents