Recognizing images with Sherpa AI Server models through the API and Sherpa Designer#
VLM OCR models help extract text from a scanned document or photograph while retaining headings, tables and numbers in the response. The result can then be processed by a Robot or another integration.
This article shows two ways to send an image to Sherpa AI Server for recognition: a Python API request and a Robot project in Sherpa Designer. The server performs recognition, and the result is saved to a file or a Robot variable. Configuring the model and API token in the server web interface is a prerequisite covered in the linked articles below. This example does not cover Chat or recognition through the Documents screen.
A VLM (Vision-Language Model) accepts both text and images. A specialized OCR model, such as olmOCR-2-7B-1025-FP8, can be used for recognition. The Sherpa AI Server administrator defines the exact name of the available model.
Preparing the connection#
A connection configured in advance routes the image to the intended OCR model.
On the Models screen, the administrator must provide an accessible image-capable model and a working model instance. Model types, instances and object folders are described in the Models screen guide.
A direct request requires a valid API token with permission to call the method within its account. Token creation and authentication methods are described in the API screen guide.
The API example requires Python 3.10 or later and Pillow to create the sample image. The HTTP request itself uses only the Python standard library. The Sherpa AI Server address must be reachable from the computer running the example.
Sample image for recognition#
The sample invoice helps verify that the model has retained the table rows and total amount.
Example: creating a sample invoice.
Create the sample image yourself. No prepared file is needed. Create an empty working directory and run this command there to install Pillow:
python -m pip install "Pillow>=10.1"
Save the following code as create_invoice.py in this directory. It creates fictional invoice number 42 with two items: Pen, 2 units at 50 RUB, and Pencil, 1 unit at 30 RUB. The total is 130 RUB.
from PIL import Image, ImageDraw, ImageFont
image = Image.new("RGB", (1300, 860), "white")
draw = ImageDraw.Draw(image)
font = ImageFont.load_default(size=30)
heading = ImageFont.load_default(size=44)
draw.text((70, 55), "DEMO INVOICE No. 42", font=heading, fill="black")
draw.text((70, 130), "Training example - fictional data only", font=font, fill="black")
draw.text((70, 194), "Currency: RUB", font=font, fill="black")
for y in (280, 355, 445, 535):
draw.line((70, y, 1230, y), fill="black", width=2)
for x in (70, 590, 780, 1050, 1230):
draw.line((x, 280, x, 535), fill="black", width=2)
rows = [
(298, ("Item", "Qty", "Unit price", "Amount")),
(379, ("Pen", "2", "50", "100")),
(469, ("Pencil", "1", "30", "30")),
]
for y, cells in rows:
for x, text in zip((85, 610, 800, 1070), cells):
draw.text((x, y), text, font=font, fill="black")
draw.text((70, 615), "TOTAL: 130 RUB", font=heading, fill="black")
image.save("vlm-ocr-invoice-42.png")
print("Saved: vlm-ocr-invoice-42.png")
Run the command below to create the image. The file vlm-ocr-invoice-42.png appears in the current directory. Open it in an image viewer and compare it with the illustration: number 42, the Pen and Pencil rows, amounts 100 and 30, and a total of 130 RUB.
python create_invoice.py

