출력을 입력으로 연결하는 패턴
1단계에서 구조화된 데이터를 추출해 2단계에 주입합니다.
출력을 입력으로 연결하는 패턴은(는) CoddyKit의 무료 AI Prompt Engineering 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Prompt Engineering 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.
핵심 과제: 추출과 주입
프롬프트 체인에서 1단계는 텍스트를 생성합니다. 2단계는 해당 텍스트의 특정 부분을 입력으로 필요로 합니다. 이때의 과제는 1단계 출력에서 정확히 필요한 필드를 안정적으로 추출하고, 이를 2단계 프롬프트에 깔끔하게 주입하는 것입니다.
1단계가 구조화되지 않은 산문을 반환하면 추출이 불안정해집니다. 해결책은 1단계 프롬프트가 구조화된 출력(일반적으로 JSON)을 반환하도록 설계하여, 이를 구문 분석하고 프로그래밍 방식으로 주입할 수 있게 하는 것입니다.
기계 처리를 위한 1단계 설계
체인에 입력으로 사용할 프롬프트는 항상 구조화된 데이터를 출력해야 합니다. 프롬프트에서 정확한 JSON 스키마를 지정하십시오.
import anthropic
import json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
step1_prompt = '''
<task>
Analyze the customer review below.
</task>
<review>
The onboarding was confusing and took 3 hours. The core feature works great though.
</review>
<output_format>
Return ONLY a JSON object. No other text.
{
"sentiment": "positive|negative|mixed",
"issues": ["string"],
"positives": ["string"],
"priority": "high|medium|low"
}
</output_format>
'''
response = client.messages.create(
model='claude-opus-4-5',
max_tokens=300,
messages=[{'role': 'user', 'content': step1_prompt}]
)
print(response.content[0].text)1단계 출력 구문 분석
1단계에서 JSON을 반환하면 파이썬에서 구문을 분석하고 2단계에 필요한 필드를 추출하십시오.
import json
def parse_step1_output(raw_text):
# Models sometimes wrap JSON in extra text -- strip it
text = raw_text.strip()
# Find the first { and last } to extract JSON object
start = text.find("{")
end = text.rfind("}")
if start != -1 and end != -1 and end > start:
text = text[start:end+1]
try:
return json.loads(text)
except json.JSONDecodeError as e:
raise ValueError("Step 1 output is not valid JSON: " + str(e))
# Example usage
raw = '{"sentiment": "mixed", "issues": ["confusing onboarding"], "positives": ["core feature"], "priority": "high"}'
parsed = parse_step1_output(raw)
print(parsed['issues'])
print(parsed['priority'])추출한 필드를 2단계에 주입하기
구문 분석이 끝나면 특정 필드를 2단계의 프롬프트 템플릿에 주입하십시오. 파이썬 f-문자열이나 템플릿 변수를 사용하십시오.
def build_step2_prompt(parsed_step1):
issues = '\n'.join(f'- {issue}' for issue in parsed_step1['issues'])
priority = parsed_step1['priority']
sentiment = parsed_step1['sentiment']
return f'''
<context>
A customer review was analyzed. Overall sentiment: {sentiment}. Priority: {priority}.
</context>
<task>
Write a customer support response addressing these specific issues:
{issues}
Acknowledge the positives before addressing the issues.
</task>
<output_format>
Plain text response, 3 sentences maximum, professional tone.
</output_format>
'''
parsed = {'sentiment': 'mixed', 'issues': ['confusing onboarding'], 'priority': 'high', 'positives': ['core feature']}
print(build_step2_prompt(parsed))전체 2단계 체인
구문 분석과 주입을 결합한 완전한 2단계 파이프라인은 다음과 같습니다.
import anthropic, json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
def call(prompt, max_tokens=500):
r = client.messages.create(
model='claude-opus-4-5', max_tokens=max_tokens,
messages=[{'role': 'user', 'content': prompt}]
)
return r.content[0].text
def review_response_chain(review_text):
# Step 1: Analyze
step1 = call(f'Analyze this review. Return JSON: {{"sentiment": str, "issues": [str], "priority": str}}\n\nReview: {review_text}')
parsed = json.loads(step1.strip())
# Inject into Step 2
issues_str = ', '.join(parsed['issues'])
step2_prompt = f'Write a 2-sentence support reply. Issues to address: {issues_str}. Priority: {parsed["priority"]}.'
# Step 2: Draft response
reply = call(step2_prompt)
return reply
print(review_response_chain('Login is broken. App crashes on startup.'))중첩된 JSON 주입 처리
1단계에서 중첩된 객체를 반환하는 경우, 주입되는 프롬프트를 간결하게 유지하도록 2단계에 필요한 내용만 추출하십시오.
step1_output = {
'document': {
'title': 'Q3 Report',
'sections': [
{'name': 'Revenue', 'value': '$4.2M', 'change': '+12%'},
{'name': 'Users', 'value': '85,000', 'change': '+5%'},
{'name': 'Churn', 'value': '3.2%', 'change': '-0.8%'}
]
},
'summary': 'Strong revenue quarter with moderate user growth.'
}
# Extract only what Step 2 needs — not the full nested object
def extract_for_step2(data):
sections = data['document']['sections']
metrics = '\n'.join(f"{s['name']}: {s['value']} ({s['change']})" for s in sections)
return {
'metrics': metrics,
'summary': data['summary']
}
step2_input = extract_for_step2(step1_output)
print(step2_input)과도한 주입 피하기
흔히 저지르는 실수는 1단계의 전체 출력을 2단계에 주입하는 것입니다. 이렇게 하면 2단계의 프롬프트가 불필요하게 커지고, 관련 없는 필드 때문에 모델이 혼동할 수 있습니다.
- 잘못된 예:
f'Here is the analysis: {str(all_of_step1_output)}' - 올바른 예: 2단계에 필요한 특정 필드만 추출하고 명확한 레이블과 함께 주입하십시오
2단계에는 필요한 정보를 정확히 필요한 만큼만 전달해야 합니다.
출력에 따른 조건부 분기
구문 분석한 1단계 출력에 따라 실행할 2단계 프롬프트를 선택할 수 있습니다. 이렇게 하면 선형 체인을 분기형 파이프라인으로 바꿀 수 있습니다.
def route_chain(user_message):
# Step 1: Classify intent
classification = json.loads(call(
f'Classify this message as billing, technical, or general. Return JSON: {{"intent": str}}\n\nMessage: {user_message}'
))
intent = classification['intent']
# Route to specialized Step 2 prompt
if intent == 'billing':
prompt = f'You are a billing specialist. Address: {user_message}'
elif intent == 'technical':
prompt = f'You are a senior engineer. Provide technical guidance for: {user_message}'
else:
prompt = f'You are a general support agent. Respond to: {user_message}'
return call(prompt)
print(route_chain('My invoice shows a wrong amount.'))단계 간 상태 누적
단계가 많은 체인에서는 각 단계의 출력을 누적하는 상태 딕셔너리를 유지하십시오.
def run_pipeline(initial_input):
state = {'input': initial_input}
# Step 1
state['entities'] = json.loads(call(
f'Extract entities as JSON: {{"people": [], "companies": []}}\n\n{state["input"]}'
))
# Step 2 uses entities from Step 1
companies_str = ', '.join(state['entities'].get('companies', []))
state['company_types'] = call(
f'Classify these companies as startup/enterprise: {companies_str}'
)
# Step 3 uses output from Steps 1 and 2
state['summary'] = call(
f'Write a 2-sentence summary.\nEntities: {state["entities"]}\nClassifications: {state["company_types"]}'
)
return state
result = run_pipeline('Apple and OpenAI announced a partnership with Elon Musk.')
print(result['summary'])JSON 추출 유틸리티
체인 인프라에서 재사용할 수 있는 추출 유틸리티를 구축하십시오.
import re, json
def extract_json(text):
"Extract JSON from model output, handling extra text around the object."
# Try direct parse first
try:
return json.loads(text.strip())
except json.JSONDecodeError:
pass
# Try finding JSON object by bracket matching
start = text.find("{")
end = text.rfind("}")
if start != -1 and end != -1 and end > start:
try:
return json.loads(text[start:end+1])
except json.JSONDecodeError:
pass
# Try finding JSON array
start = text.find("[")
end = text.rfind("]")
if start != -1 and end != -1 and end > start:
try:
return json.loads(text[start:end+1])
except json.JSONDecodeError:
pass
raise ValueError("Could not extract JSON from: " + text[:200])
print(extract_json('{"key": "value"}'))출력에서 입력으로 이어지는 패턴 테스트
출력에서 입력으로 이어지는 파이프라인에는 두 수준의 테스트가 필요합니다.
- 각 단계 단위 테스트: 1단계가 안정적으로 구문 분석 가능한 JSON을 반환합니까? 2단계가 주어진 추출 입력에 대해 올바른 출력을 생성합니까?
- 체인 통합 테스트: 종단 간 파이프라인이 대표적인 입력에 대해 올바른 결과를 생성합니까?
일관성이 중요한 분류 및 추출 단계에서는 온도를 0으로 설정하여 단계 프롬프트를 결정론적으로 유지하십시오.
def test_step1(review_text, expected_sentiment):
raw = call(f'Analyze review. Return JSON: {{"sentiment": str}}\n\n{review_text}')
parsed = extract_json(raw)
assert parsed['sentiment'] == expected_sentiment, f'Expected {expected_sentiment}, got {parsed["sentiment"]}'
print(f'PASS: sentiment={parsed["sentiment"]}')
# Run unit test for Step 1
test_step1('The product is excellent!', 'positive')
test_step1('This is terrible.', 'negative')빠른 확인
프롬프트 체인의 1단계 결과를 프로그램으로 추출하여 2단계에 주입할 경우, 권장되는 출력 형식은 무엇입니까?
출력에서 입력으로 이어지는 흐름 — 핵심 요점
안정적인 출력에서 입력으로 이어지는 패턴이 프롬프트 체인을 운영 환경에 사용할 수 있게 만듭니다.
- 1단계 프롬프트가 일반적인 설명이 아니라 명시적인 스키마를 포함한 JSON을 반환하도록 설계하십시오
- 주입하기 전에 1단계 출력을 구문 분석하십시오. 마크다운 펜스를 제거하고 JSON 디코딩 오류를 처리하십시오
- 2단계에 필요한 특정 필드만 주입하고 과도한 주입을 피하십시오
- 상태 딕셔너리를 사용하여 더 긴 체인에서 데이터를 누적하고 전달하십시오
- 구문 분석한 출력으로 조건부 분기를 수행하여 특화된 2단계 프롬프트로 전달할 수 있습니다
- 모델 출력의 불일치를 처리하는 재사용 가능한 JSON 추출 유틸리티를 구축하십시오
- 각 단계를 독립적으로 단위 테스트한 다음 전체 파이프라인을 통합 테스트하십시오
자주 묻는 질문
“출력을 입력으로 연결하는 패턴” 강의는 무료인가요?
네 — “출력을 입력으로 연결하는 패턴” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Prompt Engineering 강의 전체를 잠금 해제할 수 있습니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.
“출력을 입력으로 연결하는 패턴”에서 뭘 배우나요?
1단계에서 구조화된 데이터를 추출해 2단계에 주입합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Prompt Engineering을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Prompt Engineering을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Prompt Engineering은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“출력을 입력으로 연결하는 패턴” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Prompt Engineering 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Prompt Engineering 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 프롬프트 연결이란 무엇인가
- 출력을 입력으로 연결하는 패턴
- 순차 변환 연결
- 프롬프트 연결에서 오류 처리