> ## Documentation Index
> Fetch the complete documentation index at: https://docs.vlm.run/llms.txt
> Use this file to discover all available pages before exploring further.

# Visual Grounding

> Connect text elements with their visual locations in documents for precise content understanding

Connect text elements with their visual locations in documents for precise content understanding. Perfect for interactive document analysis, content verification, automated form filling, and document comparison workflows.

<Frame caption="Visual Grounding Example showing text-to-visual element mapping with highlighted connections.">
  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', alignItems: 'stretch' }}>
    <div style={{ gridRow: 'span 2' }}>
      <div style={{ textAlign: 'center', }}>Document Form</div>

      <img src="https://mintcdn.com/autonomiai/7LCH2ZD074tEU8dT/agents/assets/visual-grounding-form.jpg?fit=max&auto=format&n=7LCH2ZD074tEU8dT&q=85&s=d7eab8339f01fb58ee4e3d3f765dab42" alt="Document form grounding example" style={{ width: '100%', height: '100%', objectFit: 'contain', border: '1px solid #ddd', borderRadius: '4px' }} width="1587" height="2048" data-path="agents/assets/visual-grounding-form.jpg" />
    </div>

    <div>
      <div style={{ textAlign: 'center', }}>Driver's License</div>

      <img src="https://mintcdn.com/autonomiai/7LCH2ZD074tEU8dT/agents/assets/visual-grounding-id.jpg?fit=max&auto=format&n=7LCH2ZD074tEU8dT&q=85&s=c73e895a487ce6a8f8612a6e3760ad44" alt="Example of a driver's license document with visual grounding" style={{ width: '100%', height: '100%', objectFit: 'contain', border: '1px solid #ddd', borderRadius: '4px' }} width="1000" height="633" data-path="agents/assets/visual-grounding-id.jpg" />
    </div>

    <div>
      <div style={{ textAlign: 'center', }}>TV News Broadcast Text</div>

      <img src="https://mintcdn.com/autonomiai/QgYI_B3eAc6URNVd/agents/assets/visual-grounding-tv.jpg?fit=max&auto=format&n=QgYI_B3eAc6URNVd&q=85&s=7b3f99e5ebbb682f07bdbd5f469b2617" alt="TV news broadcast grounding example" style={{ width: '100%', height: '100%', objectFit: 'contain', border: '1px solid #ddd', borderRadius: '4px' }} width="1453" height="760" data-path="agents/assets/visual-grounding-tv.jpg" />
    </div>
  </div>
</Frame>

## Usage Example

<Tip>
  For best results, we recommend using the [Structured Outputs API](/agents/structured-responses) to get responses in a structured and validated data format.
</Tip>

<Info title="Document Visual Grounding">
  The following examples can map text elements to their visual locations, detect spatial relationships, and identify cross-references in documents. The response schema includes bounding boxes, confidence scores, and relationship types.
</Info>

