0Pricing
AI Agents · Lesson

Cross-Modal Reasoning Patterns

Grounding text claims in images and synthesizing multi-source multimodal context.

Cross-Modal Reasoning Patterns is a free AI Agents lesson on CoddyKit — lesson 4 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 Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Cross-Modal Reasoning

Cross-modal reasoning occurs when an agent must reconcile information from two or more modalities — text, images, charts, tables — that may agree, contradict, or complement each other. Example: a report text says revenue grew 20%, but the attached chart shows a flat line.

The agent must decide which source is correct, or flag the discrepancy for human review.

Text-Image Grounding

Text-image grounding means verifying that claims made in text can be visually confirmed in an accompanying image. For example: does the product description match the product photo? Does the document mention a table that actually appears in the image?

import anthropic
import base64

def ground_text_in_image(
    text_claim: str,
    image_path: str
) -> dict:
    client = anthropic.Anthropic(api_key='YOUR_API_KEY')
    with open(image_path, 'rb') as f:
        b64 = base64.standard_b64encode(f.read()).decode('utf-8')

    prompt = (
        f'Text claim: "{text_claim}"\n\n'
        'Does the image above support, contradict, or partially support this claim?\n'
        'Return JSON: {"verdict": "support|contradict|partial|insufficient_evidence", '
        '"confidence": 0.0, "evidence": "..."}'
    )
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=256,
        messages=[{'role': 'user', 'content': [
            {'type': 'image', 'source': {'type': 'base64',
              'media_type': 'image/jpeg', 'data': b64}},
            {'type': 'text', 'text': prompt}
        ]}]
    )
    import json
    return json.loads(response.content[0].text)

Chart vs Text Contradiction Detection

A common real-world scenario: a financial report's prose says one thing, but the chart embedded in the document tells a different story. The agent can extract chart data visually and compare it against numeric claims in the text.

def compare_chart_to_text(
    chart_image_path: str,
    text_with_claims: str
) -> dict:
    import anthropic, base64, json
    client = anthropic.Anthropic(api_key='YOUR_API_KEY')
    with open(chart_image_path, 'rb') as f:
        b64 = base64.standard_b64encode(f.read()).decode('utf-8')

    prompt = (
        'The following text makes claims about data.\n'
        f'TEXT: {text_with_claims}\n\n'
        'Compare the chart image to the text claims. '
        'List any contradictions and agreements. '
        'Return JSON: {"agreements": [str], "contradictions": [str], '
        '"verdict": "consistent|inconsistent|partial"}'
    )
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=512,
        messages=[{'role': 'user', 'content': [
            {'type': 'image', 'source': {'type': 'base64',
              'media_type': 'image/jpeg', 'data': b64}},
            {'type': 'text', 'text': prompt}
        ]}]
    )
    return json.loads(response.content[0].text)

Signal Combination Strategies

When signals from multiple modalities agree, increase confidence. When they disagree, apply a conflict resolution strategy: trust the more structured source (charts beat prose for numbers), flag for human review, or ask the LLM to reason about which is more reliable.

SIGNAL_SOURCES = {
    'chart': 0.9,     # high trust for quantitative data
    'table': 0.85,
    'photo': 0.8,
    'prose': 0.6,     # lower trust — may be imprecise or outdated
    'caption': 0.7
}

def combine_signals(signals: list) -> dict:
    """
    signals: list of {'source': str, 'claim': str, 'supports': bool}
    Returns weighted verdict.
    """
    support_weight = 0.0
    total_weight = 0.0
    for sig in signals:
        w = SIGNAL_SOURCES.get(sig['source'], 0.5)
        total_weight += w
        if sig['supports']:
            support_weight += w

    confidence = support_weight / total_weight if total_weight > 0 else 0.0
    return {
        'confidence': round(confidence, 3),
        'verdict': 'supported' if confidence >= 0.6 else 'contested',
        'needs_review': 0.4 <= confidence < 0.6
    }

if __name__ == '__main__':
    signals = [
        {'source': 'chart', 'claim': 'Revenue grew 20%', 'supports': True},
        {'source': 'prose', 'claim': 'Revenue grew 20%', 'supports': False},
    ]
    print(combine_signals(signals))

Text-to-Image Verification Pipeline

A product verification pipeline: given a product description and its photo, check that every key attribute mentioned in the text is visible in the image. Return a structured report of matches and mismatches.

