AI एजेंट · पाठ

डेटा विश्लेषण के लिए कोड इंटरप्रेटर पैटर्न

सैंडबॉक्स किए गए Python निष्पादन में एजेंट टूल के भीतर pandas/matplotlib चलाना।

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

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

कोड व्याख्याता प्रतिरूप

कोड व्याख्याता प्रतिरूप एजेंट को डेटा विश्लेषण संबंधी प्रश्नों के उत्तर देने के लिए पाइथन कोड बनाने, उस कोड को सैंडबॉक्स में निष्पादित करने, परिणाम कैप्चर करने और परिणामों की व्याख्या करने देता है।

हर विश्लेषण संचालन को पहले से कोड में लिखने के बजाय, एजेंट प्रत्येक प्रश्न के लिए कस्टम कोड लिखता है—इससे डेटा कार्यों के लिए लगभग असीम लचीलापन मिलता है।

मुख्य चक्र: बनाना → निष्पादित करना → व्याख्या करना

इस प्रतिरूप में तीन चरण होते हैं, जिन्हें दोहराया जा सकता है:

  1. बनाना — LLM प्रश्न का उत्तर देने के लिए पाइथन कोड लिखता है
  2. निष्पादित करना — सैंडबॉक्स में कोड चलाएँ और मानक परिणाम तथा फ़ाइलें कैप्चर करें
  3. व्याख्या करना — परिणामों की व्याख्या करने के लिए परिणाम LLM को वापस भेजें
def code_interpreter_agent(question, data_path):
    # Step 1: Generate code
    code = generate_analysis_code(question, data_path)
    print('Generated code:', code[:200])

    # Step 2: Execute in sandbox
    result = execute_in_sandbox(code)

    if result['error']:
        # Try to fix the error
        fixed_code = fix_code(code, result['error'])
        result = execute_in_sandbox(fixed_code)

    # Step 3: Interpret output
    return interpret_output(question, result)

print(code_interpreter_agent(
    'What is the average order value by customer segment?',
    'data/orders.csv'
))

कोड निर्माण प्रॉम्प्ट

कोड निर्माण प्रॉम्प्ट में ये शामिल होने चाहिए: डेटा पथ/स्कीमा, प्रश्न और सीमाएँ (कोई बाहरी एपीआई नहीं, pandas का उपयोग करें, चार्ट फ़ाइलों में सहेजें)।

CODE_GEN_PROMPT = """You are a Python data analyst. Write Python code to answer the question.
Data available at: {data_path}
Question: {question}
Write ONLY Python code (no markdown, no explanation):"""

def llm_call(prompt):
    return "```python\nprint('df.describe() results')\n```"

def generate_analysis_code(question, data_path):
    response = llm_call(CODE_GEN_PROMPT.format(question=question, data_path=data_path))
    code = response.strip()
    if code.startswith('```'):
        code = code.split('```')[1]
        if code.startswith('python'):
            code = code[6:]
    return code.strip()

print(generate_analysis_code('What is the average price?', 'data.csv'))

उप-प्रक्रिया सैंडबॉक्स निष्पादन

सबसे सरल सैंडबॉक्स समय-सीमा के साथ अलग उप-प्रक्रिया में कोड चलाना है। इससे प्रक्रिया अलगाव मिलता है—यदि कोड अचानक बंद हो जाए, तो एजेंट बंद नहीं होता।

import subprocess
import tempfile
import os

def execute_in_sandbox(code, timeout=30):
    # Write code to temp file
    with tempfile.NamedTemporaryFile(suffix='.py', mode='w', delete=False) as f:
        f.write(code)
        script_path = f.name

    try:
        result = subprocess.run(
            ['python3', script_path],
            capture_output=True,
            text=True,
            timeout=timeout,
            env={**os.environ, 'MPLBACKEND': 'Agg'}  # non-interactive matplotlib
        )
        return {
            'stdout': result.stdout,
            'stderr': result.stderr,
            'returncode': result.returncode,
            'error': result.stderr if result.returncode != 0 else None
        }
    except subprocess.TimeoutExpired:
        return {'stdout': '', 'stderr': 'Timeout', 'returncode': -1, 'error': 'Code timed out'}
    finally:
        os.unlink(script_path)

if __name__ == '__main__':
    result = execute_in_sandbox('print(2 + 2)')
    print('Sandbox stdout:', result['stdout'].strip())
    print('Return code   :', result['returncode'])

E2B क्लाउड सैंडबॉक्स

E2B सुरक्षित कोड निष्पादन के लिए एक प्रबंधित क्लाउड सैंडबॉक्स उपलब्ध कराता है—उप-प्रक्रिया से अधिक सुरक्षित। यह फ़ाइल सिस्टम की पहुँच वाले अलग कंटेनर में कोड चलाता है।

pip install e2b-code-interpreter से इंस्टॉल करें।

from e2b_code_interpreter import Sandbox
import os