<CodeGroup>
  ```python Python theme={"theme":{"light":"github-light","dark":"dark-plus"}}
  from vlmrun.client import VLMRun

  # Initialize the VLMRun client
  client = VLMRun(api_key="<VLMRUN_API_KEY>")

  # Perform visual grounding
  response = client.agent.completions.create(
      model="vlmrun-orion-1:auto",
      messages=[
          {
            "role": "user",
            "content": [
              {"type": "text", "text": "Localize all the speaker names in the TV news broadcast text and visualize them on the image. Only provide one bounding box for each speaker name."},
              {"type": "image_url", "image_url": {"url": "https://storage.googleapis.com/vlm-data-public-prod/hub/examples/media.tv-news/finance_bb_3_speakers.jpg", "detail": "auto"}}
            ]
          }
      ]
  )

  print(response.choices[0].message.content)
  # >>> {"elements": [{"content": "HAIDI STROUD-WATTS", "xywh": [0.428, 0.217, 0.128, 0.286]}, ...]}
  ```

  ```python Python - Structured Outputs theme={"theme":{"light":"github-light","dark":"dark-plus"}}
  from vlmrun.client import VLMRun
  from pydantic import BaseModel, Field

  # Define the response schema
  class GroundingWithText(BaseModel):
    content: str = Field(..., description="The text content")
    xywh: tuple[float, float, float, float] = Field(..., description="Bounding box (x, y, w, h)")

  class GroundingResponse(BaseModel):
    elements: list[GroundingWithText] = Field(..., description="Text to visual mappings")

  # Initialize the VLMRun client
  client = VLMRun(api_key="<VLMRUN_API_KEY>")

  # Perform visual grounding with structured output
  response = client.agent.completions.create(
      model="vlmrun-orion-1:auto",
      messages=[
          {
            "role": "user",
            "content": [
              {"type": "text", "text": "Localize all the speaker names in the TV news broadcast text and visualize them on the image. Only provide one bounding box for each speaker name."},
              {"type": "image_url", "image_url": {"url": "https://storage.googleapis.com/vlm-data-public-prod/hub/examples/media.tv-news/finance_bb_3_speakers.jpg", "detail": "auto"}}
            ]
          }
      ],
      response_format={"type": "json_schema", "schema": GroundingResponse.model_json_schema()},
  )

  # Validate the response
  result = GroundingResponse.model_validate_json(response.choices[0].message.content)
  # >>> GroundingResponse(elements=[GroundingWithText(content="...", xywh=(...)), ...])
  ```

  ```typescript Node.js theme={"theme":{"light":"github-light","dark":"dark-plus"}}
  import { VlmRun } from "vlmrun";

  const client = new VlmRun({
    apiKey: "<VLMRUN_API_KEY>",
    baseURL: "https://api.vlm.run/v1"
  });

  const response = await client.agent.completions.create({
    model: "vlmrun-orion-1:auto",
    messages: [
      {
        role: "user",
        content: [
          { type: "text", text: "Localize all the speaker names in the TV news broadcast text and visualize them on the image. Only provide one bounding box for each speaker name." },
          { type: "image_url", image_url: { url: "https://storage.googleapis.com/vlm-data-public-prod/hub/examples/media.tv-news/finance_bb_3_speakers.jpg", detail: "auto" } }
        ]
      }
    ]
  });

  console.log(response.choices[0].message.content);
  ```

  ```typescript Node.js - Structured Outputs [expandable] theme={"theme":{"light":"github-light","dark":"dark-plus"}}
  import { VlmRun } from "vlmrun";
  import { z } from "zod";
  import { zodToJsonSchema } from "zod-to-json-schema";

  // Define the response schema with Zod
  const GroundingResponseSchema = z.object({
    elements: z.array(z.object({
      content: z.string().describe("The text content"),
      xywh: z.array(z.number()).describe("Bounding box (x, y, w, h)")
    })).describe("Text to visual mappings")
  });

  // Initialize the VLMRun client
  const client = new VlmRun({
    apiKey: "<VLMRUN_API_KEY>",
    baseURL: "https://api.vlm.run/v1"
  });

  // Perform visual grounding with structured output
  const response = await client.agent.completions.create({
    model: "vlmrun-orion-1:auto",
    messages: [
      {
        role: "user",
        content: [
          { type: "text", text: "Localize all the speaker names in the TV news broadcast text and visualize them on the image. Only provide one bounding box for each speaker name." },
          { type: "image_url", image_url: { url: "https://storage.googleapis.com/vlm-data-public-prod/hub/examples/media.tv-news/finance_bb_3_speakers.jpg", detail: "auto" } }
        ]
      }
    ],
    response_format: {
      type: "json_schema",
      schema: zodToJsonSchema(GroundingResponseSchema)
    }
  });

  const result = GroundingResponseSchema.parse(JSON.parse(response.choices[0].message.content));
  ```
</CodeGroup>

## FAQ

<AccordionGroup>
  <Accordion title="What types of text-visual mappings are supported?" icon="link">
    * **Form Fields**: Connect labels with input fields, checkboxes, and buttons
    * **Data Fields**: Map data labels with their corresponding values
    * **Interactive Elements**: Link text instructions with clickable elements
    * **Validation Rules**: Connect validation text with form fields
    * **Cross-References**: Map text mentions with figures, tables, and sections
  </Accordion>

  <Accordion title="What format do the bounding boxes come in?" icon="crop">
    The bounding boxes come in the format of `xywh`, where `x` and `y` are the top-left corner coordinates, and `w` and `h` are the width and height of the bounding box. All values are in pixels relative to the document image.
  </Accordion>

  <Accordion title="What spatial relationships can be detected?" icon="arrows-split-up-and-left">
    * **Label-Field Pairs**: Identify which labels belong to which fields
    * **Hierarchical Structure**: Understand parent-child relationships
    * **Proximity Analysis**: Determine related elements based on spatial proximity
    * **Alignment Patterns**: Detect aligned elements and groups
  </Accordion>

  <Accordion title="What is the confidence score?" icon="percent">
    The confidence score is a value between 0 and 1 that indicates the confidence of the text-visual mapping. Higher scores indicate more reliable connections.
  </Accordion>

  <Accordion title="Can it process multi-page documents?" icon="file">
    Yes, visual grounding can process multi-page documents. Each page is analyzed separately, and the results include page-specific mappings and relationships.
  </Accordion>
</AccordionGroup>