def verify_product_description(
    description: str,
    product_image_path: str
) -> dict:
    import anthropic, base64, json
    client = anthropic.Anthropic(api_key='YOUR_API_KEY')
    with open(product_image_path, 'rb') as f:
        b64 = base64.standard_b64encode(f.read()).decode('utf-8')

    prompt = (
        f'Product description:\n{description}\n\n'
        'For each attribute mentioned in the description (color, shape, material, '
        'size, features), check whether it is visible in the product photo.\n'
        'Return JSON: {"verified": [{"attribute": str, "status": str}], '
        '"unverified": [str], "overall_match": float}\n'
        'status: confirmed / contradicted / not_visible\n'
        'overall_match: 0.0-1.0'
    )
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=512,
        messages=[{'role': 'user', 'content': [
            {'type': 'image', 'source': {'type': 'base64',
              'media_type': 'image/jpeg', 'data': b64}},
            {'type': 'text', 'text': prompt}
        ]}]
    )
    return json.loads(response.content[0].text)

Document + Image Cross-Reference

When analysing scanned documents, the OCR text and the underlying image both exist. Cross-reference them: does the extracted text match what is visually present? Mismatches can indicate OCR errors that need correction.

def crossref_ocr_with_image(
    ocr_text: str,
    document_image_path: str
) -> dict:
    import anthropic, base64, json
    client = anthropic.Anthropic(api_key='YOUR_API_KEY')
    with open(document_image_path, 'rb') as f:
        b64 = base64.standard_b64encode(f.read()).decode('utf-8')

    prompt = (
        f'The OCR system produced this text from the document image:\n\n'
        f'{ocr_text}\n\n'
        'Compare the OCR text to what you actually see in the image. '
        'Identify any OCR errors, missed text, or hallucinated characters.\n'
        'Return JSON: {"ocr_errors": [{"incorrect": str, "correct": str}], '
        '"missed_sections": [str], "accuracy_estimate": float}'
    )
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=512,
        messages=[{'role': 'user', 'content': [
            {'type': 'image', 'source': {'type': 'base64',
              'media_type': 'image/jpeg', 'data': b64}},
            {'type': 'text', 'text': prompt}
        ]}]
    )
    return json.loads(response.content[0].text)

Multi-Source Reasoning Agent

A multi-source reasoning agent systematically collects evidence from each modality, combines signals, and produces a final conclusion with a confidence score. It cites which sources supported its conclusion and which contradicted it.

def multi_source_reasoning(
    claim: str,
    evidence_sources: list  # list of {'type': 'text'|'image', 'content': str|path}
) -> dict:
    import anthropic, base64, json
    client = anthropic.Anthropic(api_key='YOUR_API_KEY')
    content_blocks = [
        {'type': 'text',
         'text': f'Evaluate this claim using ALL sources below:\nClaim: "{claim}"\n'}
    ]
    for i, src in enumerate(evidence_sources):
        if src['type'] == 'text':
            content_blocks.append(
                {'type': 'text', 'text': f'Source {i+1} (text): {src["content"]}'}
            )
        elif src['type'] == 'image':
            with open(src['content'], 'rb') as f:
                b64 = base64.standard_b64encode(f.read()).decode('utf-8')
            content_blocks.append(
                {'type': 'text', 'text': f'Source {i+1} (image):'}
            )
            content_blocks.append(
                {'type': 'image', 'source': {'type': 'base64',
                  'media_type': 'image/jpeg', 'data': b64}}
            )
    content_blocks.append({'type': 'text', 'text':
        'Return JSON: {"verdict": str, "confidence": float, '
        '"supporting_sources": [int], "contradicting_sources": [int]}'
    })
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=512,
        messages=[{'role': 'user', 'content': content_blocks}]
    )
    return json.loads(response.content[0].text)

Image-to-Text Fact Generation

Sometimes you have an image and need to generate structured facts from it for downstream text-based reasoning. Extract quantitative facts from charts and tables as JSON so they can be mathematically verified against text claims.

def extract_facts_from_chart(chart_path: str) -> dict:
    import anthropic, base64, json
    client = anthropic.Anthropic(api_key='YOUR_API_KEY')
    with open(chart_path, 'rb') as f:
        b64 = base64.standard_b64encode(f.read()).decode('utf-8')

    prompt = (
        'Extract all quantitative data from this chart. '
        'Return JSON with: chart_type, x_axis_label, y_axis_label, '
        'and data_points as [{label: str, value: float}].\n'
        'Also extract any trend: increasing/decreasing/stable/volatile.'
    )
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=512,
        messages=[{'role': 'user', 'content': [
            {'type': 'image', 'source': {'type': 'base64',
              'media_type': 'image/jpeg', 'data': b64}},
            {'type': 'text', 'text': prompt}
        ]}]
    )
    return json.loads(response.content[0].text)

Confidence Threshold Routing

After cross-modal reasoning, route the result based on confidence: high confidence → auto-approve, medium → flag for optional review, low → escalate to human. Never auto-approve conflicting signals regardless of confidence score.