Recognition through the API#
This method retrieves image text in your application without creating a Chat in the Sherpa AI Server portal.
Before running the example, set the following environment variables:
SHERPA_AI_URL— your Sherpa AI Server address, for examplehttps://aiserver.example.com, without the API path.SHERPA_AI_TOKEN— the secret of a valid API token. Supply it through the secure settings of the execution environment.SHERPA_AI_MODEL— the name of an available model. This variable is optional: the example defaults toolmOCR-2-7B-1025-FP8.
Save the code as ocr_image.py next to the sample image:
import base64
import json
import os
from pathlib import Path
from urllib.request import Request, urlopen
base_url = os.environ["SHERPA_AI_URL"].rstrip("/")
api_token = os.environ["SHERPA_AI_TOKEN"]
model = os.environ.get("SHERPA_AI_MODEL", "olmOCR-2-7B-1025-FP8")
image = base64.b64encode(Path("vlm-ocr-invoice-42.png").read_bytes()).decode("ascii")
payload = {
"model": model,
"messages": [{"role": "user", "content": [
{"type": "text", "text": "Read the text in the image. Return Markdown preserving document headings, tables and numbers. Do not invent missing values."},
{"type": "image_url", "image_url": {"url": "data:image/png;base64," + image}}
]}],
"temperature": 0,
"max_tokens": 2000,
"stream": False
}
request = Request(
base_url + "/api/v1/threads/chat/completions",
data=json.dumps(payload).encode("utf-8"),
headers={"Authorization": "Bearer " + api_token,
"Content-Type": "application/json"},
method="POST"
)
with urlopen(request, timeout=300) as response:
result = json.load(response)
choice = result["choices"][0]
Path("ocr-result.md").write_text(choice["message"]["content"], encoding="utf-8")
print("finish_reason:", choice.get("finish_reason"))
print("Saved: ocr-result.md")
Run the example from that directory:
python ocr_image.py
The request is sent with POST to /api/v1/threads/chat/completions. One user message contains the task text and the image in image_url. The file is read on the computer running the example, encoded as Base64 and sent with the image/png MIME type.
The example parameters control processing:
temperature: 0— reduces variation in the generated response.max_tokens: 2000— limits response length. A long page may require a higher value within the model's context limit.stream: false— returns the complete response at once.timeout=300— sets a network timeout of 300 seconds.
On success, the server returns HTTP 200. The application saves choices[0].message.content to ocr-result.md in the current directory. For the sample image, verify invoice number 42, both table items and the total of 130 RUB.
The model may return the table as Markdown or HTML. Check the values regardless of the response formatting.
Requests from Sherpa Designer#
Recognition can be included in a Robot project so that subsequent automation steps can use the extracted text.
Connection and custom model selection are described in the guide to model requests from Sherpa Designer. Use the image created in the previous section. The example path is C:\OCR\vlm-ocr-invoice-42.png: create the image in C:\OCR or replace the path with the full path to your working directory on the Robot computer.
The following block and property names are from Sherpa Designer 1.44. "Chat Completions" is in the "Sherpa AI Server. Model requests" palette.
Example: recognizing the sample invoice in Sherpa Designer.
Prepare three variables in "Start":
Variable1—$OcrHistory,Value1—$null: reset the history before processing the image.Variable2—$OcrRoles,Value2—@("user";"user"): roles for the two history rows.Variable3—$OcrContents,Value3— the expression below: task text and the full path to the generated image.
@("Read all text in this invoice. Preserve the table and total.";"C:\OCR\vlm-ocr-invoice-42.png")
Start block: preparing three OCR history variables. Add "List To DataTable". Set
List*to$OcrRoles,ColumnNameto"role", andResultto$OcrHistory. The block creates a DataTable with two rows and arolecolumn.
List To DataTable block: the role column and shared result variable. Add another "List To DataTable" block. Set
ColumnNameto"content"andResultto the same$OcrHistoryvariable. SetList*to$OcrContents. The block adds thecontentcolumn to the existing DataTable while retaining therolecolumn.
List To DataTable block: the content column in the same history table. Add "Chat Completions". The model name must exactly match an available name on your server. Set the following properties:
- property
InTable—$OcrHistory: the table from the two preceding blocks: task text and image path. - property
Model— "Sherpa AI Server": routes the request to Sherpa AI Server. - property
CustomModelName—"olmOCR-2-7B-1025-FP8": selects the available OCR model. Replace the string if its name differs. - property
Temperature—0: reduces response variation. - property
MaxLength—2000: limits the response to 2000 tokens. - property
Timeout—300: waits up to 300 seconds for the response. - property
ResponseContent—$OcrText: stores recognized text for subsequent blocks.
Leave
ContentSystemandContentUserempty: the history already contains the task. This example does not fillStop,TopP,Tools,ToolChoice, orStructuredOutput. Turn offAutoLengthLimitto use the specified response limit.
Chat Completions block: InTableinput and OCR model selection.
Chat Completions block: Temperature,MaxLengthandAutoLengthLimit.
Chat Completions block: response limit, optional parameters and Timeout.
Chat Completions block: ResponseContentis bound to $OcrText.- property
After the request, add "Log". Set
WriteToLogto"ROWS=" + $OcrHistory.Rows.Count + "; TEXT=" + $OcrText. Leave screenshot capture, forwarding logs or screenshots to Orchestrator, and status display disabled. The sample response appears in the local Log panel.Connect the blocks in this order and end the chain with "End". Run the project. In the Log panel, check invoice number 42,
Pen— 2 × 50 = 100,Pencil— 1 × 30 = 30, and the total of 130 RUB. The$OcrTextvariable holds the same response for subsequent blocks. A failed request does not verify recognition.The Log entry must begin with
ROWS=2. Double-click the entry to open the full response: it must contain both invoice items and a total of 130 RUB. Table formatting can vary. The response shown here uses HTML.
Full Log entry: two history rows, invoice number 42 and a total of 130 RUB.
Processing a PDF one page at a time#
Sending pages individually helps retain the order of the recognized text and repeat processing for only the page that needs it.
For this scenario, first convert the PDF into page images. In Sherpa Designer, this is covered by the "Render document to images" article. Then perform the following steps:
- Keep the original PDF page order.
- Prepare a separate image and recognition request for each page.
- Save each response with its page number.
- Combine the checked results in the original document order.
In the API example, image_url contains an image. A path to a PDF on the user's computer does not send the file or its pages to the server. Start with one page per request: image size, response length and available model context affect processing capacity.
If the server returns HTTP 400 with decoder prompt ... is longer than the maximum model length, the image and instruction exceed the model's available context. Increasing MaxLength does not fix this cause: the property limits the response length, not the input image size.
Before retrying, reduce the page image while preserving its aspect ratio, for example with the "Scale Image" block. A width of 1300 pixels was tested with the sample invoice. This is an example setting, not a universal limit: choose the size for your document and model while keeping small text legible. Keep the original PDF separate from the prepared images.
OCR during file upload and indexing in the portal is configured on the Documents screen. Recognition modes and OCR model selection for PDFs are already covered by the Documents screen guide.
Checking the result#
Checking the response helps detect missing rows and incorrect values before using them in a Robot.
After recognition, perform these checks:
- Compare numbers, dates, amounts and table-cell values with the image. The sample invoice total must be 130 RUB.
- Check that the response is complete. A
finish_reason: lengthvalue indicates that generation stopped at a length limit. Check the response limit and the available model context. - Evaluate results on your own document types. Scan quality, page rotation, small text, handwritten notes and complex layouts can affect recognition.
If a request fails, check server availability, the API token and its permissions, the exact OCR model name, its running instance and the Base64 image. HTTP 200 confirms that the request was executed. Verify recognized data against the source page.