0Pricing
AI Prompt Engineering · Lesson

Visual Question Answering

Asking specific questions about image content, quantities, and attributes.

Visual Question Answering 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.

Visual Question Answering

Visual Question Answering (VQA) is the task of answering natural language questions about an image. Unlike image description (which describes everything), VQA focuses the model on answering a specific question.

VQA prompts are precise, direct, and often require counting, identifying, comparing, or reasoning about visual content. The quality of the prompt determines whether you get a precise, useful answer or a vague general response.

Basic VQA Prompt Structure

A VQA prompt pairs an image with a specific question. The key is making the question precise enough to produce a direct, usable answer:

import anthropic, base64

client = anthropic.Anthropic(api_key='YOUR_API_KEY')

def ask_about_image(image_path, question, answer_format='Direct answer. No extra explanation.'):
    with open(image_path, 'rb') as f:
        img_b64 = base64.standard_b64encode(f.read()).decode('utf-8')

    prompt = f'{question}\n\n{answer_format}'

    r = client.messages.create(
        model='claude-opus-4-5', max_tokens=150,
        messages=[{'role': 'user', 'content': [
            {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/jpeg', 'data': img_b64}},
            {'type': 'text', 'text': prompt}
        ]}]
    )
    return r.content[0].text

# Example VQA calls (replace image.jpg with actual image)
print('VQA function defined. Ready for image questions.')

Counting Questions

Counting is a common VQA task. Precise counting prompts produce more accurate results than vague ones:

# Vague (bad):
vague_prompt = 'How many people are there?'

# Precise (good): specifies what counts and what does not
counting_prompt = '''
How many people are visible in this image?
Count only: people whose faces OR bodies are at least 50% visible.
Do NOT count: people who are heavily cropped, cut off at the edge, or only partially visible.
Return a single number.
'''

# Even more precise: handles partial visibility explicitly
precise_count = '''
Count the number of distinct individuals visible in this image.
If a person is partially obscured, count them if more than half their body is visible.
Return JSON: {"count": integer, "partially_visible": integer, "notes": "string or null"}
'''

print('Counting prompts: vague vs precise.')
print('Precise prompts define edge cases explicitly.')

Brand and Logo Identification

Identifying brand logos in images is a common product analysis task. The prompt must specify what to look for and what format to return:

logo_prompt = '''
Identify all visible brand logos, company names, and product labels in this image.

For each, note:
- Brand/company name
- Where it appears in the image (top-left, center, on a product, etc.)
- Confidence: high (clearly legible) | medium (partially visible) | low (partially obscured)

Return JSON: {"brands": [{"name": str, "location": str, "confidence": str}]}
If no logos are visible, return: {"brands": []}
'''

import anthropic, base64, json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')

def identify_brands(image_path):
    with open(image_path, 'rb') as f:
        img_b64 = base64.standard_b64encode(f.read()).decode('utf-8')
    r = client.messages.create(
        model='claude-opus-4-5', max_tokens=200,
        messages=[{'role': 'user', 'content': [
            {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/jpeg', 'data': img_b64}},
            {'type': 'text', 'text': logo_prompt}
        ]}]
    )
    return json.loads(r.content[0].text)

print('Brand identification function defined.')

Emotion and Expression Recognition

Identifying emotional expressions in images requires careful prompt design that acknowledges uncertainty:

emotion_prompt = '''
Describe the emotional expression of the person in this image.

Assess:
- Primary emotion: (happy, sad, angry, surprised, fearful, disgusted, neutral, or other)
- Intensity: (low, moderate, high)
- Confidence: (high if expression is clear, medium if subtle, low if face is obscured or turned away)
- Evidence: which specific facial features support your assessment

Return JSON:
{
  "primary_emotion": str,
  "intensity": str,
  "confidence": str,
  "evidence": str,
  "secondary_emotion": str or null
}

If no person or face is clearly visible, return: {"primary_emotion": null, "confidence": "none", "reason": str}
'''

print(emotion_prompt)

Spatial Relationship Questions

Questions about where objects are relative to each other require explicit spatial vocabulary in the prompt:

spatial_prompt = '''
Answer questions about the spatial relationships of objects in this image.
Use these spatial terms consistently:
- Position in frame: top-left, top-center, top-right, middle-left, center, middle-right, bottom-left, bottom-center, bottom-right
- Relative position: in front of, behind, to the left of, to the right of, above, below, overlapping
- Distance: in the foreground, in the midground, in the background

Question: {question}

Answer in one or two sentences using the spatial vocabulary above.
'''

# Example questions:
questions = [
    'Where is the red cup relative to the laptop?',
    'Is the plant in the foreground or background?',
    'What object is to the left of the person?'
]

for q in questions:
    print(spatial_prompt.replace('{question}', q)[:200])
    print('---')

Quality and Condition Assessment

Assessing the quality or condition of objects in images — useful for product inspection, real estate assessment, and quality control:

condition_prompt = '''
Assess the condition of the main subject in this image.

Rate on these dimensions (1-5 scale, 5=excellent):
- Physical condition: (1=heavily damaged, 5=like new)
- Cleanliness: (1=very dirty, 5=spotless)
- Completeness: (1=major parts missing, 5=fully intact)

For each rating, provide one-sentence evidence.

Return JSON:
{
  "physical_condition": {"score": int, "evidence": str},
  "cleanliness": {"score": int, "evidence": str},
  "completeness": {"score": int, "evidence": str},
  "overall_grade": "excellent|good|fair|poor",
  "recommendation": str
}
'''

print('Condition assessment prompt defined.')
print('Useful for: product inspection, real estate, equipment maintenance.')

Yes/No VQA Questions

Binary yes/no questions need prompts that prevent the model from giving a hedged prose answer when you need a simple boolean:

def yes_no_question(image_path, question):
    with open(image_path, 'rb') as f:
        img_b64 = base64.standard_b64encode(f.read()).decode('utf-8')

    prompt = f'''
Answer this yes/no question about the image.
Return JSON: {{"answer": "yes|no", "confidence": "high|medium|low", "reason": str}}
Do NOT answer with maybe, possibly, or a hedged statement.
If you genuinely cannot determine the answer, return {{"answer": "unclear", "confidence": "low", "reason": str}}

Question: {question}
'''

    r = client.messages.create(
        model='claude-opus-4-5', max_tokens=100,
        messages=[{'role': 'user', 'content': [
            {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/jpeg', 'data': img_b64}},
            {'type': 'text', 'text': prompt}
        ]}]
    )
    return json.loads(r.content[0].text)

# Example: 'Is there a safety helmet visible in the image?'
print('Yes/no VQA function defined.')

Chaining VQA Questions

Multiple VQA questions about the same image can be chained in a single prompt to reduce API calls:

multi_question_prompt = '''
Answer all of the following questions about this image.
Return a JSON object where each key is the question ID.

Questions:
1. How many people are visible?
2. What is the approximate age range of the youngest person?
3. Is there any food visible in the image?
4. What is the dominant color in the image?
5. Is the setting indoors or outdoors?

Return JSON:
{
  "q1": {"answer": str},
  "q2": {"answer": str},
  "q3": {"answer": "yes|no", "details": str or null},
  "q4": {"answer": str},
  "q5": {"answer": "indoors|outdoors|unclear"}
}
'''

print('Multi-question VQA prompt — answers 5 questions in one API call.')

Handling VQA Uncertainty

VQA questions sometimes cannot be answered with certainty — the image may be blurry, the relevant element may be partially obscured, or the answer may be genuinely ambiguous. Prompt for explicit uncertainty rather than forcing a guess:

uncertainty_vqa_prompt = '''
Answer this question about the image as precisely as possible.
If the answer is not clearly visible or is ambiguous, say so explicitly.

Question: {question}

Return JSON:
{
  "answer": str,
  "confidence": "high|medium|low|cannot_determine",
  "limitation": str or null
}

For confidence levels:
- high: Answer is clearly visible and unambiguous
- medium: Visible but some uncertainty
- low: Partially visible or requires inference
- cannot_determine: Not enough visual information

Question: What brand is printed on the water bottle?
'''

print(uncertainty_vqa_prompt)

Domain-Specific VQA Prompts

Different domains require different VQA vocabulary and measurement standards. Domain-specific prompts produce more accurate, actionable answers:

# Manufacturing quality control VQA
qc_prompt = '''
Inspect this product image for quality defects.
Answer each question:
1. Are there any visible scratches or surface damage? (yes/no + location)
2. Is the product alignment within expected tolerance? (yes/no)
3. Are all required labels/markings present? (yes/no + list missing ones)
4. Overall QC result: PASS or FAIL?

Return JSON:
{"scratches": {"present": bool, "location": str or null},
 "alignment_ok": bool,
 "labels_complete": bool, "missing_labels": [str],
 "qc_result": "PASS|FAIL",
 "fail_reasons": [str]}
'''

# Food safety VQA  
food_prompt = '''
Inspect this food preparation image.
1. Are gloves being worn? 2. Is hair covered? 3. Any visible contamination risk?
Return JSON: {"gloves": bool, "hair_covered": bool, "contamination_risk": bool, "details": str}
'''

print("Domain-specific QC and food safety VQA prompts defined.")

Quick Check

Which VQA prompt is most likely to produce a precise, usable answer when counting objects in an image?

VQA Prompts — Key Takeaways

Effective Visual Question Answering requires precisely engineered prompts:

  • Make questions specific and direct — avoid vague terms like some or various
  • Define edge cases explicitly for counting questions (what counts as partially visible?)
  • Specify exact output format — JSON, single number, yes/no — to prevent hedged prose answers
  • Include confidence levels for all answers so uncertain outputs can be flagged
  • Batch multiple questions about the same image into one call to reduce API costs
  • For binary yes/no questions, explicitly prevent hedged responses with an unclear escape hatch
  • Domain-specific VQA (medical, legal, product) requires domain vocabulary in the prompt

Frequently asked questions

Is the “Visual Question Answering” lesson free?

Yes — the full text of “Visual Question Answering” 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 “Visual Question Answering”?

Asking specific questions about image content, quantities, and attributes. 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 “Visual Question Answering” 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. Image Description and Captioning Prompts
  2. Visual Question Answering
  3. Multi-Image Comparison Prompts
  4. OCR and Document Analysis Prompts
← Back to AI Prompt Engineering