def execute_with_e2b(code, data_bytes=None):
    with Sandbox(api_key=os.getenv('E2B_API_KEY')) as sandbox:
        # Upload data file if provided
        if data_bytes:
            sandbox.files.write('/home/user/data.csv', data_bytes)

        # Execute code
        execution = sandbox.run_code(code)

        result = {
            'stdout': '\n'.join(execution.logs.stdout),
            'stderr': '\n'.join(execution.logs.stderr),
            'error': None
        }

        # Check for errors
        if execution.error:
            result['error'] = str(execution.error)

        # Download any generated files
        result['files'] = []
        for output in execution.results:
            if hasattr(output, 'png'):
                result['files'].append({
                    'type': 'image/png',
                    'data': output.png  # base64 encoded
                })

    return result

जनरेट की गई फ़ाइलें प्राप्त करना

कोड चार्ट, CSV निर्यात या अन्य फ़ाइलें बना सकता है। इन्हें सैंडबॉक्स के फ़ाइल सिस्टम से प्राप्त करें और व्याख्या या प्रदर्शन के लिए एजेंट को वापस दें।

import os
import glob
import base64

OUTPUT_DIR = '/tmp/chart_output'

def execute_and_capture(code, timeout=30):
    # Create output dir
    os.makedirs(OUTPUT_DIR, exist_ok=True)

    result = execute_in_sandbox(code, timeout=timeout)

    # Capture any generated image files
    generated_files = []
    for filepath in glob.glob(os.path.join(OUTPUT_DIR, '*.png')):
        with open(filepath, 'rb') as f:
            encoded = base64.b64encode(f.read()).decode('utf-8')
        generated_files.append({
            'filename': os.path.basename(filepath),
            'type': 'image/png',
            'base64': encoded
        })
        os.unlink(filepath)  # clean up

    result['generated_files'] = generated_files
    print(f'Captured {len(generated_files)} file(s) from sandbox')
    return result

त्रुटि सुधार लूप

पहली बार चलाने पर जनरेट किया गया कोड अक्सर त्रुटिपूर्ण होता है। सुधार लूप लागू करें: मूल कोड के साथ त्रुटि LLM को भेजें और उससे सुधार करने के लिए कहें। पुनः प्रयासों की संख्या 2–3 तक सीमित रखें।

FIX_PROMPT = '''The following Python code raised an error. Fix it.

Original code:
{code}

Error:
{error}

Return ONLY the fixed Python code (no explanation, no markdown):'''

def fix_code(code, error):
    return llm_call(FIX_PROMPT.format(code=code, error=error)).strip()

def execute_with_retry(code, max_retries=2):
    for attempt in range(max_retries + 1):
        result = execute_and_capture(code)
        if not result['error']:
            return result
        print(f'Attempt {attempt + 1} failed: {result["error"][:100]}')
        if attempt < max_retries:
            code = fix_code(code, result['error'])
    return result  # return last result even if errored

कोड परिणामों की व्याख्या

कच्चे कोड परिणाम (संख्याएँ, सारणियाँ) को प्राकृतिक भाषा के answer में बदलना आवश्यक है। मानक आउटपुट LLM को दें और उससे मूल प्रश्न के संदर्भ में परिणाम समझाने के लिए कहें।

INTERPRET_PROMPT = '''A Python script was executed to answer a data analysis question.
Explain the results in clear, non-technical language.

Original question: {question}

Code output (stdout):
{output}

Provide a clear, concise answer that directly addresses the question.
Highlight the most important numbers or findings.
Answer:'''

def interpret_output(question, execution_result):
    stdout = execution_result.get('stdout', '').strip()
    error = execution_result.get('error')

    if error and not stdout:
        return f'The analysis failed with error: {error}'

    if not stdout:
        return 'The code ran successfully but produced no output.'

    return llm_call(INTERPRET_PROMPT.format(
        question=question,
        output=stdout[:3000]  # truncate very long outputs
    ))

कोड निर्माण में सुरक्षा सीमाएँ

जनरेट किया गया कोड नेटवर्क अनुरोध नहीं कर सकता, संवेदनशील फ़ाइलों तक पहुँच नहीं सकता और सिस्टम आदेश नहीं चला सकता। इसे प्रॉम्प्ट और सैंडबॉक्स प्रतिबंधों—दोनों के माध्यम से लागू करें।

BLOCKED_IMPORTS = ['requests', 'httpx', 'urllib', 'socket', 'subprocess', 'os.system']

def pre_validate_code(code):
    errors = []
    for blocked in BLOCKED_IMPORTS:
        if f'import {blocked}' in code or f'from {blocked}' in code:
            errors.append(f'Blocked import: {blocked}')

    # Block shell execution
    import re
    if re.search(r'os\.system|subprocess\.run|subprocess\.call|eval\(|exec\(', code):
        errors.append('Blocked: shell execution or eval/exec')

    # Block reading outside allowed paths
    if re.search(r'open\([^)]*\.\./|open\([^)]*\/etc\/', code):
        errors.append('Blocked: unauthorized file access')

    if errors:
        raise ValueError('Security check failed:\n' + '\n'.join(errors))

    return True

