0Pricing
AI Prompt Engineering · Lesson

Output-to-Input Patterns

Extracting structured data from Step 1 to inject into Step 2.

Output-to-Input Patterns is a free AI Prompt Engineering lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Prompt Engineering learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Core Challenge: Extracting and Injecting

In a prompt chain, Step 1 produces text. Step 2 needs a specific piece of that text as input. The challenge is reliably extracting exactly the right field from Step 1's output and injecting it cleanly into Step 2's prompt.

If Step 1 returns unstructured prose, extraction is fragile. The solution is to design Step 1 prompts to return structured output — typically JSON — that can be parsed and injected programmatically.

Designing Step 1 for Machine Consumption

A prompt intended to feed a chain should always output structured data. Specify the exact JSON schema in the prompt:

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)

Parsing Step 1 Output

Once Step 1 returns JSON, parse it in Python and extract the fields needed for Step 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'])

Injecting Extracted Fields into Step 2

After parsing, inject specific fields into Step 2's prompt template. Use Python f-strings or template variables:

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))

Full Two-Step Chain

Combining parse and inject into a complete two-step pipeline:

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.'))

Handling Nested JSON Injection

When Step 1 returns nested objects, extract only what Step 2 needs to keep the injected prompt concise:

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)

Avoiding Over-Injection

A common mistake is injecting the entire Step 1 output into Step 2. This bloats Step 2's prompt and can confuse the model with irrelevant fields.

  • Bad: f'Here is the analysis: {str(all_of_step1_output)}'
  • Good: Extract only the specific fields Step 2 needs and inject them with clear labels

Step 2 should receive exactly the information it needs — no more, no less.

Conditional Branching Based on Output

Parsed Step 1 output can control which Step 2 prompt runs — turning a linear chain into a branching pipeline:

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.'))

Accumulating State Across Steps

For longer chains, maintain a state dictionary that accumulates outputs from each step:

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 Extraction Utilities

Build a reusable extraction utility for your chain infrastructure:

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"}'))

Testing Output-to-Input Patterns

Output-to-input pipelines need two levels of testing:

  • Unit test each step: Does Step 1 reliably return parseable JSON? Does Step 2 produce the right output for a given extracted input?
  • Integration test the chain: Does the end-to-end pipeline produce correct results for representative inputs?

Keep step prompts deterministic by using temperature=0 for classification and extraction steps where consistency matters.

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')

Quick Check

What is the recommended output format for Step 1 of a prompt chain when the result will be programmatically extracted and injected into Step 2?

Output-to-Input — Key Takeaways

Reliable output-to-input patterns are what make prompt chains production-ready:

  • Design Step 1 prompts to return JSON with an explicit schema — not prose
  • Parse Step 1 output before injection: strip markdown fences, handle JSONDecodeError
  • Inject only the specific fields Step 2 needs — avoid over-injection
  • Use state dictionaries to accumulate and pass data across longer chains
  • Parsed output can drive conditional branching to route to specialized Step 2 prompts
  • Build reusable JSON extraction utilities that handle model output inconsistencies
  • Unit test each step independently, then integration test the full pipeline

Frequently asked questions

Is the “Output-to-Input Patterns” lesson free?

Yes — the full text of “Output-to-Input Patterns” is free to read here on the web, and the AI Prompt Engineering course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Prompt Engineering course, upgrade to CoddyKit PRO.

What will I learn in “Output-to-Input Patterns”?

Extracting structured data from Step 1 to inject into Step 2. You practise AI Prompt Engineering with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AI Prompt Engineering?

No prior experience is required. AI Prompt Engineering on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Output-to-Input Patterns” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AI Prompt Engineering lesson?

Yes. Every AI Prompt Engineering lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. What Is Prompt Chaining?
  2. Output-to-Input Patterns
  3. Sequential Transformation Chains
  4. Error Handling in Prompt Chains
← Back to AI Prompt Engineering