We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Multimodal Search

Search has a problem: users don't always ask with text. Instead of typing, "What should I do if my leg is turning purple?" they want to ask, "What should I do?" and upload a photo of their purple leg.

Some LLMs are multimodal: they can understand both text and images, which opens up new search possibilities. One way to handle non-text input in RAG is multimodal query rewriting. It's as easy as it sounds: we ask the LLM to do the rewrite.

Analyze this image and rewrite the text query for better search results.

Image: [Uploaded image]

Text Query: "{text_query}"

Instructions:

  • Describe what you see in the image
  • Combine visual and textual information
  • Generate searchable keywords
  • Focus on movie-specific details (actors, scenes, style)

Assignment

Implement multimodal query rewriting using a multimodal model on OpenRouter to convert an image and a text query into a better searchable query.

  1. mime, _ = mimetypes.guess_type(args.image)
    mime = mime or "image/jpeg"
    
  2. Given the included image and text query, rewrite the text query to improve search results from a movie database. Make sure to:
    - Synthesize visual and textual information
    - Focus on movie-specific details (actors, scenes, style, etc.)
    - Return only the rewritten query, without any additional commentary
    
  3. import base64
    
    data_url = f"data:{mime};base64,{base64.b64encode(img).decode()}"
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": system_prompt.strip()},
                {"type": "image_url", "image_url": {"url": data_url}},
                {"type": "text", "text": args.query.strip()},
            ],
        }
    ]
    
  4. content = response.choices[0].message.content
    print(f"Rewritten query: {content.strip()}")
    if response.usage is not None:
        print(f"Total tokens:    {response.usage.total_tokens}")
    

If everything seems to be working, submit the CLI tests.