0Pricing
AI Agents · 강의

처음부터 ReAct 구현

LangChain 없이 Python 100줄로 구현해보세요. Action 줄을 분석하고 도구를 실행하며 Final Answer가 나올 때까지 반복합니다.

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

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

반복 과정 직접 구축하기

프레임워크 없이 Python 약 100줄로 ReAct를 작성할 수 있습니다. 한 번 직접 작성해 보면 프레임워크가 추상화하는 내용을 직관적으로 이해할 수 있습니다.

Step 1: Define Tools

import json, math

def calculator(expression: str) -> str:
    try:
        return str(eval(expression, {'__builtins__': {}}, vars(math)))
    except Exception as e:
        return f'Error: {e}'

def search_wikipedia(query: str) -> str:
    # placeholder — call a real search API
    return f'Wikipedia summary for: {query}'

TOOLS = {
    'calculator': calculator,
    'search_wikipedia': search_wikipedia,
}

print(calculator('2 + 2 * sqrt(16)'))
print(search_wikipedia('agents'))

Step 2: Tool Schemas

schemas = [
    {'type': 'function', 'function': {
        'name': 'calculator',
        'description': 'Evaluate a math expression like 2 + 2 * sqrt(16)',
        'parameters': {'type': 'object', 'properties': {'expression': {'type': 'string'}}, 'required': ['expression']}
    }},
    {'type': 'function', 'function': {
        'name': 'search_wikipedia',
        'description': 'Search Wikipedia and return a summary',
        'parameters': {'type': 'object', 'properties': {'query': {'type': 'string'}}, 'required': ['query']}
    }}
]
import json
print(json.dumps(schemas, indent=2))

Step 3: System Prompt

system = '''
You are a research assistant. Use the available tools when needed.
Think step by step. If you have enough information, give a final answer.
'''
print(system.strip())

Step 4: The Loop

from openai import OpenAI
client = OpenAI()

def react(question, max_steps=10):
    messages = [
        {'role': 'system', 'content': system},
        {'role': 'user', 'content': question}
    ]
    for step in range(max_steps):
        r = client.chat.completions.create(
            model='gpt-4o-mini',
            messages=messages,
            tools=schemas,
        )
        msg = r.choices[0].message
        messages.append(msg)
        if not msg.tool_calls:
            return msg.content
        for tc in msg.tool_calls:
            args = json.loads(tc.function.arguments)
            try:
                result = TOOLS[tc.function.name](**args)
            except Exception as e:
                result = f'Tool error: {e}'
            messages.append({'role': 'tool', 'tool_call_id': tc.id, 'content': str(result)})
    return 'Step limit reached.'

Step 5: Run It

answer = react('What is the population of Tokyo times the square root of pi?')
print(answer)

6단계: 로그 기록 추가

디버깅을 위해 모든 단계를 기록하십시오:

def react_verbose(question, max_steps=10):
    messages = [...]
    for step in range(max_steps):
        r = client.chat.completions.create(model='gpt-4o-mini', messages=messages, tools=schemas)
        msg = r.choices[0].message
        print(f'[step {step}] thought: {msg.content}')
        if msg.tool_calls:
            for tc in msg.tool_calls:
                print(f'[step {step}] action: {tc.function.name}({tc.function.arguments})')
        ...

7단계: 도구로 단계 카운터 추가

일부 에이전트는 모델이 언제 수렴해야 하는지 알 수 있도록 시스템 프롬프트에 단계 수를 포함합니다:

system = f'You have at most {MAX_STEPS} steps. Step {current_step}/{MAX_STEPS}. ...'

8단계: 최종 답변 형식

구조화된 출력을 원한다면 최종 도구 호출을 강제하십시오:

tools.append({'type': 'function', 'function': {
    'name': 'final_answer',
    'description': 'Submit the final answer to the user.',
    'parameters': {'type': 'object', 'properties': {'answer': {'type': 'string'}}, 'required': ['answer']}
}})
# Loop terminates when final_answer is called.

9단계: 도구 오류

에이전트가 복구할 수 있도록 항상 오류를 도구 결과로 반환하십시오:

try:
    result = TOOLS[name](**args)
except Exception as e:
    result = f'TOOL ERROR: {type(e).__name__}: {e}'
# Model sees the error and can try a different approach.

10단계: 병렬 도구 호출

msg.tool_calls에 여러 항목이 있으면 이를 병렬로 실행하십시오:

import asyncio

async def run_tools(tool_calls):
    async def run_one(tc):
        args = json.loads(tc.function.arguments)
        return tc.id, TOOLS[tc.function.name](**args)
    return await asyncio.gather(*[run_one(tc) for tc in tool_calls])

11단계: 대화 길이 제한

MAX_STEPS 안에서도 메시지 목록이 지나치게 커질 수 있습니다. 차례가 바뀔 때마다 토큰 수를 기준으로 줄이십시오:

if total_tokens(messages) > 6000:
    messages = trim_messages(messages)

12단계: 프로덕션 강화

프로덕션 환경에서는 도구 호출 시간 초과, 도구별 할당량, API 실패 시 지수 백오프를 사용한 재시도, 전체 추적 로그 기록을 추가하십시오. 하지만 위의 반복 과정이 기본 골격입니다.

도구 오류 처리

도구에서 예외가 발생하면 어떻게 해야 합니까?

복습

약 80줄로 구현하는 ReAct: 메시지 목록 + while 반복문 + 디스패치 표입니다. 프레임워크는 편의 기능을 더하지만 핵심은 이것입니다.

자주 묻는 질문

“처음부터 ReAct 구현” 강의는 무료인가요?

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

“처음부터 ReAct 구현”에서 뭘 배우나요?

LangChain 없이 Python 100줄로 구현해보세요. Action 줄을 분석하고 도구를 실행하며 Final Answer가 나올 때까지 반복합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“처음부터 ReAct 구현” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. ReAct: 추론 + 행동 패턴
  2. 처음부터 ReAct 구현
  3. 일반적인 도구 세트(웹, 계산기, RAG)
  4. 도구 오류 감지 및 복구
← AI Agents(으)로 돌아가기