When extracting information from documents, knowing where the information is located can be as important.
This is useful for verification, highlighting the source in the UI, or further processing.
The API provides a location_granularity parameter to control the precision of the coordinate extraction.
Mode
Description
element(default)
Returns the coordinates of the entire HTML element (e.g., a table cell, a paragraph) containing the extracted value. This is faster and sufficient for general localization.
word
Returns the word-level coordinates of the specific words referenced by the extracted value. This is more granular but may take slightly longer.
all
Returns both the element-level and word-level coordinates.
To get location coordinates, you need to specify location as true and location_granularity in the extra_body of your request.
When location is set to true, the response includes tool_calls with the function name additional_values.
The arguments of this function call contain the extracted values along with their location coordinates.
The parsed result will be as below according to the location_granularity set in the request.
Element mode (location_granularity="element")
In this mode, the response includes coordinates which represent the bounding box of the element. The coordinates are relative values (0.0 to 1.0) based on the page size.
You can visualize the extracted coordinates on the original document image using Python and PIL.
from PIL import Image, ImageDrawimport jsondef plot_coordinates(image_path, response): # Load image img = Image.open(image_path) draw = ImageDraw.Draw(img) width, height = img.size # Parse response if not response.choices[0].message.tool_calls: print("No extraction result found.") return tool_call = response.choices[0].message.tool_calls[0] parsed_result = json.loads(tool_call.function.arguments) def draw_polygon(coords, color): if not coords: return # Scale coordinates to image size scaled_coords = [(x * width, y * height) for x, y in coords] # Draw polygon with outline draw.polygon(scaled_coords, outline=color, width=3) def traverse(data): if isinstance(data, dict): # Draw if coordinates exist if 'coordinates' in data: draw_polygon(data['coordinates'], 'red') if 'word_coordinates' in data: for word_poly in data['word_coordinates']: draw_polygon(word_poly, 'blue') # Recursively traverse all values for value in data.values(): traverse(value) elif isinstance(data, list): for item in data: traverse(item) traverse(parsed_result) # Display image img.show()# Example Usage# image_path = 'document.jpg'# plot_coordinates(image_path, response)