liveBook · Manning

Visual question answering

As explained in Data Analysis with LLMs

A visual question-answering system is a system that answers natural-language questions about the content of an image or other visual input.

Visual question answering answers a natural-language question about an image. It combines an image URL and question as multimodal input, then returns the answer as text. section 6.2.1

A visual question-answering request contains:

Classifying fruit images

To find banana pictures for a logo project, ask “Is this a banana ("Yes","No")?” for each image URL and retain images receiving “Yes.” This turns visual question answering into a simple classification method. section 6.2.3

Listing 6.1 Answering questions about images via language models
import argparse
import openai
import time

client = openai.OpenAI()

def analyze_image(image_url, question):       #1
    """ Use language model to answer questions about image.
    
    Args:
        image_url: URL leading to image.
        question: question about image.
    
    Returns:
        Answer generated by the language model.
    """
    for nr_retries in range(1, 4):
        try:
            response = client.chat.completions.create(
                model='gpt-4o',
                messages=[                  #2
                    {'role':'user', 'content':[
                        {'type':'text', 'text':question}, 
                        {'type':'image_url', 'image_url':{
                            'url':image_url
                            }
                        }]
                    }]
                )
            return response.choices[0].message.content
        except:
            time.sleep(nr_retries * 2)
    raise Exception('Cannot query OpenAI model!')

if __name__ == '__main__':
    
    parser = argparse.ArgumentParser()                   #3
    parser.add_argument('imageurl', type=str, help='URL to image')
    parser.add_argument('question', type=str, help='Question about image')
    args = parser.parse_args()
    
    answer = analyze_image(args.imageurl, args.question)
    print(answer)

A short Python function passes the image URL and question to the chat completions endpoint, then prints the generated answer. section 6.2.2

How Data Analysis with LLMs covers it

How deep it goes
Explains multimodal message structure and Python API usage, but stops short of describing model internals.
Examples
Demonstrates an apple image, a banana question, fruit repositories, and repeated Yes-or-No questions over image URLs.
What you can do after
Build it from scratch with Python by sending an image URL and question to GPT-4o and displaying its text answer.
How it connects
Connects multimodal prompts, image classification, natural-language questions, and the chat completions endpoint.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data Analysis with LLMs. The section links point to the parts of the book it draws on.