if __name__ == '__main__':
    try:
        pre_validate_code('import requests\nrequests.get("http://x")')
    except ValueError as e:
        print('Rejected:', e)
    print('Safe code passed:', pre_validate_code('print(1 + 1)'))

डेटा स्कीमा सम्मिलन

LLM तब बेहतर कोड बनाता है जब उसे पहले से डेटा स्कीमा—कॉलम के नाम, प्रकार और नमूना पंक्तियाँ—पता हों। कोड निर्माण प्रॉम्प्ट में स्कीमा का विवरण शामिल करें।

import pandas as pd

def get_data_schema(data_path):
    df = pd.read_csv(data_path, nrows=5)
    schema_lines = []
    for col in df.columns:
        dtype = str(df[col].dtype)
        sample = df[col].dropna().iloc[0] if len(df[col].dropna()) > 0 else 'N/A'
        schema_lines.append(f'  - {col} ({dtype}): sample={sample!r}')
    schema_text = '\n'.join(schema_lines)
    return f'CSV columns:\n{schema_text}\nTotal rows: {len(pd.read_csv(data_path))}'

ENHANCED_PROMPT = CODE_GEN_PROMPT + '\n\nData schema:\n{schema}'

def generate_analysis_code_with_schema(question, data_path):
    schema = get_data_schema(data_path)
    response = llm_call(ENHANCED_PROMPT.format(
        question=question, data_path=data_path, schema=schema
    ))
    return response.strip()

निष्पादन इतिहास का रिकॉर्ड रखना

किसी सत्र में सभी कोड निष्पादनों का रिकॉर्ड रखें। इससे एजेंट पिछले परिणामों का संदर्भ दे सकता है, पहले की गणनाओं पर आगे काम कर सकता है और उपयोगकर्ता को अपने विश्लेषण के चरण समझा सकता है।

from datetime import datetime

execution_history = []

def record_execution(question, code, result):
    execution_history.append({
        'timestamp': datetime.now().isoformat(),
        'question': question,
        'code_lines': len(code.splitlines()),
        'stdout_preview': result.get('stdout', '')[:200],
        'success': result.get('error') is None,
        'generated_files': len(result.get('generated_files', []))
    })

def get_session_summary():
    total = len(execution_history)
    successful = sum(1 for e in execution_history if e['success'])
    return {
        'total_executions': total,
        'successful': successful,
        'failed': total - successful,
        'success_rate': f'{successful/max(total,1)*100:.0f}%',
        'questions_answered': [e['question'][:60] for e in execution_history]
    }

# Usage in agent loop
def code_interpreter_agent_tracked(question, data_path):
    code = generate_analysis_code_with_schema(question, data_path)
    result = execute_with_retry(code)
    record_execution(question, code, result)
    return interpret_output(question, result)

ज्ञान-जाँच

विशिष्ट डेटा विश्लेषण कार्यों को एजेंट के उपकरणों के रूप में पहले से कोड में लिख देने के बजाय कोड व्याख्याकार पैटर्न का उपयोग करने का मुख्य लाभ क्या है?

पुनरावलोकन: डेटा विश्लेषण के लिए कोड व्याख्याकार पैटर्न

कोड व्याख्याकार पैटर्न: Python कोड जनरेट करें (स्कीमा संदर्भ और सुरक्षा सीमाओं के साथ) → सैंडबॉक्स में निष्पादित करें (उप-प्रक्रिया या E2B) → मानक आउटपुट और फ़ाइलें प्राप्त करें → त्रुटियों पर पुनः प्रयास करें → परिणामों की प्राकृतिक भाषा में व्याख्या करें।

मुख्य बातें: बेहतर कोड निर्माण के लिए डेटा स्कीमा सम्मिलित करें, अवरुद्ध आयात और शेल आदेशों के लिए कोड का पूर्व-सत्यापन करें, अनियंत्रित निष्पादन रोकने के लिए उप-प्रक्रिया की समय-सीमा रखें और प्रदर्शन के लिए जनरेट किए गए चार्ट को base64 के रूप में प्राप्त करें।

शुरुआत निःशुल्क

एआई शिक्षक के साथ AI एजेंट सीखें — निःशुल्क

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

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

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

क्या “डेटा विश्लेषण के लिए कोड इंटरप्रेटर पैटर्न” पाठ निःशुल्क है?

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

“डेटा विश्लेषण के लिए कोड इंटरप्रेटर पैटर्न” में मैं क्या सीखूँगा?

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

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

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

“डेटा विश्लेषण के लिए कोड इंटरप्रेटर पैटर्न” पाठ पूरा करने में कितना समय लगता है?

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

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

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

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

  1. डेटा विश्लेषण के लिए कोड इंटरप्रेटर पैटर्न
  2. Pandas-आधारित डेटा एजेंट टूल
  3. स्वचालित चार्ट और विज़ुअलाइज़ेशन बनाना
  4. सांख्यिकीय सारांश एजेंट
← AI एजेंट पर वापस जाएँ