def route_cross_modal_result(result: dict) -> str:
    confidence = result.get('confidence', 0.0)
    has_contradiction = bool(result.get('contradicting_sources'))

    if has_contradiction:
        return 'ESCALATE'
    if confidence >= 0.85:
        return 'AUTO_APPROVE'
    if confidence >= 0.6:
        return 'OPTIONAL_REVIEW'
    return 'ESCALATE'

# Example routing table:
# confidence >= 0.85, no contradiction -> AUTO_APPROVE
# confidence 0.6-0.85, no contradiction -> OPTIONAL_REVIEW
# any contradiction, or confidence < 0.6 -> ESCALATE

def handle_routing(claim: str, evidence_sources: list):
    result = multi_source_reasoning(claim, evidence_sources)
    action = route_cross_modal_result(result)
    print(f'Claim: "{claim}"')
    print(f'Verdict: {result["verdict"]} (confidence={result["confidence"]:.2f})')
    print(f'Action: {action}')
    return action, result

Handling Insufficient Visual Evidence

Sometimes an image is too low-resolution, blurry, or partially occluded to provide useful evidence. The agent must detect this and abstain from making a cross-modal conclusion rather than hallucinating one.

def assess_image_evidence_quality(
    image_path: str,
    claim: str
) -> dict:
    import anthropic, base64, json
    client = anthropic.Anthropic(api_key='YOUR_API_KEY')
    with open(image_path, 'rb') as f:
        b64 = base64.standard_b64encode(f.read()).decode('utf-8')

    prompt = (
        f'Claim to verify: "{claim}"\n\n'
        'Assess whether this image provides sufficient evidence to evaluate the claim.\n'
        'Consider: image quality, relevance, completeness, and readability.\n'
        'Return JSON: {"sufficient": bool, "quality_issues": [str], '
        '"usable_evidence": str}'
    )
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=256,
        messages=[{'role': 'user', 'content': [
            {'type': 'image', 'source': {'type': 'base64',
              'media_type': 'image/jpeg', 'data': b64}},
            {'type': 'text', 'text': prompt}
        ]}]
    )
    return json.loads(response.content[0].text)

Building a Cross-Modal Fact-Checker

Putting it all together: a document fact-checker that takes a report (text + embedded images) and verifies every quantitative claim in the text against the supporting charts and tables. Returns a structured verification report.

def fact_check_report(
    report_text: str,
    image_paths: list
) -> dict:
    import re
    # Extract numeric claims from text (simple regex pattern)
    claim_pattern = r'[A-Z][^.!?]*[0-9][%$][^.!?]*[.!?]'
    claims = re.findall(claim_pattern, report_text)

    results = []
    for claim in claims:
        sources = [
            {'type': 'text', 'content': report_text},
        ] + [{'type': 'image', 'content': p} for p in image_paths]

        reasoning = multi_source_reasoning(claim, sources)
        action = route_cross_modal_result(reasoning)
        results.append({
            'claim': claim,
            'verdict': reasoning['verdict'],
            'confidence': reasoning['confidence'],
            'action': action
        })

    total = len(results)
    auto_approved = sum(1 for r in results if r['action'] == 'AUTO_APPROVE')
    return {
        'total_claims': total,
        'auto_approved': auto_approved,
        'escalated': total - auto_approved,
        'details': results
    }

Knowledge Check

When text and chart signals contradict each other, what should the cross-modal agent do according to best practices?

Recap: Cross-Modal Reasoning Patterns

You have completed this lesson. Key points:

  • Text-image grounding: verify text claims against visual evidence
  • Signal combination: weighted trust (charts > prose for numbers), structured sources beat unstructured
  • Contradiction detection: always escalate to human — never auto-resolve contradictions
  • Confidence routing: auto-approve (high) → optional review (medium) → escalate (low or contradiction)
  • Insufficient evidence: abstain rather than hallucinate a cross-modal conclusion

Next course: IoT and Sensor-Driven Agents — processing real-world data streams with MQTT.

Frequently asked questions

Is the “Cross-Modal Reasoning Patterns” lesson free?

Yes — the full text of “Cross-Modal Reasoning Patterns” is free to read here on the web, and the AI Agents 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 Agents course, upgrade to CoddyKit PRO.

What will I learn in “Cross-Modal Reasoning Patterns”?

Grounding text claims in images and synthesizing multi-source multimodal context. You practise AI Agents 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 Agents?

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

How long does the “Cross-Modal Reasoning 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 Agents lesson?

Yes. Every AI Agents 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. Image + Text Agents with Claude Vision and GPT-4V
  2. Audio + Text Agent Workflows
  3. Video Understanding in Agents
  4. Cross-Modal Reasoning Patterns
← Back to AI Agents