Making a Text-Only Model Understand Screenshots: Hook-Based Interception and Image Transcription

    This article explains how to let text-only language models work with screenshots without interrupting the existing conversation. By intercepting image attachments with lifecycle hooks, sending them to a multimodal model for structured transcription, and appending the result to the original prompt, developers can preserve their preferred text model while adding essential visual context. The article covers implementation steps, caching, privacy, reliability, cost, transcription quality, and the limits of text-based image descriptions.

    1. The Problem

    More developers are using AI coding tools for everyday work. These tools typically have two layers:

    • An outer shell that reads and writes files, runs commands, and invokes tools.
    • An underlying language model that understands requests and generates content.

    To control costs, teams often choose different models for different tasks. Text-only models are relatively inexpensive and perform reliably for coding, refactoring, and debugging logical problems, so they are widely used.

    Their limitation is straightforward: they do not accept image input. When a user pastes a screenshot into a conversation, the shell may leave only a placeholder such as [Unsupported Image]. The model never sees the image, but it may still respond based on incomplete context. This can be more misleading than returning an explicit error.

    2. Common Image-Based Workflows

    Images are common inputs in software development, especially in the following scenarios:

    • Frontend debugging: A screenshot contains an error dialog, console output, or unexpected styling, and the developer wants the model to identify the cause.
    • Design-to-code work: A designer provides a UI screenshot, and the developer wants the model to generate the corresponding structure and styles.
    • Automated test evaluation: A test process captures the current page state, and the model must determine whether it matches the expected result.
    • Document information extraction: Scans of receipts, contracts, or tables contain fields that need to be extracted for further processing.

    All of these tasks depend on visual information. If the image is lost in the input pipeline, subsequent reasoning and code generation lack the necessary evidence.

    3. Two Conventional Approaches and Their Limitations

    There are two common ways to deal with the image limitations of text-only models.

    Approach 1: Extract Text and Paste It Manually

    A developer can use an optical character recognition tool to extract text from the screenshot and then copy the result into the conversation. This has several drawbacks:

    1. Every image requires multiple manual steps.
    2. Only the text is preserved; layout, colors, component hierarchy, and relative positions are lost.
    3. Charts and flow diagrams are difficult to represent accurately with plain text.

    Approach 2: Switch to a Multimodal Model

    A multimodal model can process the image directly, but switching models interrupts the current conversation. The original context may not be available in the new session, forcing the developer to describe the problem again and fragmenting the workflow.

    Both approaches require developers to adapt to the tool’s input limitations instead of allowing the tool to adapt to their workflow. The image-processing step should therefore be automated.

    4. Core Idea: Translate Images at the Model Entry Point

    Many AI coding tools are extensible. They provide lifecycle hooks that allow custom logic to run at specific stages, such as before a user prompt is submitted, before or after a tool call, or when a session ends. Hooks decouple application logic from the core reasoning process, allowing developers to change the data flow without modifying the model itself.

    The workflow can be designed as follows:

    1. User input (text + image)
    2. │
    3. ▼
    4. [Lifecycle hook] Detect image attachments and save them to a local cache
    5. │
    6. ▼
    7. [Visual transcription module] Call a multimodal model to generate structured text
    8. │
    9. ▼
    10. Rewrite the prompt: original instruction + image transcription
    11. │
    12. ▼
    13. Text-only language model performs reasoning and returns code or analysis

    The key principle is that the text-only model remains the primary reasoning engine. The multimodal model is used only as a translator. This separation preserves the developer’s existing conversation context.

    The quality of the transcription directly affects the result. Simple OCR is not enough because it loses structural information. The transcription prompt should require the model to:

    • Preserve all visible text verbatim.
    • Describe the layout and component hierarchy.
    • List error types and locations separately.
    • Mark content that cannot be read.
    • Describe only visible information and avoid unsupported assumptions.

    5. Implementation Steps

    The implementation can be divided into four stages.

    5.1 Detect Image Attachments

    The event received by the hook contains the user input and a list of attachments. The handler should iterate through the attachments and distinguish images from other content. Only images enter the transcription workflow; all other content remains unchanged.

    5.2 Persist and Cache Images Locally

    After an image is saved locally, use its content hash as the cache key. A hash avoids collisions between different images with the same filename. It also allows the system to reuse the result when the same image appears again, reducing unnecessary model calls.

    5.3 Call a Multimodal Model for Transcription

    The following is an example transcription module. The API endpoint and key are read from environment variables. The request structure must be adjusted according to the documentation of the selected service.

    1. import base64
    2. import hashlib
    3. import json
    4. import os
    5. import pathlib
    6. import urllib.request
    7. CACHE_DIR = pathlib.Path(os.environ.get("VISION_CACHE_DIR", ".vision_cache"))
    8. VISION_API_URL = os.environ["VISION_API_URL"] # Multimodal service endpoint
    9. VISION_API_KEY = os.environ["VISION_API_KEY"] # Inject the key through the environment
    10. PROMPT = (
    11. "Describe this image objectively:\n"
    12. "1. Extract all visible text verbatim and preserve its original form;\n"
    13. "2. Describe the layout and component hierarchy;\n"
    14. "3. If the image contains an error, list the error type, filename, and line number separately;\n"
    15. "4. Mark unreadable content as 'Unreadable';\n"
    16. "5. Describe only what is visible in the image and do not speculate."
    17. )
    18. def describe_image(image_path: str) -> str:
    19. data = pathlib.Path(image_path).read_bytes()
    20. cache_key = hashlib.sha256(data).hexdigest()
    21. CACHE_DIR.mkdir(parents=True, exist_ok=True)
    22. cache_file = CACHE_DIR / f"{cache_key}.txt"
    23. if cache_file.exists():
    24. return cache_file.read_text(encoding="utf-8")
    25. # This request structure is illustrative. Follow the selected service's documentation.
    26. payload = {
    27. "messages": [{
    28. "role": "user",
    29. "content": [
    30. {"type": "text", "text": PROMPT},
    31. {"type": "image", "data": base64.b64encode(data).decode("ascii")},
    32. ],
    33. }]
    34. }
    35. req = urllib.request.Request(
    36. VISION_API_URL,
    37. data=json.dumps(payload).encode("utf-8"),
    38. headers={
    39. "Authorization": f"Bearer {VISION_API_KEY}",
    40. "Content-Type": "application/json",
    41. },
    42. )
    43. with urllib.request.urlopen(req, timeout=60) as resp:
    44. result = json.loads(resp.read())
    45. text = extract_text(result) # Extract the response according to the service documentation
    46. cache_file.write_text(text, encoding="utf-8")
    47. return text

    5.4 Rewrite the Prompt and Return It

    Once the hook receives the transcription, it appends the description to the original instruction. Multiple images should be numbered so the model can distinguish their sources.

    1. def on_user_prompt(event: dict) -> dict:
    2. """Process image attachments before sending the prompt to a text-only model.
    3. Replace the event structure with the definition used by the actual hook API.
    4. """
    5. remaining, descriptions = [], []
    6. for attachment in event.get("attachments", []):
    7. if attachment.get("type") == "image":
    8. descriptions.append(describe_image(attachment["path"]))
    9. else:
    10. remaining.append(attachment)
    11. if descriptions:
    12. blocks = [
    13. f"[Image transcription {i}]\n{text}"
    14. for i, text in enumerate(descriptions, start=1)
    15. ]
    16. event["prompt"] = event["prompt"] + "\n\n" + "\n\n".join(blocks)
    17. event["attachments"] = remaining
    18. return event

    6. Engineering Considerations

    A solution that works in a demonstration still requires additional engineering before it can support everyday development.

    Security and Privacy

    Screenshots often contain API keys, customer data, identity information, or other sensitive content. Apply redaction before processing, such as masking tokens with known formats. Inject keys only through environment variables or a secret-management service.

    Restrict access to the cache directory and configure a periodic cleanup policy. Do not record image contents or full transcriptions in logs.

    Reliability

    External requests can time out or fail. The transcription module should define a timeout and retry retryable errors a limited number of times.

    If transcription fails, do not silently discard the image. Insert an explicit message into the prompt, such as:

    1. Image transcription failed. Please verify the image content.

    This makes the missing information visible to both the model and the user.

    Cost and Latency

    Reuse cached results when the same image appears again. Trigger transcription only for image attachments. When multiple images are submitted, process them in parallel to reduce waiting time.

    Transcription Quality

    Important numbers, error codes, and code snippets are especially easy to transcribe incorrectly and should be checked manually. For critical information, the system can request two transcriptions with different prompts and compare the results. Differences should then be reviewed by a person.

    Context Length

    A large screenshot may produce a long transcription. Set a maximum description length. If the limit is exceeded, truncate the result and mark that truncation occurred so the transcription does not consume too much of the model’s context window.

    7. Common Problems and Solutions

    The following issues frequently appear in practice:

    1. Important details are summarized away. The transcription says that the page shows an error but omits the error code and line number. Explicitly require verbatim text extraction in the prompt.
    2. Images are silently discarded. If the hook skips an attachment after an exception, the model has no indication that information is missing. Insert an explicit placeholder when processing fails.
    3. Cache collisions occur. Using filenames as cache keys allows different images to overwrite one another. Use a content hash instead.
    4. The hook blocks the main workflow. Long transcription requests can make the interface feel unresponsive. Use timeouts, show processing progress, or generate a quick summary for large images first.
    5. The order of multiple images becomes unclear. The model may not know which transcription belongs to which image. Number each transcription and reference those numbers in the prompt.
    6. The transcription includes speculation. A vision model may fill in content that is difficult to read. Require it to distinguish visible content from unreadable content, and preserve that distinction when building the final prompt.

    8. Scope and Alternatives

    This approach solves the problem of giving a text-only model information contained in an image. It does not fully replace direct visual reasoning.

    Tasks involving pixel-level alignment, exact color values, or precise spacing are difficult to express accurately in text. For these cases, using a multimodal model directly is usually more reliable.

    When the image source is controllable, structured data is preferable. For example, if a design can be exported as component descriptions or style variables, providing that data directly will generally be more accurate and efficient than relying on a screenshot.

    9. Conclusion

    The key to supporting images in a text-only model workflow is to automate the translation step rather than requiring manual model switching or manual transcription.

    A lifecycle hook can intercept image attachments, send them to a multimodal model for structured description, and append the result to the original prompt. This restores essential visual context without interrupting the conversation or changing the primary reasoning model.

    For production use, the implementation must also address privacy, cache management, failure handling, cost, latency, transcription accuracy, context limits, and the clear reporting of missing information. When a task depends on exact visual details, direct multimodal reasoning or structured source data remains the better choice.