AI एजेंट · पाठ

इंटरैक्टिव REPL-शैली एजेंट

टर्मिनल एजेंट में इनपुट चक्र, इतिहास और बहु-चरणीय बातचीत।

पाठ 2, कुल 4 में से13 चरण

इंटरैक्टिव REPL-शैली एजेंट, CoddyKit पर AI एजेंट का एक निःशुल्क पाठ है। यह 4 में से 2वाँ पाठ है। आप नीचे पूरा पाठ निःशुल्क पढ़ सकते हैं—फिर अंतर्निहित कोड संपादक और 24/7 एआई ट्यूटर के साथ ब्राउज़र में इसका व्यावहारिक अभ्यास कर सकते हैं। यह AI एजेंट सीखने के मार्ग का हिस्सा है और आपकी प्रगति वेब तथा CoddyKit ऐप पर सिंक होती रहती है। AI एजेंट पाठ्यक्रम में कुल 4 पाठ शामिल हैं।

REPL-शैली का एजेंट क्या है

REPL (Read-Eval-Print Loop) एक इंटरैक्टिव टर्मिनल सत्र है, जिसमें आप इनपुट लिखते हैं, आउटपुट get करते हैं और आगे बढ़ते रहते हैं। टर्मिनल में चैट एजेंट ठीक इसी तरह काम करते हैं: उपयोगकर्ता संदेश लिखता है, एजेंट उत्तर देता है और उपयोगकर्ता के बाहर निकलने तक बातचीत जारी रहती है।

मूल 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}')

सत्र को फ़ाइल में सहेजना

उपयोगकर्ताओं को सत्र के अंत में बातचीत को फ़ाइल में सहेजने दें। यह उन research सत्रों के लिए उपयोगी है, जिनमें आप एजेंट द्वारा खोजी गई जानकारी का रिकॉर्ड रखना चाहते हैं।

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 एजेंट सीखें — निःशुल्क

अपने ब्राउज़र में वास्तविक कोड लिखें और चलाएँ, चौबीसों घंटे एआई शिक्षक से तुरंत सहायता पाएँ, और वेब या ऐप पर वहीं से शुरू करें जहाँ आपने छोड़ा था।

पाठ्यक्रम
60
पाठ
239

अक्सर पूछे जाने वाले प्रश्न

क्या “इंटरैक्टिव REPL-शैली एजेंट” पाठ निःशुल्क है?

हाँ—“इंटरैक्टिव REPL-शैली एजेंट” का पूरा पाठ यहाँ वेब पर निःशुल्क पढ़ा जा सकता है। इंटरैक्टिव अभ्यास (अंतर्निहित कोड संपादक और 24/7 एआई ट्यूटर) करने और AI एजेंट पाठ्यक्रम का बाकी हिस्सा अनलॉक करने के लिए CoddyKit PRO लें। AI एजेंट पाठ्यक्रम में कुल 4 पाठ शामिल हैं।

“इंटरैक्टिव REPL-शैली एजेंट” में मैं क्या सीखूँगा?

टर्मिनल एजेंट में इनपुट चक्र, इतिहास और बहु-चरणीय बातचीत। आप ब्राउज़र में सीधे चलाए जाने वाले व्यावहारिक कोड के साथ AI एजेंट का अभ्यास करते हैं, और पाठ पूरा करते समय 24/7 एआई ट्यूटर आपके प्रश्नों के उत्तर देता है।

क्या AI एजेंट शुरू करने के लिए मुझे किसी अनुभव की आवश्यकता है?

पहले के अनुभव की आवश्यकता नहीं है। CoddyKit पर AI एजेंट शुरुआती से लेकर उन्नत शिक्षार्थियों तक सभी के लिए व्यवस्थित किया गया है, इसलिए आप यहीं से या शुरुआत से सीखना शुरू कर सकते हैं और अपनी गति से आगे बढ़ सकते हैं। यह 4 में से 2वाँ पाठ है।

“इंटरैक्टिव REPL-शैली एजेंट” पाठ पूरा करने में कितना समय लगता है?

CoddyKit का अधिकांश पाठ लगभग 5–10 मिनट में पूरा हो जाता है। हर पाठ छोटा और संवादात्मक है, इसलिए आप लगातार प्रगति करते हैं और वेब या ऐप पर वहीं से सीखना जारी रख सकते हैं जहाँ आपने छोड़ा था।

क्या मैं इस AI एजेंट पाठ में कोड लिख और चला सकता हूँ?

हाँ। हर AI एजेंट पाठ में एक अंतर्निर्मित कोड संपादक शामिल है, जिससे आप सीधे अपने ब्राउज़र में वास्तविक कोड लिख और चला सकते हैं और तुरंत एआई प्रतिक्रिया पा सकते हैं—स्थानीय सेटअप की आवश्यकता नहीं है।

इस पाठ्यक्रम के सभी पाठ

  1. कमांड-लाइन एजेंट इंटरफ़ेस बनाना
  2. इंटरैक्टिव REPL-शैली एजेंट
  3. तर्क पार्स करना और सहायता टेक्स्ट
  4. CLI एजेंट में स्ट्रीमिंग आउटपुट
← AI एजेंट पर वापस जाएँ