트리거-작업 에이전트 패턴
이벤트 감지 → 결정 → 작업으로 이어지는 핵심 자동화 반복 과정을 알아봅니다.
트리거-작업 에이전트 패턴은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
트리거-액션 에이전트란 무엇입니까
트리거-액션 에이전트는 이벤트를 감지하고 작업으로 응답합니다. 세 단계로 이루어진 반복 과정은 다음과 같습니다. 이벤트 감지 → LLM이 작업 결정 → 작업 실행.
예: 이메일 수신 → 요약하고 답장하기, 파일 업로드 → 검증하고 처리하기, 매일 오전 9시 → 일일 보고서 생성하기입니다.
트리거 유형
트리거는 세 가지 범주로 나뉩니다.
- 이벤트 기반: 이메일이 도착하거나 파일이 업로드되면 웹훅 실행
- 시간 기반: 크론 일정에 따라 일정한 간격으로 에이전트 실행
- 폴링 기반: 새 데이터를 찾기 위해 에이전트가 API를 반복해서 확인
적절한 트리거 유형을 선택하면 에이전트의 지연 시간과 리소스 사용량이 결정됩니다.
감지 단계
감지란 이벤트를 수신하거나 인식하는 것을 의미합니다. 웹훅의 경우 서버가 POST 요청을 수신합니다. 폴링의 경우 에이전트가 API를 조회하고 결과를 마지막으로 확인한 상태와 비교합니다.
import json
def detect_new_email(current_emails, last_seen_id):
new_emails = [
e for e in current_emails
if e['id'] > last_seen_id
]
return new_emails
# Simulate detection
current = [{'id': 3, 'subject': 'Meeting'}, {'id': 4, 'subject': 'Invoice'}]
new = detect_new_email(current, last_seen_id=2)
print('New emails:', [e['subject'] for e in new])결정 단계
이벤트를 감지한 후 에이전트는 컨텍스트를 LLM에 보내 어떤 작업을 수행할지 묻습니다. LLM은 도구를 선택하거나 직접 응답을 반환합니다.
import openai
client = openai.OpenAI(api_key='sk-...')
def decide_action(event_description):
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[
{'role': 'system', 'content': 'You are an automation agent. Decide what action to take for the event.'},
{'role': 'user', 'content': f'Event: {event_description}'}
],
tools=[
{'type': 'function', 'function': {'name': 'send_reply', 'description': 'Reply to email', 'parameters': {'type': 'object', 'properties': {'message': {'type': 'string'}}, 'required': ['message']}}}
]
)
return response.choices[0].message
result = decide_action('New email: Invoice for $500 from supplier')
print(result)실행 단계
실행 단계에서는 선택한 작업을 수행합니다. API를 호출하거나, 파일을 작성하거나, 메시지를 보내거나, 다른 워크플로를 실행할 수 있습니다. 항상 오류를 처리하고 결과를 기록하십시오.
import logging
import sys
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
logger = logging.getLogger('agent')
def execute_action(action_name, params):
try:
if action_name == 'send_reply':
# In real code, call Gmail API here
logger.info(f'Sending reply: {params["message"]}')
return {'status': 'success'}
elif action_name == 'create_task':
logger.info(f'Creating task: {params["title"]}')
return {'status': 'success'}
else:
raise ValueError(f'Unknown action: {action_name}')
except Exception as e:
logger.error(f'Action failed: {e}')
return {'status': 'error', 'message': str(e)}
if __name__ == '__main__':
result = execute_action('send_reply', {'message': 'Thanks for reaching out!'})
print('Result:', result)
상태 머신 모델
상태 머신은 자동화 에이전트를 모델링하는 강력한 방법입니다. 상태는 다음과 같을 수 있습니다. IDLE, DETECTING, DECIDING, EXECUTING, ERROR. 전이는 이벤트나 조건이 발생할 때 일어납니다.
상태 머신을 사용하면 에이전트의 동작을 예측하기 쉽고 디버깅도 간단해집니다.
from enum import Enum
class AgentState(Enum):
IDLE = 'idle'
DETECTING = 'detecting'
DECIDING = 'deciding'
EXECUTING = 'executing'
ERROR = 'error'
class AutomationAgent:
def __init__(self):
self.state = AgentState.IDLE
def transition(self, new_state):
print(f'State: {self.state.value} -> {new_state.value}')
self.state = new_state
def run_cycle(self, event=None):
self.transition(AgentState.DETECTING)
if event:
self.transition(AgentState.DECIDING)
self.transition(AgentState.EXECUTING)
self.transition(AgentState.IDLE)
agent = AutomationAgent()
agent.run_cycle(event={'type': 'email', 'subject': 'Test'})이메일 수신 트리거 패턴
Gmail 푸시 알림은 Pub/Sub을 사용합니다. 새 이메일이 도착하면 Google이 사용자의 주제에 메시지를 게시합니다. 에이전트는 웹훅을 수신하고 이메일을 가져와 처리합니다.
from fastapi import FastAPI, Request
import base64, json
app = FastAPI()
@app.post('/gmail-push')
async def gmail_push(request: Request):
body = await request.json()
# Decode Pub/Sub message
message = body.get('message', {})
data = base64.b64decode(message.get('data', '')).decode('utf-8')
notification = json.loads(data)
email_address = notification.get('emailAddress')
history_id = notification.get('historyId')
print(f'New email for {email_address}, historyId: {history_id}')
# Fetch email details and run agent here
return {'status': 'ok'}파일 업로드 트리거 패턴
S3 이벤트 알림이나 로컬 파일 시스템 감시기는 파일이 나타날 때 에이전트를 실행할 수 있습니다. watchdog 라이브러리는 새 파일을 찾기 위해 디렉터리를 감시합니다.
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time
class UploadHandler(FileSystemEventHandler):
def on_created(self, event):
if event.is_directory:
return
print(f'New file detected: {event.src_path}')
self.process_file(event.src_path)
def process_file(self, filepath):
# Run agent logic on new file
print(f'Processing: {filepath}')
observer = Observer()
handler = UploadHandler()
observer.schedule(handler, path='/tmp/uploads/', recursive=False)
observer.start()
try:
time.sleep(30) # Watch for 30 seconds
finally:
observer.stop()
observer.join()시간 기반 트리거 패턴
시간 기반 트리거는 일정에 따라 에이전트를 실행합니다. 프로세스 내부 스케줄링에는 APScheduler를 사용하고, 프로세스 수준의 스케줄링에는 시스템 크론 작업을 사용하십시오.
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime
scheduler = BlockingScheduler()
def daily_report_agent():
print(f'Daily report running at {datetime.now()}')
# Fetch data, call LLM, send report
pass
def hourly_check_agent():
print(f'Hourly check at {datetime.now()}')
pass
# Run at 8am every day
scheduler.add_job(daily_report_agent, 'cron', hour=8, minute=0)
# Run every 30 minutes
scheduler.add_job(hourly_check_agent, 'interval', minutes=30)
print('Scheduler started')
scheduler.start()멱등성 작업 실행
자동화 에이전트는 멱등성을 갖춰야 합니다. 동일한 작업을 두 번 실행해도 중복된 효과가 발생해서는 안 됩니다. 멱등성 키와 실행 전에 확인하는 패턴을 사용하십시오.
import hashlib
processed_events = set() # In production, use Redis or DB
def compute_event_id(event):
content = f"{event['type']}:{event['source_id']}:{event['timestamp']}"
return hashlib.sha256(content.encode()).hexdigest()[:16]
def handle_event_idempotent(event):
event_id = compute_event_id(event)
if event_id in processed_events:
print(f'Skipping duplicate event: {event_id}')
return {'status': 'duplicate', 'event_id': event_id}
# Process event
print(f'Processing event: {event_id}')
processed_events.add(event_id)
return {'status': 'processed', 'event_id': event_id}
# Simulate duplicate event
event = {'type': 'email', 'source_id': 'abc123', 'timestamp': '2024-01-01T09:00:00'}
print(handle_event_idempotent(event))
print(handle_event_idempotent(event)) # Duplicate - skipped오류 상태 및 복구
견고한 에이전트는 장애를 원활하게 처리합니다. 실행에 실패하면 지수 백오프로 다시 시도하거나, 사람에게 알리거나, 수동 검토를 위해 배달 못한 편지 큐로 이동할 수 있습니다.
import time
def execute_with_retry(action_fn, max_retries=3):
for attempt in range(max_retries):
try:
result = action_fn()
print(f'Success on attempt {attempt + 1}')
return result
except Exception as e:
wait = 2 ** attempt # Exponential backoff: 1s, 2s, 4s
print(f'Attempt {attempt + 1} failed: {e}. Retrying in {wait}s')
if attempt < max_retries - 1:
time.sleep(wait)
else:
print('All retries exhausted. Moving to dead-letter queue.')
raise
# Example usage
call_count = [0]
def flaky_action():
call_count[0] += 1
if call_count[0] < 3:
raise ConnectionError('Service unavailable')
return 'Done'
execute_with_retry(flaky_action)지식 확인: 트리거-액션 패턴
트리거-액션 에이전트 패턴에 대한 이해도를 테스트해 보십시오.
전체 구성
완전한 트리거-액션 에이전트는 트리거 소스(이메일, 파일, 타이머), 감지 계층, LLM 기반 의사 결정, 멱등성 실행, 재시도 로직, 상태 추적을 모두 결합합니다.
간단하게 시작하십시오. 트리거 유형 하나와 작업 하나만 사용하십시오. 에이전트의 동작에 자신감이 생기면 복잡성을 점진적으로 추가하십시오.
AI 튜터와 함께 AI Agents을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 60
- 레슨
- 239
자주 묻는 질문
“트리거-작업 에이전트 패턴” 강의는 무료인가요?
네 — “트리거-작업 에이전트 패턴” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
“트리거-작업 에이전트 패턴”에서 뭘 배우나요?
이벤트 감지 → 결정 → 작업으로 이어지는 핵심 자동화 반복 과정을 알아봅니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Agents을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“트리거-작업 에이전트 패턴” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 트리거-작업 에이전트 패턴
- 에이전트를 웹훅에 연결하기
- 예약 및 Cron 기반 에이전트
- 다중 앱 자동화 파이프라인 구축